Plotting a line using a FOR loop

9 visualizzazioni (ultimi 30 giorni)
sourestdeeds
sourestdeeds il 26 Nov 2016
Commentato: Star Strider il 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?

Risposta accettata

Star Strider
Star Strider il 26 Nov 2016
Modificato: Star Strider il 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 Commenti
Walter Roberson
Walter Roberson il 26 Nov 2016
Remember to put in a drawnow() after the plot() call
Star Strider
Star Strider il 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.)

Accedi per commentare.

Più risposte (1)

Walter Roberson
Walter Roberson il 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.

Categorie

Scopri di più su Graphics Performance in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by