MATLAB Environment and Syntax 5 — Questions and Answers
Question 1: What is the effect of using `global x` inside a MATLAB function?
- Makes `x` read-only inside the function
- Shares `x` across the base workspace and all functions that declare it global (Correct answer)
- Exports `x` to a file automatically
- Converts `x` to a persistent variable
Correct answer: Shares `x` across the base workspace and all functions that declare it global
Declaring a variable `global` allows multiple functions and the base workspace to share the same instance of that variable.
Question 2: Which MATLAB command saves all current workspace variables to a `.mat` file named `data.mat`?
- export data.mat
- write('data.mat')
- save('data.mat') (Correct answer)
- store data.mat
Correct answer: save('data.mat')
`save('data.mat')` writes all workspace variables to a binary `.mat` file, which can later be restored with `load`.
Question 3: What does `nargin` return inside a MATLAB function?
- The maximum allowed number of inputs
- The actual number of input arguments passed by the caller (Correct answer)
- The number of output arguments
- The name of the first argument
Correct answer: The actual number of input arguments passed by the caller
`nargin` returns the count of input arguments that were actually provided when the function was called, enabling optional-argument patterns.
Question 4: In MATLAB, what does the `end` keyword represent when used as an array index?
- Zero (the first element)
- The last valid index of that dimension (Correct answer)
- One past the last index (for slicing)
- It is a syntax error in indexing
Correct answer: The last valid index of that dimension
When used inside indexing parentheses, `end` automatically resolves to the last index of the relevant array dimension.
Question 5: Which of the following correctly creates a row vector of integers from 1 to 10 with a step of 2?
- 1:2:10 (Correct answer)
- 1,2,10
- linspace(1,10,2)
- range(1,10,2)
Correct answer: 1:2:10
The colon operator `start:step:end` generates a vector; `1:2:10` produces [1 3 5 7 9].
Question 6: What is the result of `isinf(1/0)` in MATLAB?
- false (0)
- true (1) (Correct answer)
- NaN
- An error is thrown
Correct answer: true (1)
MATLAB evaluates `1/0` as `Inf` without error, and `isinf(Inf)` returns logical 1.
Question 7: What does the `persistent` keyword do in a MATLAB function?
- Makes the variable accessible from the Command Window
- Preserves the variable's value between calls to the function (Correct answer)
- Prevents the variable from being cleared
- Creates a read-only constant
Correct answer: Preserves the variable's value between calls to the function
A `persistent` variable retains its value between successive calls to the same function, similar to a static local variable in C.
What is the effect of using `global x` inside a MATLAB function?