Borrar filtros
Borrar filtros

constructing matrix with loop

2 visualizaciones (últimos 30 días)
sermet
sermet el 20 de Mzo. de 2016
Comentada: sermet el 20 de Mzo. de 2016
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 comentarios
Stephen23
Stephen23 el 20 de Mzo. de 2016
Editada: Stephen23 el 20 de Mzo. de 2016
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 el 20 de Mzo. de 2016
any proper way you suggest to create all sum_i?

Iniciar sesión para comentar.

Respuesta aceptada

Stephen23
Stephen23 el 20 de Mzo. de 2016
Editada: Stephen23 el 20 de Mzo. de 2016
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
>>
  1 comentario
sermet
sermet el 20 de Mzo. de 2016
thank you very much Stephen.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by