MATLAB Programming and Scripting 2 — Questions and Answers
Question 1: What does the 'nargin' function return inside a MATLAB function?
- Number of output arguments
- Number of input arguments provided by the caller (Correct answer)
- Total number of defined parameters
- Number of optional arguments
Correct answer: Number of input arguments provided by the caller
'nargin' returns the number of input arguments actually passed by the caller at runtime.
Question 2: Which MATLAB construct is used to handle errors gracefully without stopping execution?
- if-else block
- try-catch block (Correct answer)
- switch-case block
- while loop with break
Correct answer: try-catch block
A try-catch block catches runtime errors and lets execution continue in the catch branch.
Question 3: In MATLAB, what is the result of evaluating 'mod(7, 3)'?
- 2
- 1 (Correct answer)
- 3
- 0
Correct answer: 1
mod(7,3) returns 1 because 7 = 2*3 + 1.
Question 4: How do you define a nested function in MATLAB?
- Place a function inside another function's body before its 'end' keyword (Correct answer)
- Use the '@' operator inside a function file
- Create an anonymous function inside the caller
- Nest function files inside a folder named after the parent function
Correct answer: Place a function inside another function's body before its 'end' keyword
Nested functions are defined inside another function's body and must use explicit 'end' statements.
Question 5: What does the 'persistent' keyword do when used inside a MATLAB function?
- Saves the variable to the workspace permanently
- Retains the variable's value between function calls (Correct answer)
- Makes the variable globally accessible
- Prevents the variable from being overwritten
Correct answer: Retains the variable's value between function calls
A persistent variable retains its value across multiple calls to the same function, similar to a static variable in C.
Question 6: Which operator is used for element-wise multiplication in MATLAB?
- *
- .* (Correct answer)
- &*
- x*
Correct answer: .*
The '.*' operator performs element-by-element multiplication, unlike '*' which performs matrix multiplication.
Question 7: What is the output of 'class(int32(5))' in MATLAB?
- double
- int32 (Correct answer)
- integer
- numeric
Correct answer: int32
The class() function returns the data type name as a string, so it returns 'int32' for an int32 value.
What does the 'nargin' function return inside a MATLAB function?