フィルターのクリア

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 Center および File ExchangeMATLAB についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by