MATLAB Answers

## Data point missing in if statement

Asked by Marisabel Gonzalez

### Marisabel Gonzalez (view profile)

on 6 Apr 2019
Latest activity Commented on by Marisabel Gonzalez

### Marisabel Gonzalez (view profile)

on 6 Apr 2019
Accepted Answer by John D'Errico

### John D'Errico (view profile)

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...

John D'Errico

### John D'Errico (view profile)

on 6 Apr 2019
And why exactly did you feel it necessary to post the same identical question two days in a row? Your first question got an answer. If you post it again, I will start closing the new ones. Just get someone to clarify things, rather than posting over and over again.

Sign in to comment.

R2018a

## 1 Answer

### John D'Errico (view profile)

Answer by John D'Errico

### John D'Errico (view profile)

on 6 Apr 2019
Edited by John D'Errico

### John D'Errico (view profile)

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:
1. The point (5,10) is plotted.
2. 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.
3. The point (5,10) is plotted AGAIN. But again, the last plot gets zapped into the bit bucket.
4. 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.
5. 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.

#### 1 Comment

Marisabel Gonzalez

### Marisabel Gonzalez (view profile)

on 6 Apr 2019
Thanks John!

Sign in to comment.