A loop within a loop (for or if)
2 次查看(过去 30 天)
显示 更早的评论
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
编辑: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
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!