Asked by Marisabel Gonzalez
on 6 Apr 2019

The following piece of code only plots 4 points and it should plot 5 (not 6 because two points overlap). I was wondering if you could tell me how to fix it.

A = [5;5;5;3;3;2];

B = [10;4;10;10;4;4];

for n = 1:length(A)

if A(n) == 5

plot(A(n),B(n),'rx')

elseif A(n) == 3

hold on

plot(A(n),B(n),'bx')

else

hold on

plot(A(n),B(n),'gx')

end

end

axis([0 10 0 20])

Please note that I want to use if staments.

The output should be:

But the bottom red point is missing when using the code above...

Answer by John D'Errico
on 6 Apr 2019

Edited by John D'Errico
on 6 Apr 2019

Accepted Answer

Let me explain separately, since you are misssing the point.

The important point is NOT that there are duplicated points at (5,10). That is irrelevant. What matters is there is NOT a hold on, established after the first call to plot. So look at the flow:

- The point (5,10) is plotted.
- The point (5,4) is plotted, BUT as a new plot, because hold on was not employed. If you just call plot TWICE in a row, without a hold on in between the previous plot figure is deleted.
- The point (5,10) is plotted AGAIN. But again, the last plot gets zapped into the bit bucket.
- Finally, a point at (3,10) is plotted, but before this is done, hold is set to on. So now future points are plotted on the same set of axes. You need not set hold to on again for this set of axes. Hold stays on, until it is turned off, or until the figure is deleted.
- Since hold is now on, the remaining points are plotted. A total of 4 points are seen.

In fact, 6 points were plotted. But the first two points were lost in the bit bucket. It has nothing to do with the replicated point, but with the failure to issue a hold on immediately.

Your code never hits the call to hold UNTIL the 4th point was plotted on those axes, because the first three calls all had A(n)==5. In your code, hold is never set in the block where A(n)==5. Repeated calls to plot will delete the previous figure if hold is not set to on.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## John D'Errico (view profile)

Direct link to this comment:https://de.mathworks.com/matlabcentral/answers/454789-data-point-missing-in-if-statement#comment_690613

Sign in to comment.