Applying a For Loop to a matrix
Mostra commenti meno recenti
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!
Risposte (1)
Mischa Kim
il 3 Mag 2014
Modificato: Mischa Kim
il 3 Mag 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 Commenti
alex
il 3 Mag 2014
Mischa Kim
il 3 Mag 2014
Modificato: Mischa Kim
il 3 Mag 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
Mischa Kim
il 4 Mag 2014
In this case you can simply do:
A = [CA1 CA2 CA3];
xsumcos = sum(cos(A),2);
ysumsin = sum(sin(A),2);
alex
il 4 Mag 2014
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!