MATLAB: Constructing matrix with loop

bsxfundynamic variable namesefficientevalfor looploopmatrix manipulation

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?

Best Answer

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
>>
Related Question