Info

この質問は閉じられています。 編集または回答するには再度開いてください。

change nested for to vectorise

1 回表示 (過去 30 日間)
Mani Ahmadian
Mani Ahmadian 2014 年 10 月 22 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
Hi
I have a 100*100 grid as below:
xgrid=1:100;
ygrid=1:100;
I have 5 data points in this grid(x,y) as below,too:
X=[10 20 30 40 50];
Y=[55 65 75 85 95];
to compute distances of each node from these data points,I use a nested for structure as:
deltaX=zeros(100,100,length(X));
deltaY=zeros(100,100,length(X));
for ii=1:length(X)
for jj=1:100
for kk=1:100
deltaX(jj,kk,ii)=X(ii)-xgrid(kk);
deltaY(jj,kk,ii)=Y(ii)-ygrid(kk);
end
end
end
deltaY=permute(deltaY,[2 1 3]);
distance1=hypot(deltaX,deltaY);
distancegrid=zeros(100,100,length(X));
distancegrid=squeeze(distance1);
I want to remove this nested for structure and vectorise my code. How it's possible to do?
Thanks a lot
Mani

回答 (2 件)

David Sanchez
David Sanchez 2014 年 10 月 22 日
xgrid=1:100;
ygrid=1:100;
X=[10 20 30 40 50];
Y=[55 65 75 85 95];
% to start with, there is no need of a 3D matrix.
% you result is the same along your jj dimension
deltaX=zeros(100,length(X));
deltaY=zeros(100,length(X));
% and you can vectorize like this
for ii=1:length(X)
deltaX(:,ii)=X(ii)-xgrid;
deltaY(:,ii)=Y(ii)-ygrid;
end
  1 件のコメント
Mani Ahmadian
Mani Ahmadian 2014 年 10 月 22 日
Dear David
Thanks for your answer. But I'm trying to find a way to do all computations without for structure, I have limitations because my data base is very large and it's so time consuming. Do you/someone have an approach to do the job without for structure?
Mani

Mani Ahmadian
Mani Ahmadian 2014 年 10 月 22 日
Hi everybody.
would you please help me to improve my code?
Thanks a lot.
Mani

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by