MATLAB Script and Function Creation 2 — Questions and Answers
Question 1: What is the correct way to define a function that returns multiple output values in MATLAB?
- function [a, b] = myFunc(x) (Correct answer)
- function (a, b) = myFunc(x)
- function myFunc(x) returns [a, b]
- def myFunc(x) -> [a, b]:
Correct answer: function [a, b] = myFunc(x)
Multiple return values are declared in square brackets on the left side of the assignment in the function signature.
Question 2: Which command clears all variables from the MATLAB workspace at the start of a script?
- clear all (Correct answer)
- delete vars
- reset workspace
- flush()
Correct answer: clear all
`clear all` removes all variables, globals, and functions from the workspace.
Question 3: In a MATLAB function file, where must the primary function definition appear?
- At the top of the file before any other code (Correct answer)
- Anywhere in the file
- After all helper functions
- In a separate header block
Correct answer: At the top of the file before any other code
MATLAB requires the primary function to be the first function defined in a function file.
Question 4: What happens when a MATLAB script is run and a variable with the same name already exists in the workspace?
- The existing variable is overwritten (Correct answer)
- An error is thrown
- The script skips that assignment
- A new scope is created
Correct answer: The existing variable is overwritten
Scripts share the caller's workspace, so running a script overwrites any existing variable of the same name.
Question 5: Which keyword is used to exit a function early in MATLAB before reaching the end?
- return (Correct answer)
- exit
- break
- stop
Correct answer: return
`return` immediately exits the current function and returns control to the calling code.
Question 6: What does `nargin` return inside a MATLAB function?
- The number of input arguments passed by the caller (Correct answer)
- The number of output arguments requested
- The total number of declared inputs
- The index of the last argument
Correct answer: The number of input arguments passed by the caller
`nargin` returns the actual count of input arguments provided when the function was called.
Question 7: A local function defined inside a function file is accessible:
- Only by the functions in the same file (Correct answer)
- By any script in the current folder
- Globally across all MATLAB sessions
- Only from the MATLAB command window
Correct answer: Only by the functions in the same file
Local (subfunctions) are scoped to the file they are defined in and cannot be called from outside.
What is the correct way to define a function that returns multiple output values in MATLAB?