Vectorizing three nested loops

3 ビュー (過去 30 日間)
AP 2012 年 10 月 13 日
Dear All,
How can I vectorize the following three nested loops? I tried using arrayfun but I did not succeed in doing it.
% Range of random number for x and y.
L = 8;
H = 6;
% The number of random numbers.
n = 100;
% Randomly spaced data.
x = rand( n, 1 )*L;
y = rand( n, 1 )*H;
d = .01;
[ X, Y ] = meshgrid( 0:d:L, 0:d:H );
TOL = .01;
I = zeros(size(X));
for i=1:size(X,1)
for j=1:size(X,2)
for k=1:numel(x)
dist = (X(i,j)-x(k))^2+(Y(i,j)-y(k))^2;
if( dist<TOL)
I(i,j) = 1;
end
end
end
end
Thanks,

サインインしてコメントする。

採用された回答

Matt Fig 2012 年 10 月 13 日

I2 = any((bsxfun(@minus,X,reshape(x,1,1,n)).^2 +...
bsxfun(@minus,Y,reshape(y,1,1,n)).^2)<TOL,3) ;
3 件のコメント表示非表示 2 件の古いコメント
AP 2012 年 10 月 13 日
Sorry, I did not noticed one of the statements had been changed. I get the same results too. Thanks so much.

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by