MATLAB Functions and Flow Control 2 — Questions and Answers
Question 1: What keyword is used to terminate a loop or switch statement early in MATLAB?
- return
- exit
- break (Correct answer)
- stop
Correct answer: break
The `break` statement immediately exits the innermost for or while loop.
Question 2: What does the `nargin` function return inside a MATLAB function?
- Number of output arguments
- Number of input arguments passed by the caller (Correct answer)
- Maximum number of allowed inputs
- Names of input variables
Correct answer: Number of input arguments passed by the caller
`nargin` returns the number of input arguments actually provided when the function was called.
Question 3: Which syntax correctly defines a MATLAB function that returns two output values?
- function [a, b] = myfunc(x) (Correct answer)
- function (a, b) = myfunc(x)
- function myfunc(x) returns [a, b]
- function a, b = myfunc(x)
Correct answer: function [a, b] = myfunc(x)
Multiple return values are declared with square brackets: `function [a, b] = myfunc(x)`.
Question 4: In a `switch` statement, what block handles all cases not matched by any `case`?
- default
- else
- otherwise (Correct answer)
- catch
Correct answer: otherwise
The `otherwise` block in a MATLAB switch statement handles unmatched cases.
Question 5: What happens when `continue` is used inside a for loop in MATLAB?
- Exits the loop immediately
- Skips to the next iteration (Correct answer)
- Restarts the loop from the beginning
- Pauses execution
Correct answer: Skips to the next iteration
`continue` skips the remaining statements in the current iteration and proceeds to the next one.
Question 6: Which MATLAB function allows you to call a function by its name stored as a string?
- eval()
- feval() (Correct answer)
- call()
- invoke()
Correct answer: feval()
`feval('funcname', args)` evaluates the named function with the given arguments.
Question 7: What is the output of the following code? for k = 1:3 if k == 2, continue; end disp(k) end
- 1 2 3
- 1 3 (Correct answer)
- 2
- 1 2
Correct answer: 1 3
`continue` skips `disp(k)` when k==2, so only 1 and 3 are displayed.
What keyword is used to terminate a loop or switch statement early in MATLAB?