How can i plot ALL values produced from while loop from the following code??

3 views (last 30 days)
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

Answers (3)

the cyclist
the cyclist on 20 Oct 2013
Simple way to modify your code:
  • 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.
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
Phoebe on 20 Oct 2013
I did what you said so my amended code reads;
clear q=-1; m=1; 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; n=0; 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];
n=n+1;
v1=vpost+(((q*E)/m)*h);
r1=(dt*v1)+r0;
x(n)=r1(1);
y(n)=r1(2);
t=t+dt;
r1=r0;
v1=v0;
end plot(x,y,'mo') hold on;
same problem of a single point??
  1 Comment
the cyclist
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.

Sign in to comment.


Luis Pinto
Luis Pinto on 29 Mar 2018
Edited: Luis Pinto on 29 Mar 2018
just add the command "drawnow" at the end of the loop.

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!