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
2014년 5월 3일
편집: Mischa Kim
2014년 5월 3일
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
2014년 5월 3일
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
Mischa Kim
2014년 5월 4일
In this case you can simply do:
A = [CA1 CA2 CA3];
xsumcos = sum(cos(A),2);
ysumsin = sum(sin(A),2);
alex
2014년 5월 4일
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!