Plotting a line using a FOR loop
12 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
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 个评论
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
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Performance 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!