필터 지우기
필터 지우기

remove nested for structure

조회 수: 2 (최근 30일)
Mani Ahmadian
Mani Ahmadian 2014년 10월 19일
편집: Mani Ahmadian 2014년 10월 22일
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

답변 (1개)

Matt J
Matt J 2014년 10월 19일
편집: Matt J 2014년 10월 19일
X=reshape(X,1,1,[]);
Y=reshape(Y,1,1,[]);
xgrid=linspace(xmin,xmax,100);
ygrid=linspace(ymin,ymax,100);
delta = hypot( bsxfun(@minus,X,xgrid) , bsxfun(@minus,Y,ygrid));
No idea why you've applied repmat along the jj-axis. It just duplicates data with no apparent purpose. But, you can incorporate it with the above, if you like
delta= repmat(delta,100,1);

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by