Creating an array from nested while loop

1 view (last 30 days)
Adam Doty
Adam Doty on 2 May 2015
Answered: Jan on 3 May 2015
I have a motion analysis problem I need to do, but I don't know how to create an array that will store all the possible values after I complete the calculation. In essence, Im trying to create an array from two different vectors. The following script is what I have.
% Input Variables
P=1;
B=15;
y=25;
a=20;
%while loop for y=5:24
while y>4
y=25-P
% While loop for B=15:90
while B<91
z(y,B)=(a^2+y^2-2*a*y*cos(B*(pi/180))).^.5;
Sigma(y,B)=acos((y^2-a^2-z(y,B).^2)/(-2*a.*z(y,B)));
Sigmad(y,B)=Sigma(y,B)*(180/pi);
B=B+1;
end
P(y)=P+1
end
z=z(z~=0);
Sigmad=Sigmad(Sigmad~=0);
I believe it may be a syntax issue, but I'm not too familiar with how matlab deals with its matrix/array syntax.
  3 Comments
Adam Doty
Adam Doty on 2 May 2015
I want it to create a 24x76 array (specifically for z and sigmad) storing all the values for the ranges indicated. Now it just gives me column vectors for those two. Strangely, it gives me the array I want for sigma, but populated with mostly zeroes.
Adam Doty
Adam Doty on 2 May 2015
It seems like no matter what I do, the data is only stored into an array on the last run of the my "y-loop". Any help to solve this issue would be SSSSSOOOOOOO appreciated. Its been boggling my mind for days now.

Sign in to comment.

Answers (1)

Jan
Jan on 3 May 2015
The loops look very strange:
P=1;
y=25;
while y>4
y=25-P
...
P(y)=P+1
end
P becomes a vector in P(y)=P+1 and inthe 2nd iteration y is a vector also. The inner loop would fail with the error message, that y^2 is not valid, because you can only square scalars and square matrices. But this error does not appear, because B is still 92 from the first iteration of the outer loop.
Therefore I assume that there are 2 problems concerning the loops. Better use clear and clean for loops instead of the while loops. What about this:
a=20;
for y=5:24
for B=15:90
z(y,B) = sqrt(a^2+y^2-2*a*y*cos(B*(pi/180)));
Sigma(y,B) = acos((y^2-a^2-z(y,B).^2)/(-2*a.*z(y,B)))*(180/pi);
end
end
z=z(z~=0);
Sigmad=Sigmad(Sigmad~=0);
Perhaps you need some adjustments of the loop counters.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!