Free MATLAB Programming and Scripting Questions and Answers — Questions and Answers
Question 1: What is the final value of the variable `total` after the following MATLAB code is executed? ```matlab total = 0; data = [10, -5, 20, 0, -15, 30]; for k = 1:length(data) if data(k) < 0 continue; end total = total + data(k); end disp(total); ```
- 60 (Correct answer)
- 40
- 75
- An error will occur because `continue` is not a valid command.
Correct answer: 60
The `continue` statement skips the remainder of the current loop iteration and proceeds to the next one. When the loop encounters a negative number (-5 and -15), the `continue` command is executed, skipping the `total = total + data(k);` line for that iteration. Therefore, only the non-negative numbers are added: 10 + 20 + 0 + 30 = 60.
Question 2: Which of the following lines of code correctly defines an anonymous function named `vol` that calculates the volume of a sphere (4/3 * pi * r^3) and then correctly calls it for a radius of 5?
- vol = function(r) 4/3*pi*r^3; result = vol(5);
- vol = @(r) 4/3*pi*r^3; result = vol(5); (Correct answer)
- function vol(r) = 4/3*pi*r^3; result = vol(5);
- vol = @(r) 4/3*pi*r^3; result = @vol(5);
Correct answer: vol = @(r) 4/3*pi*r^3; result = vol(5);
Anonymous functions in MATLAB are defined using the `@` symbol, followed by the input arguments in parentheses, and then the expression to be executed. The variable `vol` becomes a function handle, which is then called like a regular function by passing the input argument in parentheses, `vol(5)`.
Question 3: A programmer needs to store a character vector 'Test', a numeric vector `[1 2 3]`, and a 2x2 matrix `magic(2)` together in a single 1x3 container variable. Which data structure is most appropriate, and how is the numeric vector `[1 2 3]` correctly accessed from the container named `C`?
- A structure; accessed with `C.data2`
- A standard matrix; accessed with `C(1,2)`
- A cell array; accessed with `C{2}` (Correct answer)
- A table; accessed with `C(:,2)`
Correct answer: A cell array; accessed with `C{2}`
A cell array is the ideal data structure for collecting dissimilar types of data. To access the *contents* of a specific cell (e.g., to retrieve the numeric vector itself), you must use curly braces `{}` for indexing. Parentheses `()` would return a 1x1 cell array containing the vector, not the vector itself.
Question 4: Which of the following best describes the primary purpose of a `try-catch` block in MATLAB programming?
- To validate user input from the `input` function by attempting different data type conversions.
- To preallocate memory for an array to improve performance before entering a loop.
- To define a conditional block of code that runs only if a specific logical variable is true.
- To allow code that might produce a runtime error to execute, and to run a separate block of code if an error occurs, preventing the program from crashing. (Correct answer)
Correct answer: To allow code that might produce a runtime error to execute, and to run a separate block of code if an error occurs, preventing the program from crashing.
The `try-catch` statement provides a mechanism for robust error handling. MATLAB executes the statements in the `try` block. If a runtime error occurs, execution of the `try` block is stopped, and the statements in the `catch` block are executed instead of the program terminating with an error message.
Question 5: Why is preallocating an array before it is populated inside a `for` loop a recommended best practice in MATLAB for improving performance?
- It ensures the array elements are all integers, which are processed faster than floating-point numbers.
- It prevents MATLAB from having to repeatedly find new contiguous blocks of memory and copy all existing data as the array grows within the loop. (Correct answer)
- It is a required syntax for using the `parfor` (Parallel Computing Toolbox) construct.
- It automatically initializes all array elements to a non-zero value, which prevents `NaN` (Not-a-Number) errors during calculations.
Correct answer: It prevents MATLAB from having to repeatedly find new contiguous blocks of memory and copy all existing data as the array grows within the loop.
When an array is not preallocated, MATLAB must dynamically resize the array every time a new element is added. This resizing process involves finding a new, larger, contiguous block of memory and copying all the old elements to the new location. This operation is computationally expensive and can severely slow down code, especially for loops with many iterations.
Question 6: Given the following string array: `fileNames = ["data_01.csv", "notes.txt", "data_02.csv", "backup_data.zip"]` Which command will return a logical array `[1 0 1 1]` indicating which elements contain the substring "data"?
- `find(fileNames, "data")`
- `strcmp(fileNames, "data")`
- `contains(fileNames, "data")` (Correct answer)
- `ischar(fileNames, "data")`
Correct answer: `contains(fileNames, "data")`
The `contains` function is specifically designed to search for a substring within each element of a string array or cell array of character vectors. It returns a logical array of the same size as the input, with `true` (1) for elements that contain the substring and `false` (0) for those that do not. `strcmp` is used for exact, full-string comparisons, not for finding substrings.
What is the final value of the variable `total` after the following MATLAB code is executed?
```matlab
total = 0;
data = [10, -5, 20, 0, -15, 30];
for k = 1:length(data)
if data(k) < 0
continue;
end
total = total + data(k);
end
disp(total);
```