constructing matrix with loop

1 次查看(过去 30 天)
I have 3 matrix consist of numeric values as follows;
XY_j=[Xj_ref, Yj_ref]; %consists of 2 column and 40 rows (40x2)
XY_orj=[x_orj, y_orj]; %consists of 2 column and 205 rows (205x2)
C; %consists of one column and 40 rows (40x1)
I need to form below calculation with loop;
for i=1:40
Ne_sum_1(i)=C_matrix(i)*(sqrt((x_orj(1)-Xj_ref(i))^2+(y_orj(1)-Yj_ref(i))^2));
Ne_sum_2(i)=C_matrix(i)*(sqrt((x_orj(2)-Xj_ref(i))^2+(y_orj(2)-Yj_ref(i))^2));
Ne_sum_3(i)=C_matrix(i)*(sqrt((x_orj(3)-Xj_ref(i))^2+(y_orj(3)-Yj_ref(i))^2));
.
.
.
Ne_sum_205(i)=C_matrix(i)*(sqrt((x_orj(205)-Xj_ref(i))^2+(y_orj(205)-Yj_ref(i))^2));
end
sum_1=(sum(Ne_sum_1));
sum_2=(sum(Ne_sum_2));
sum_3=(sum(Ne_sum_3));
.
.
.
sum_205=(sum(Ne_sum_205));
After the above calculation 205 Ne_sum are created. How can I modify above computation with loop?
  2 个评论
Stephen23
Stephen23 2016-3-20
编辑:Stephen23 2016-3-20
The most important step is to realize that creating lots of separate variables is a really bad way to program. You should never create (or access) numbered variables like that, this is very slow and buggy. Here is why:
sermet
sermet 2016-3-20
any proper way you suggest to create all sum_i?

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2016-3-20
编辑:Stephen23 2016-3-20
Here is an efficient way of performing that calculation. Note that I did not use any slow, buggy, and awful dynamic variable names. I did not even waste my time using a loop. Instead I used the very fast and handy MATLAB function bsxfun. Beginners always think that creating and accessing lots of variables is a great idea: it isn't. Use the dimensions of arrays instead, and your code will be neater, faster, and more robust.
% Fake data:
Xjref = rand(40,1);
Yjref = rand(40,1);
Xorj = rand(205,1);
Yorj = rand(205,1);
C = rand(40,1);
% Calculate sum:
Xtmp = bsxfun(@minus,Xorj,Xjref.').^2;
Ytmp = bsxfun(@minus,Yorj,Yjref.').^2;
out = sum(bsxfun(@times,C.',sqrt(Xtmp+Ytmp)),2);
And checking the output:
>> size(out)
ans =
205 1
>> out
out =
12.307
13.103
8.6913
7.4902
9.2776
9.8368
... lots more here
11.505
10.511
13.673
11.405
>>

更多回答(0 个)

类别

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