Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

Views expressed in these public forums are not endorsed by Drexel University or The Math Forum.


Math Forum » Discussions » Software » comp.soft-sys.matlab

Topic: Making a loop
Replies: 4   Last Post: Jun 10, 2013 1:06 PM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Derek Goring

Posts: 3,892
Registered: 12/7/04
Re: Making a loop
Posted: Jun 10, 2013 4:56 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

On Monday, June 10, 2013 8:18:08 PM UTC+12, Dylan wrote:
> I am trying to make a loop that will store the values of theta and r in arrays so I can make a plot using the polar command. It is supposed to be a plot of the orbit of Mercury using initial force. I have used a similar loop to plot projectile motion. Unfortunately I keep receiving this error:
>
>
>
> In an assignment A(I) = B, the number of elements in B and I must be the same.
>
>
>
> Can anyone give me some advice as what I should do? Here is the code:
>
>
>
> m=3.285*10^23;
>
> rp=46*10^9;
>
> vp=58977;
>
> M=1.989*10^30;
>
> G=6.67384*10^-11;
>
> Frp=m.*M.*G./rp.^2;
>
> ptheta=0.1;
>
>
>
> L=m*rp*vp;
>
> v=vp;r(1)=rp;Fr=Frp;theta(1)=ptheta;
>
>
>
> k=1;dt=.1;
>
> while min(theta)> 0
>
> Fr=m.*M*G./r^.2;
>
> v=v+(-1./m.*Fr+L.^2./(m.^2.*r.^3))*dt;
>
>
>
> r(k+1)=r(k)+v.*dt;
>
> theta(k+1)=theta(k)+L.^2./(m.*r.^2);
>
> t(k+1)=t(k)+dt;
>
> k=k+1;
>
>
>
> end
>
>
>
> polar (theta,r)


You are using r as a scalar, whereas it is in fact a vector.
Perhaps it should be r(k)^2?
Or perhaps there should be a summation to reduce r.^2 to a scalar?

Incidentally, this is a very inefficient way of doing things because the vectors r, theta and t are growing inside the loop. This means that every time you increment them they need to be re-written off to core in a contiguous block. If/when k gets large, the loop will slowly grind to a halt and Matlab will eventually crash.
Before the loop, you need to preallocate the vectors:
noit=10000;
r=zeros(noit,1);theta=r;t=r;
then inside the loop you need to break out when the iterations reach the limit:
if k == noit,break,end






Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.