Plotting a line using a FOR loop
9 views (last 30 days)
Show older comments
sourestdeeds
on 26 Nov 2016
Commented: Star Strider
on 26 Nov 2016
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 Comments
Accepted Answer
Star Strider
on 26 Nov 2016
Edited: Star Strider
on 26 Nov 2016
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 Comments
Star Strider
on 26 Nov 2016
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.)
More Answers (1)
Walter Roberson
on 26 Nov 2016
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.
See Also
Categories
Find more on Graphics Performance in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!