A loop within a loop (for or if)

조회 수: 9 (최근 30일)
Tim Tolman
Tim Tolman 2016년 11월 8일
편집: Guillaume 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
KSSV 2016년 11월 8일
Undefined function or variable 'D1'.
Error in first (line 4) D2(i) = -(D1(i)+0.5); %mm

댓글을 달려면 로그인하십시오.

답변 (2개)

Ganesh Hegade
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
Guillaume 2016년 11월 8일
편집: 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
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by