A loop within a loop (for or if)
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi
I want to create a 3x3 matrix.I have a question regarding changing a value in an equation when i=the lenght of the column, which is 3.
The code so far:
Cm = [Cm1 Cm2 Cm3];
P = 3000
for i=1:3
D2(i) = -(D1(i)+0.5); %mm
Cg(i) = (D1(i)*D2(i))/(D1(i)+D2(i));
a1(i) = 0.721*(P*Cg(i)*Cm(1)).^(1/3); %mm
a2(i) = 0.721*(P*Cg(i)*Cm(2)).^(1/3); %mm
a3(i) = 0.721*(P*Cg(i)*Cm(3)).^(1/3); %mm
end
It works, if i manually change Cm. By doing it like this i can get a 3x3 matrix from:
a = [a1(:) a2(:) a3(:)]
But I want the Cm to change automatically. What to do? :S
Regards Tim
1 Kommentar
KSSV
am 8 Nov. 2016
Undefined function or variable 'D1'.
Error in first (line 4) D2(i) = -(D1(i)+0.5); %mm
Antworten (2)
Ganesh Hegade
am 8 Nov. 2016
Bearbeitet: Ganesh Hegade
am 8 Nov. 2016
Hi,
I didn't get exactly what you are trying to do. Hope this works.
Cm = [Cm1 Cm2 Cm3];
P = 3000
for i=1:3 % Better to use length(Cm)
D2(i) = -(D1(i)+0.5); %mm
Cg(i) = (D1(i)*D2(i))/(D1(i)+D2(i));
a1(i) = 0.721*(P*Cg(i)*Cm(i)).^(1/3); %mm
a2(i) = 0.721*(P*Cg(i)*Cm(i)).^(1/3); %mm
a3(i) = 0.721*(P*Cg(i)*Cm(i)).^(1/3); %mm
end
a = [a1', a2', a3' ];
1 Kommentar
Guillaume
am 8 Nov. 2016
I don't particularly understand your question. All I know is you don't need a loop to generate your final a.
I assume your D1 that is not shown is a 1x3 row vector. Then,
D2 = -(D1 + 0.5); %note that numbering variables is never a good idea
Cg = D1 .* D2 ./ (D1 + D2);
%if using R2016b:
a = 0.721 * (P * Cg.' * Cm) .^ (1/3);
%if using an earlier version:
a = 0.721 * (P * bsxfun(@times, Cg.', Cm)) .^ (1/3);
Note that if D1 is a 3x1 column vector, then you don't need to transpose Cg in the a calculation.
If you want to calculate a for different Cm vectors, again you don't need a loop. Simply concatenate all these Cm vectors in the third dimension and the above will still work.
0 Kommentare
Siehe auch
Kategorien
Find more on Loops and Conditional Statements in Help Center and File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!