Applying a For Loop to a matrix

Hi, I am very new to Matlab. I am struggling writing a For Loop to apply certain equations to each cell in a matrix. E.g. I have written the code; for i=1:100 PhaseAngle=atand((AngularVelocity(i,1))/K2(i+1,1)); end
in which AngularVelocity is a matrix of 1 column and 100 rows, K2 is a matrix of 1 column and 101 rows (which is why it is i+1 so it ignores the first column)
I want to to apply atand(angularvelocity/K2) for each row, however the PhaseAngle answer is overwritten every time for each cell. I need the answers in the same form as a 1 column 100 row matrix.
Also how would I do the same for a rolling summation equation;
xsumcos1=0; ysumsin1=0;
for j=1:100
xsumcos1=xsumcos1+cos(CouplingAngle1(j,1));
ysumsin1=ysumsin1+sin(CouplingAngle1(j,1));
end
Thank you in advance!

답변 (1개)

Mischa Kim
Mischa Kim 2014년 5월 3일
편집: Mischa Kim 2014년 5월 3일

2 개 추천

Alex, use
for ii = 1:100
PhaseAngle(ii) = atand(AngularVelocity(ii)/K2(ii+1));
end
I recommend using ii as the loop index rather than i, which is the imaginary unit in MATLAB. You can use the same approach for the other loop. Also, for large arrays you might want to pre-allocate memory before executing the loop:
PhaseAngle = zeros(size(AngularVelocity));

댓글 수: 5

alex
alex 2014년 5월 3일
Hey, thanks that worked for the first equation but for the second I got the error message 'In an assignment A(I) = B, the number of elements in B and I must be the same.'
Mischa Kim
Mischa Kim 2014년 5월 3일
편집: Mischa Kim 2014년 5월 3일
For the second loop you need to access the corresponding vector elements, something like:
xsumcos1(1) = 0;
ysumsin1(1) = 0;
for jj = 1:100 % same thing here, j is also used as the imag. unit
xsumcos1(jj+1) = xsumcos1(jj) + cos(CouplingAngle1(jj));
ysumsin1(jj+1) = ysumsin1(jj) + sin(CouplingAngle1(jj));
end
alex
alex 2014년 5월 3일
편집: alex 2014년 5월 3일
Yes! that works great. I have made an error in my calculations though.
I have 3 matrices of Coupling angles (CA1,CA2,CA3) all 100x1.
I want to get the sum of cos(CA1)+cos(CA2)+cos(CA3) and the sum of sin(CA1)+sin(CA2)+sin(CA3) How would I do that? Would I put all the Coupling Angle Matrices together to one matrix? and write code something like;
A=(CA1,CA2,CA3) % making the matrix
for jj=3:100
xsumcos(jj)=cos(CA1)+cos(CA2)+cos(CA3)
ysumsin(jj)=sin(CA1)+sin(CA2)+sin(CA3)
end
Thank you again!
In this case you can simply do:
A = [CA1 CA2 CA3];
xsumcos = sum(cos(A),2);
ysumsin = sum(sin(A),2);
alex
alex 2014년 5월 4일
Thank you very much for your help!

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2014년 5월 3일

댓글:

2014년 5월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by