a loop problem in matlab

조회 수: 2 (최근 30일)
James_111
James_111 2019년 1월 10일
편집: madhan ravi 2019년 1월 10일
My code is:
for p=1:0.01:2;
plot3(p,p.^2,p.^3);
end
I want to use a loop of p to create a three dimentional figure. while no error occurs, the figure is strange. I simplify my code into the above code. Any help is very appreciated! Thanks.
  댓글 수: 2
Adam Danz
Adam Danz 2019년 1월 10일
A solution was provided below but it does not explain why your code doesn't work and that's the important part.
There are two problems.
1) When you're plotting in a loop (which often can be avoided), you need to 'hold' the axes to prevent the plot from being over-written on each iteration. That would look something like this:
figure
ah = axes;
hold(ah, 'on')
for
plot(ah, x, y)
end
2) On each iteration of your for-loop, you're plotting a single point and since you didn't specify a marker type, plot3 is trying to draw a line. You can't draw a line with a single point which is why your plot ended up completely empty. One solution would have been to specify a marker type :
plplot3(p, p.^2, p.^3, 'bo')
But the best solution is to avoid the loop altogether as is demonstrated in the answer below.
James_111
James_111 2019년 1월 10일
Thank you so much for your detailed explaination. Maybe I should post my competed code again. My code has a fzero function makes it more complicated.

댓글을 달려면 로그인하십시오.

채택된 답변

madhan ravi
madhan ravi 2019년 1월 10일
편집: madhan ravi 2019년 1월 10일
Without loop:
p=1:0.01:2;
plot3(p,p.^2,p.^3); % no loops needed
grid on
With loop:
p=1:0.01:2;
h = animatedline;
grid on
view(3); % lookup doc
for i=1:numel(p)
addpoints(h,p(i),p(i)^2,p(i)^3);
drawnow
end
  댓글 수: 2
James_111
James_111 2019년 1월 10일
편집: madhan ravi 2019년 1월 10일
madhan ravi
madhan ravi 2019년 1월 10일
편집: madhan ravi 2019년 1월 10일
Anytime :) , sure let me try and sorry I missed your reply there , let me get some sleep and then get back to you there.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Graphics Performance에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by