MATLAB Programming and Scripting 4 — Questions and Answers
Question 1: How do you preallocate a 100x100 matrix of zeros in MATLAB?
- M = null(100,100)
- M = zeros(100,100) (Correct answer)
- M = empty(100,100)
- M = allocate(100,100)
Correct answer: M = zeros(100,100)
zeros(m,n) creates an m-by-n matrix of double-precision zeros, which is the standard preallocating technique.
Question 2: In MATLAB, what does the colon operator 1:2:10 generate?
- [1 2 3 4 5 6 7 8 9 10]
- [1 3 5 7 9] (Correct answer)
- [2 4 6 8 10]
- [1 2 10]
Correct answer: [1 3 5 7 9]
The syntax start:step:end generates [1 3 5 7 9] — values from 1 to 10 with step 2.
Question 3: Which statement correctly defines a function handle in MATLAB?
- f = function(x) x^2
- f = @(x) x^2 (Correct answer)
- f = lambda x: x^2
- f = def(x) x^2 end
Correct answer: f = @(x) x^2
The '@(x) x^2' syntax creates an anonymous function handle in MATLAB.
Question 4: What does 'fieldnames(S)' return when S is a MATLAB structure?
- The values of all fields
- A cell array of field name strings (Correct answer)
- The number of fields
- A struct with field metadata
Correct answer: A cell array of field name strings
fieldnames() returns a cell array of character vectors, each containing one field name of the struct.
Question 5: Which MATLAB function evaluates a string as a MATLAB expression?
- run()
- exec()
- eval() (Correct answer)
- parse()
Correct answer: eval()
eval() executes the MATLAB code contained in a character vector or string.
Question 6: How does 'continue' differ from 'break' inside a MATLAB loop?
- continue exits the loop; break skips to the next iteration
- continue skips to the next iteration; break exits the loop (Correct answer)
- They are interchangeable
- continue restarts the loop from the beginning
Correct answer: continue skips to the next iteration; break exits the loop
'continue' skips the rest of the current iteration and moves to the next one, while 'break' exits the loop entirely.
Question 7: What is the purpose of the 'inputParser' class in MATLAB?
- Parsing command-line arguments at startup
- Validating and parsing function input arguments with named parameters and defaults (Correct answer)
- Reading structured text files
- Converting user input from the command window
Correct answer: Validating and parsing function input arguments with named parameters and defaults
inputParser provides a systematic way to define required, optional, and name-value pair arguments with validation for functions.
How do you preallocate a 100x100 matrix of zeros in MATLAB?