# A loop within a loop (for or if)

1 ビュー (過去 30 日間)
Tim Tolman 2016 年 11 月 8 日

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 件のコメント表示非表示 なし
KSSV 2016 年 11 月 8 日
Undefined function or variable 'D1'.
Error in first (line 4) D2(i) = -(D1(i)+0.5); %mm

サインインしてコメントする。

### 回答 (2 件)

Ganesh Hegade 2016 年 11 月 8 日

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 件のコメント表示非表示 なし
Guillaume 2016 年 11 月 8 日
%Better to use length(Cm)
Actually, better to use numel(Cm). length is dangerous if the input is not a vector.
But of course, even better is not to use a loop...

サインインしてコメントする。

Guillaume 2016 年 11 月 8 日
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.

サインインしてコメントする。

### Community Treasure Hunt

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

Start Hunting!