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