MATLAB Functions and Flow Control 3 — Questions and Answers
Question 1: What is a MATLAB anonymous function?
- A function defined in a separate .m file without a name
- A short function defined inline using the @() syntax (Correct answer)
- A function that accepts no arguments
- A private function inside a class
Correct answer: A short function defined inline using the @() syntax
Anonymous functions use the `@(args) expression` syntax and are defined inline without a separate file.
Question 2: Which of the following correctly creates an anonymous function that squares its input?
- sq = function(x) x^2
- sq = @(x) x^2 (Correct answer)
- sq = @x x^2
- sq(x) = x^2
Correct answer: sq = @(x) x^2
The anonymous function syntax is `@(input_args) expression`, so `@(x) x^2` is correct.
Question 3: What does `nargout` return inside a MATLAB function?
- Number of arguments the function accepts
- Number of output values requested by the caller (Correct answer)
- Total outputs the function can return
- Number of inputs minus outputs
Correct answer: Number of output values requested by the caller
`nargout` returns how many output arguments the caller requested when invoking the function.
Question 4: In MATLAB, what is a nested function?
- A function that calls itself recursively
- A function defined inside another function's body (Correct answer)
- A function stored in a subfolder
- A lambda expression
Correct answer: A function defined inside another function's body
A nested function is defined within the body of another (parent) function and shares its workspace.
Question 5: How does MATLAB handle a `while` loop when the condition is false from the start?
- Executes the body once then stops
- Throws an error
- Never executes the loop body (Correct answer)
- Asks the user for input
Correct answer: Never executes the loop body
If the while condition is false initially, MATLAB skips the loop body entirely without executing it.
Question 6: Which statement correctly ends a function definition in a MATLAB function file containing multiple functions?
- exit
- endfunction
- end (Correct answer)
- stop
Correct answer: end
The `end` keyword closes a function definition when multiple functions share one file.
Question 7: What is the purpose of `varargin` in a MATLAB function definition?
- Specifies a variable number of input arguments (Correct answer)
- Declares a variable as global
- Lists optional output arguments
- Defines default argument values
Correct answer: Specifies a variable number of input arguments
`varargin` allows a function to accept a variable number of input arguments, collected into a cell array.
What is a MATLAB anonymous function?