MATLAB Functions and Flow Control 4 — Questions and Answers
Question 1: What type does `varargin` produce inside a MATLAB function?
- A numeric array
- A structure
- A cell array (Correct answer)
- A string array
Correct answer: A cell array
`varargin` collects extra input arguments into a cell array that can be indexed with {}.
Question 2: Which MATLAB construct should be used to catch and handle runtime errors?
- try...catch (Correct answer)
- if...else
- switch...otherwise
- do...while
Correct answer: try...catch
The `try...catch` block lets you intercept runtime errors and execute alternative code.
Question 3: What does `error('message')` do in MATLAB?
- Prints a warning and continues
- Throws a runtime error and halts execution (Correct answer)
- Logs the message to a file
- Displays a dialog box
Correct answer: Throws a runtime error and halts execution
`error()` raises an exception that stops execution unless caught by a try-catch block.
Question 4: In MATLAB, how do you pass a function as an argument to another function?
- Using the function name as a string only
- Using a function handle created with @ (Correct answer)
- By copying the function body inline
- Using the load() command
Correct answer: Using a function handle created with @
A function handle `@funcname` creates a reference to the function that can be passed as an argument.
Question 5: What is the result of calling a function handle `f = @(x) x + 1` with `f(4)`?
- 4
- 5 (Correct answer)
- 1
- Error
Correct answer: 5
The anonymous function adds 1 to its input, so `f(4)` returns 4 + 1 = 5.
Question 6: Which loop type is best suited when the number of iterations is not known in advance?
- for loop
- while loop (Correct answer)
- do-while loop
- switch loop
Correct answer: while loop
A `while` loop continues until its condition becomes false, making it ideal when iteration count is unknown.
Question 7: What does `return` do when used inside a MATLAB function?
- Exits MATLAB entirely
- Immediately exits the current function and returns to the caller (Correct answer)
- Restarts the function from the top
- Skips the current iteration
Correct answer: Immediately exits the current function and returns to the caller
`return` causes control to pass back to the calling function (or command prompt) immediately.
What type does `varargin` produce inside a MATLAB function?