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!

Respuestas (1)

Mischa Kim
Mischa Kim el 3 de Mayo de 2014
Editada: Mischa Kim el 3 de Mayo de 2014
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 comentarios

alex
alex el 3 de Mayo de 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 el 3 de Mayo de 2014
Editada: Mischa Kim el 3 de Mayo de 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 el 3 de Mayo de 2014
Editada: alex el 3 de Mayo de 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 el 4 de Mayo de 2014
Thank you very much for your help!

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 3 de Mayo de 2014

Comentada:

el 4 de Mayo de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by