MATLAB Script and Function Creation 5 — Questions and Answers
Question 1: What is the correct way to call a function stored in a function handle `fh` with argument `3`?
- fh(3) (Correct answer)
- call(fh, 3)
- invoke fh with 3
- fh->call(3)
Correct answer: fh(3)
A function handle is called using standard parenthesis syntax, just like a regular function call.
Question 2: Which MATLAB command adds a folder to the search path so functions in it can be found?
- addpath('folderName') (Correct answer)
- path add 'folderName'
- include('folderName')
- import folderName
Correct answer: addpath('folderName')
`addpath` appends or prepends a directory to MATLAB's search path at runtime.
Question 3: In MATLAB, what is the output of `class(@sin)`?
- 'function_handle' (Correct answer)
- 'double'
- 'char'
- 'builtin'
Correct answer: 'function_handle'
`@sin` creates a function handle, and `class()` reports its type as `'function_handle'`.
Question 4: How do you suppress output from a MATLAB statement inside a script or function?
- End the statement with a semicolon (;) (Correct answer)
- Wrap it in suppress()
- Assign it to ans
- Prefix it with quiet:
Correct answer: End the statement with a semicolon (;)
A trailing semicolon prevents MATLAB from printing the result of a statement to the command window.
Question 5: What is the purpose of `validateattributes` in a MATLAB function?
- To check that input arguments satisfy specified class and attribute constraints (Correct answer)
- To document the function's inputs for help text
- To convert inputs to a required data type automatically
- To count the number of attributes in a struct
Correct answer: To check that input arguments satisfy specified class and attribute constraints
`validateattributes` checks that a variable belongs to the correct class and meets size/value constraints, throwing an error if not.
Question 6: Which statement correctly defines a function that takes no inputs and returns no outputs in MATLAB?
- function myFunc() (Correct answer)
- void myFunc()
- def myFunc():
- function [] myFunc
Correct answer: function myFunc()
A zero-input, zero-output MATLAB function uses `function functionName()` with empty parentheses.
Question 7: When debugging a MATLAB function, `dbstop if error` causes the debugger to:
- Pause execution at the point where any error occurs (Correct answer)
- Suppress all errors silently
- Stop the MATLAB session completely
- Skip error-prone lines automatically
Correct answer: Pause execution at the point where any error occurs
`dbstop if error` sets a breakpoint that pauses execution at the exact line that throws an error, allowing inspection of the workspace.
What is the correct way to call a function stored in a function handle `fh` with argument `3`?