MATLAB Programming and Scripting 5 — Questions and Answers
Question 1: Which MATLAB function returns the size of an array along a specific dimension?
- length(A, dim)
- numel(A, dim)
- size(A, dim) (Correct answer)
- ndims(A, dim)
Correct answer: size(A, dim)
size(A, dim) returns the length of array A along the specified dimension.
Question 2: What does the tilde '~' symbol mean when used as a function output argument in MATLAB?
- The output is mandatory
- The output is ignored/discarded (Correct answer)
- The output is returned as a logical
- The output is negated
Correct answer: The output is ignored/discarded
Using '~' as a placeholder output argument tells MATLAB to discard that output without storing it.
Question 3: In MATLAB, which type of file has the '.m' extension and contains only commands (no function definition)?
- Function file
- Class file
- Script file (Correct answer)
- Package file
Correct answer: Script file
A script file (.m) contains a sequence of MATLAB commands that execute in the calling workspace, unlike function files which define functions.
Question 4: What does 'cellfun(@numel, C)' return for a cell array C?
- A cell array of element counts per cell
- A numeric array where each element is the number of elements in the corresponding cell (Correct answer)
- The total number of elements across all cells
- A logical array
Correct answer: A numeric array where each element is the number of elements in the corresponding cell
cellfun applies a function to each cell and by default returns a numeric array of the scalar results.
Question 5: How do you add a new field 'age' with value 30 to an existing structure variable 'person'?
- person.add('age', 30)
- person->age = 30
- person.age = 30 (Correct answer)
- addfield(person, 'age', 30)
Correct answer: person.age = 30
MATLAB adds a new field to a struct using dot notation assignment: person.age = 30.
Question 6: Which keyword ends a function, for loop, while loop, if block, and switch block in MATLAB?
- done
- endblock
- end (Correct answer)
- finish
Correct answer: end
The 'end' keyword terminates all control flow constructs and function definitions in MATLAB.
Question 7: What is the result of logical short-circuit evaluation using '&&' vs '&' in MATLAB?
- They are identical for all inputs
- '&&' short-circuits scalar operands and skips evaluating the right side if the left is false; '&' always evaluates both sides element-wise (Correct answer)
- '&' short-circuits; '&&' does not
- '&&' is for arrays; '&' is for scalars
Correct answer: '&&' short-circuits scalar operands and skips evaluating the right side if the left is false; '&' always evaluates both sides element-wise
'&&' performs short-circuit AND on scalars, skipping the right operand when the left is false; '&' always evaluates both operands element-wise.
Which MATLAB function returns the size of an array along a specific dimension?