remove nested for structure

3 views (last 30 days)
Mani Ahmadian
Mani Ahmadian on 19 Oct 2014
Edited: Mani Ahmadian on 22 Oct 2014
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

Answers (1)

Matt J
Matt J on 19 Oct 2014
Edited: Matt J on 19 Oct 2014
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);

Community Treasure Hunt

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

Start Hunting!