Data point missing in if statement
1 次查看(过去 30 天)
显示 更早的评论
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...
1 个评论
John D'Errico
2019-4-6
编辑:John D'Errico
2019-4-6
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.
采纳的回答
John D'Errico
2019-4-6
编辑:John D'Errico
2019-4-6
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.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!