MATLAB Script and Function Creation 3 — Questions and Answers
Question 1: What is the purpose of the `end` keyword at the close of a function definition in MATLAB?
- It marks the boundary of the function so local functions can follow (Correct answer)
- It returns the last computed value
- It is optional and has no effect
- It terminates the MATLAB session
Correct answer: It marks the boundary of the function so local functions can follow
Using `end` to close a function is required when the file contains more than one function, to delineate each function's scope.
Question 2: Which of the following correctly calls a function named `calcArea` with input `5` and captures its output?
- result = calcArea(5) (Correct answer)
- result <- calcArea(5)
- calcArea(5) -> result
- call calcArea(5) as result
Correct answer: result = calcArea(5)
Standard MATLAB function call syntax assigns the returned value using the equals sign.
Question 3: Anonymous functions in MATLAB are created using which syntax?
- f = @(x) x^2 (Correct answer)
- f = lambda x: x**2
- f = function(x) x^2 end
- f = def(x) x^2
Correct answer: f = @(x) x^2
The `@(args) expression` syntax defines an anonymous function inline without a separate file.
Question 4: What is the difference between a MATLAB script and a function regarding variable scope?
- Scripts share the base workspace; functions have their own private workspace (Correct answer)
- Functions share the base workspace; scripts have private scope
- Both share the same workspace
- Both have completely isolated workspaces
Correct answer: Scripts share the base workspace; functions have their own private workspace
Functions execute in their own workspace, isolating their variables from the base workspace, while scripts do not.
Question 5: How do you add a persistent variable inside a MATLAB function so it retains its value between calls?
- persistent varName (Correct answer)
- static varName
- global varName
- retain varName
Correct answer: persistent varName
`persistent` declares a variable that retains its value between successive calls to the function.
Question 6: What does `nargout` allow a function to determine?
- How many output arguments the caller requested (Correct answer)
- How many input arguments were passed
- The data type of the output
- Whether any output was suppressed with semicolons
Correct answer: How many output arguments the caller requested
`nargout` returns the number of output arguments requested by the calling expression, enabling conditional output generation.
Question 7: Which file extension is required for MATLAB function and script files?
- .m (Correct answer)
- .mat
- .mlx
- .mfun
Correct answer: .m
Standard MATLAB scripts and functions are saved with the `.m` extension; `.mat` is for data, `.mlx` is for live scripts.
What is the purpose of the `end` keyword at the close of a function definition in MATLAB?