필터 지우기
필터 지우기

constructing matrix with loop

조회 수: 2 (최근 30일)
sermet
sermet 2016년 3월 20일
댓글: sermet 2016년 3월 20일
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
>>
  댓글 수: 1
sermet
sermet 2016년 3월 20일
thank you very much Stephen.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by