Plotting a line using a FOR loop

조회 수: 12 (최근 30일)
sourestdeeds
sourestdeeds 2016년 11월 26일
댓글: Star Strider 2016년 11월 26일
x = 0.75;
y = 0;
for n = 0 : 11
k = ( ( (-1).^n .* factorial(2.*n) ) / ( (1-2.*n )...
.* (factorial(n)).^2 .* (4).^n ) ) .* (x).^n;
y = y + k;
plot(n, y, '-o' , 'LineWidth', 1.5);
disp(['Result to ', num2str(n+1), ' terms is ',...
num2str(y, 11)]);
end
disp(['Direct evaluation of sqrt(1+', num2str(x, 10),...
') = ', num2str(sqrt(1+x), 11)]);
Using the above code I have tried so many things to plot a graph that connects lines, just plotting the dots works in the manner shown above in my code. I figure i have to store the values in an array somehow to plot the graph outside of the FOR loop but every attempt so far has failed. Is there an elegant way to modify what i have to plot a graph of each pass, connecting all the dots with a line?

채택된 답변

Star Strider
Star Strider 2016년 11월 26일
편집: Star Strider 2016년 11월 26일
One approach:
x = 0.75;
y = 0;
for n = 0 : 11
k = ( ( (-1).^n .* factorial(2.*n) ) / ( (1-2.*n )...
.* (factorial(n)).^2 .* (4).^n ) ) .* (x).^n;
y = y + k;
yv(n+1) = y; % <— STORE ‘y’ VALUES
disp(['Result to ', num2str(n+1), ' terms is ',...
num2str(y, 11)]);
end
disp(['Direct evaluation of sqrt(1+', num2str(x, 10),...
') = ', num2str(sqrt(1+x), 11)]);
plot([0:length(yv)-1], yv, '-o' , 'LineWidth', 1.5);
  댓글 수: 2
Walter Roberson
Walter Roberson 2016년 11월 26일
Remember to put in a drawnow() after the plot() call
Star Strider
Star Strider 2016년 11월 26일
That was an error. I intended to cut the plot call out of the loop and paste it at then end (with modifications) rather than copy it. The code works regardless.
The edited code eliminates the ambiguity. (The code is otherwise the same as I originally posted, except that the plot call now appears only after the loop.)

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2016년 11월 26일
plot() only draws a line when it is passed at least two non-infinite non-nan points in a single call. You are passing in only one point at a time. You can, as you discovered, add a marker, but you cannot get it to draw a line.
If you are using a sufficiently recent version you could use animatedline()
Otherwise, you will need to record the n and y values and plot() the vector of those values.
  댓글 수: 1
sourestdeeds
sourestdeeds 2016년 11월 26일
Going to read about animated line now :)

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

카테고리

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