MATLAB Answers

How can I run multiple iterations that plot on the same graph?

1 view (last 30 days)
Caleb Coombe
Caleb Coombe on 26 May 2021
Edited: Adam Danz on 28 May 2021
Hello all,
I want to take the equation:
4*x+((Dl*x^2)/2)-4
I would like to run 100 iterations of this equation with Dl starting as 1 and stepping by 1 until it reaches 100.
I would also like all of the lines of this equation to be plotted on the same graph.
Any suggestions on how to do this?
Thank you!

Answers (2)

Adam Danz
Adam Danz on 26 May 2021
Edited: Adam Danz on 28 May 2021
Using a vector of values x, y is an mxn matrix for m values in Dl and n values in x.
x = 1:5; % Row vector
Dl = 1:100; % row or column vector
y = 4*x+((Dl(:).*x.^2)./2)-4
y = 100×5
0.5000 6.0000 12.5000 20.0000 28.5000 1.0000 8.0000 17.0000 28.0000 41.0000 1.5000 10.0000 21.5000 36.0000 53.5000 2.0000 12.0000 26.0000 44.0000 66.0000 2.5000 14.0000 30.5000 52.0000 78.5000 3.0000 16.0000 35.0000 60.0000 91.0000 3.5000 18.0000 39.5000 68.0000 103.5000 4.0000 20.0000 44.0000 76.0000 116.0000 4.5000 22.0000 48.5000 84.0000 128.5000 5.0000 24.0000 53.0000 92.0000 141.0000
plot(x,y) % 100 lines with 5 x-values

Paul Hoffrichter
Paul Hoffrichter on 26 May 2021
Edited: Paul Hoffrichter on 26 May 2021
If you are new to Matlab programming, then you are probably used to a for-loop and you are plotting the curve in each iteration. If this is so, then all you have to do is add "hold on" to be associated with the figure.
x = -1:0.1:1; % setup x values
figure(101), clf, hold on;
ylim( [-10 55] ); % set y axis limits to keep the plot steady looking
grid on; grid minor;
for Dl = 1:100
y = 4*x + (Dl*x.^2)/2 - 4;
plot(x,y);
title( ['Iteration #: ' num2str(Dl) ] );
pause(0.1); % add this to see the effect of each iteration
end
figure(101), hold off;

Community Treasure Hunt

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

Start Hunting!