필터 지우기
필터 지우기

Help vectorizing 2 For loops with meshgrid and subscripts

조회 수: 1 (최근 30일)
carlos Uribe
carlos Uribe 2014년 8월 12일
답변: Roger Stafford 2014년 8월 13일
Hello,
I have been thinking on vectorizing this code:
mat=zeros(a^2,a^2);
x=[1:a];
y=[1:a];
[Xm,Ym]=meshgrid(x,y)
for i=1:a^2
for j=1:a^2
[x1,y1]=ind2sub([a a],i);
[x2,y2]=ind2sub([a a],j);
mat(i,j)=(Xm(x1,y1)-Xm(x2,y2))^2+(Ym(x1,y1)-Ym(x2,y2))^2);
end
end
This takes too long as
a^2 is about 20k.
I still haven't been able to come with a nice solution, and not sure if it's even possible. If anyone can give me a hand I really appreciate it.
Thank you in advance.

채택된 답변

Yu Jiang
Yu Jiang 2014년 8월 13일
편집: Yu Jiang 2014년 8월 13일
Hi Carlos
Here is what I would do:
mat1=zeros(a^2,a^2);
x=[1:a];
y=[1:a];
[Xm,Ym]=meshgrid(x,y);
Xm1 = kron(ones(a^2,1), Xm(:));
Xm2 = kron(Xm(:), ones(a^2,1));
Ym1 = kron(ones(a^2,1), Ym(:));
Ym2 = kron(Ym(:), ones(a^2,1));
mat1=(Xm1-Xm2).^2+(Ym1-Ym2).^2;
mat1=reshape(mat1,a^2,a^2);
-Yu

추가 답변 (1개)

Roger Stafford
Roger Stafford 2014년 8월 13일
[Xm,Ym] = meshgrid(1:a,1:a);
[X1,X2] = meshgrid(Xm(:),Xm(:));
[Y1,Y2] = meshgrid(Ym(:),Ym(:));
mat = (X1-X2).^2+(Y1-Y2).^2;

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by