How to grow a vector in a loop?
조회 수: 5 (최근 30일)
이전 댓글 표시
So I have two nested loops
for ii = 1:ldiv+1
for jj = 1:sdiv+1
x_m = sb_panel(ii,jj).xm;
y_m = sb_panel(ii,jj).ym;
z_m = sb_panel(ii,jj).zm;
for kk = 1:ldiv+1
for ll = 1:sdiv+1
x_a = sb_panel(kk,ll).xa;
y_a = sb_panel(kk,ll).ya;
z_a = sb_panel(kk,ll).za;
x_b = sb_panel(kk,ll).xb;
y_b = sb_panel(kk,ll).yb;
z_b = sb_panel(kk,ll).zb;
aa = 1/(((x_m-x_a)*(y_m-y_b)-(x_m-x_b)*(y_m-y_a)));
bb = ((x_b-x_a)*(x_m-x_a)+(y_b-y_a)*(y_m-y_a))/sqrt((x_m-x_a)^2+(y_m-y_a)^2);
cc = ((x_b-x_a)*(x_m-x_b)+(y_b-y_a)*(y_m-y_b))/sqrt((x_m-x_b)^2+(y_m-y_b)^2);
dd = (1/(y_a-y_m))*(1+(x_m-x_a)/sqrt((x_m-x_a)^2+(y_m-y_a)^2));
ee = (1/(y_b-y_m))*(1+(x_m-x_b)/sqrt((x_m-x_b)^2+(y_m-y_b)^2));
coeff = [(aa*(bb-cc)+dd-ee)];
end
end
end
end
The problem is the innermost loop runs as many times as it's supposed to and assigns the last value to 'coeff' but what I want is that each time it runs, it assigns a value to coeff, and then assign the value in next cell when it runs again.
댓글 수: 0
채택된 답변
Matt J
2021년 10월 15일
편집: Matt J
2021년 10월 15일
You could just vectorize everything.
x_m = [sb_panel.xm];
y_m = [sb_panel.ym];
z_m = [sb_panel.zm];
x_a = [sb_panel.xa].';
y_a = [sb_panel.ya].';
z_a = [sb_panel.za].';
x_b = [sb_panel.xb].';
y_b = [sb_panel.yb].';
z_b = [sb_panel.zb].';
aa = 1./(((x_m-x_a).*(y_m-y_b)-(x_m-x_b).*(y_m-y_a)));
bb = ((x_b-x_a).*(x_m-x_a)+(y_b-y_a).*(y_m-y_a))./sqrt((x_m-x_a).^2+(y_m-y_a).^2);
cc = ((x_b-x_a).*(x_m-x_b)+(y_b-y_a).*(y_m-y_b))./sqrt((x_m-x_b).^2+(y_m-y_b).^2);
dd = (1./(y_a-y_m)).*(1+(x_m-x_a)./sqrt((x_m-x_a).^2+(y_m-y_a).^2));
ee = (1./(y_b-y_m)).*(1+(x_m-x_b)./sqrt((x_m-x_b).^2+(y_m-y_b).^2));
coeff = reshape( aa.*(bb-cc)+dd-ee , [],1);
댓글 수: 2
Matt J
2021년 10월 15일
Can you point out my mistakes
In your original approach? My other answer describes how to get that to work.
and more insight into what you did?
we first collected the fields of your stucture into vectors
s(1).a=10; s(2).a=20; s(3).a=30;
v=[s.a]
Then, you just use implicit expansion for all the arithmetic operations, e.g.,
v+(1:4).'
추가 답변 (2개)
Scott MacKenzie
2021년 10월 15일
One approach is to declare coeff as an empty array before the first for-statement:
coeff = [];
then add new values to the end of the coeff array as follows:
coeff = [coeff, (aa*(bb-cc)+dd-ee)];
댓글 수: 2
Scott MacKenzie
2021년 10월 15일
In that case, just reverse the order in the assignment:
coeff = [(aa*(bb-cc)+dd-ee), coeff];
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!