I have a certain problem in Matlab, mine loops won't run, they just do the first loop and then just print out the results, it seems that looping has been disabled somehow, can anyone help? I have a few examples so I'll just post code down under.

1 visualizzazione (ultimi 30 giorni)
function solarni(m1,m2,dr,v1,v2,tmax,dt)
rp=1;
rc=(m1*rp+m2*sqrt(rp^2+dr^2))/(m1+m2);
r1=[sqrt(rc^2-rp^2)];
r2=[dr-r1];
v1x=[0];
v1y=[v1];
v2x=[0];
v2y=[-v2];
x1=[r1];
y1=[0];
x2=[-r2];
y2=[0];
t=[0];
j=[];
l=[];
while t(end)<tmax
x=x1(end)-x2(end);
y=y1(end)-y2(end);
r=sqrt(x^2+y^2);
j=[j x];
l=[l y];
v1=sqrt(v1x (end)^2+v1y (end)^2);
v2=sqrt(v2x (end)^2+v2y (end)^2);
v1xi=v1x(end)-(4*pi^2*m2*(x1(end)-x2(end))*dt)/r^3;
x1i=x1(end)+v1xi*dt;
v1yi=v1y(end)-(4*pi^2*m2*(y1(end)-y2(end))*dt)/r^3;
y1i=y1(end)+v1yi*dt;
v2xi=v2x(end)-(4*pi^2*m1*(x2(end)-x1(end))*dt)/r^3;
x2i=x2(end)+v2xi*dt;
v2yi=v2y(end)-(4*pi^2*m1*(y2(end)-y1(end))*dt)/r^3;
y2i=y2(end)+v2yi*dt;
v1x=[v1x v1xi];
x1=[x1 x1i];
v1y=[v1y v1yi];
y1=[y1 y1i];
v2x=[v2x v2xi];
x2=[x2 x2i];
v2y=[v2y v2yi];
y2=[y2 y2i];
r1=[r1 sqrt((x1(end))^2+(y1(end))^2)];
r2=[r2 sqrt((x2(end))^2+(y2(end))^2)];
t=[t t(end)+dt];
end
subplot(1,2,1)
plot(j,l);
title('Relativno kretanje prvog tela u odnosu na drugo');
subplot(1,2,2)
plot(x1,y1,'b');
title('Relativno kretanje pojedinacnih tela u odnosu na pocetni centar mase sistema');
hold on
plot(x2,y2,'r');
hold off
end
Im first time using this so I dont quite know if this is exact way for posting, if anyone can help, please help, thank you in advance
  1 Commento
dpb
dpb il 11 Giu 2014
Something else is going on...use the debugger to step thru the code and see why the condition is being satisfied before you think it should...a quick check here shows
>> dt=0.1;tmax=1;
>> t=[0];
while t(end)<tmax
...
t=[t t(end)+dt];
end
>> t
t =
Columns 1 through 8
0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000
Columns 9 through 12
0.8000 0.9000 1.0000 1.1000
One thing I will note is that you're dynamically reallocating all of your vectors through the loop; this will lead to serious degradation in performance as the number of iterations increases. You should rearrange to compute a bound for the sizes and preallocate then fill...
Something like
nIter=ceil(tmax/dt)+1;
t=zeros(nIter,1);
iter=0;
while ...
t(iter+1)=t(iter)+dt);
iter=iter+1;
...
end
More "Matlaby" would be to vectorize as
t=[0:dt:tmax].';
w/o a loop and then write the solution in vector form as well. I've got a meeting shortly so can't take more time at the moment...

Accedi per commentare.

Risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements 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