- Define a counter n (initialized to zero) before your while loop.
- Update n=n+1 in every iteration of your while loop.
- Set x(n) = r1(1) and y(n) = r1(2).
- Pull the plotting routine out of the while loop.
How can i plot ALL values produced from while loop from the following code??
3 views (last 30 days)
Show older comments
I have written the following code and wish to plot all values produced but at the moment it only gives one point
clear
q=-1;
m=3;
r0=[1 2 0];
v0=[2 2 0];
B=[0 0 1];
E=[0 0 0];
t=0;
dt=0.2;
h=dt/2;
tfinal=0.1;
while t<tfinal
vpre=v0+(((q*E)/m)*h);
b=norm(B,2);
t=(((q*b)/m)*h);
s=(2*t)/(1+(t^2));
vxpre=vpre(1);
vypre=vpre(2);
vdash=vxpre + (vypre*t);
vypost=vypre - (vdash*s);
vxpost=vdash + (vypost*t);
vpost=[vxpost vypost 0];
v1=vpost+(((q*E)/m)*h);
r1=(dt*v1)+r0;
x=r1(1);
y=r1(2);
plot(x,y,'mo')
hold on;
t=t+dt;
r1=r0;
v1=v0;
end
0 Comments
Answers (3)
the cyclist
on 20 Oct 2013
Simple way to modify your code:
If your while loop runs for many iterations, you will need to preallocate memory for x and y to make this run most efficiently.
Phoebe
on 20 Oct 2013
1 Comment
the cyclist
on 20 Oct 2013
I ran your while loop. It only has one iteration, so it only generates one point.
You seem to be using the variable "t" in two different ways inside your loop. Once to just count up
t = t + dt;
but also in a more complex way:
t=(((q*b)/m)*h);
That seems wrong to me, and may be why your loop expectedly exits after just one iteration.
Luis Pinto
on 29 Mar 2018
Edited: Luis Pinto
on 29 Mar 2018
just add the command "drawnow" at the end of the loop.
0 Comments
See Also
Categories
Find more on Line Plots 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!