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!

Antworten (1)

Mischa Kim
Mischa Kim am 3 Mai 2014
Bearbeitet: Mischa Kim am 3 Mai 2014

2 Stimmen

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 Kommentare

alex
alex am 3 Mai 2014
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 am 3 Mai 2014
Bearbeitet: Mischa Kim am 3 Mai 2014
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 am 3 Mai 2014
Bearbeitet: alex am 3 Mai 2014
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 am 4 Mai 2014
Thank you very much for your help!

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Tags

Gefragt:

am 3 Mai 2014

Kommentiert:

am 4 Mai 2014

Community Treasure Hunt

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

Start Hunting!

Translated by