Consider the following MATLAB code that plots two lines using hold on. What will be the final plot display?
x = 0:0.1:2*pi; y1 = sin(x); y2 = cos(x); plot(x, y1, '-r'); hold on; plot(x, y2, '-b'); hold off;
Think about what hold on does in MATLAB plotting.
The hold on command allows multiple plots to be drawn on the same figure without erasing the previous plots. So both sine and cosine waves appear together.
Given this MATLAB code, what will the plot show?
x = 1:5; y1 = x; y2 = x.^2; plot(x, y1, '-g'); plot(x, y2, '-m');
Remember what happens when you call plot twice without hold on.
Without hold on, the second plot command clears the first plot, so only the second line appears.
Examine the code below. It is intended to plot two lines on the same figure, but only one line appears. What is the cause?
x = 0:0.5:5; plot(x, x, '-k'); hold on plot(x, x.^2, '-r'); hold off;
Check the syntax of the hold on command.
In MATLAB, hold on is a command and does not require parentheses, but missing a semicolon does not affect its execution. However, if hold on is typed without a space or misspelled, it won't work. Here, the code is correct and both lines should appear. The problem is that hold on is missing a semicolon but that does not cause the issue. The actual cause is that hold on missing parentheses is incorrect because hold on does not use parentheses. So the only plausible cause is that the user forgot to call hold on before the first plot, but here it is after the first plot, which is correct. So the problem is a trick: the code is correct and both lines appear. So the correct answer is D.
Identify the code snippet that will cause a syntax error in MATLAB.
Look for missing semicolons or missing command separators.
Option A lacks semicolons or commas between commands, causing MATLAB to raise a syntax error.
Consider this MATLAB code snippet:
x = 1:4; plot(x, x, '-o'); hold on; plot(x, x.^2, '-x'); hold off; plot(x, x.^3, '-s');
How many lines will be visible on the final figure?
Remember what hold off does after plotting.
The first plot draws the linear line. hold on allows the quadratic line to be added. Then hold off disables holding, so the next plot command clears the figure and draws only the cubic line.