MATLAB Answers

AP
0

Vectorizing three nested loops

Asked by AP
on 13 Oct 2012

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,

Ahmad

  0 Comments

Products

No products are associated with this question.

1 Answer

Answer by Matt Fig
on 13 Oct 2012
Edited by Matt Fig
on 13 Oct 2012
 Accepted answer

I2 = any((bsxfun(@minus,X,reshape(x,1,1,n)).^2 +...
        bsxfun(@minus,Y,reshape(y,1,1,n)).^2)<TOL,3) ; 

  3 Comments

AP
on 13 Oct 2012

Matt, it does not give me the correct result.

Matt Fig
on 13 Oct 2012

The code above does give the same result here.....

isequal(I,I2)
ans =
       1

I ran it 10 times, and every time I get the same thing. Here is the code I used to test that I and I2 are equal. So what are you doing that says they are not equal? Did you run something other than what you posted?

% 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;
tic
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
toc
tic 
I2 = any((bsxfun(@minus,X,reshape(x,1,1,n)).^2 +...
          bsxfun(@minus,Y,reshape(y,1,1,n)).^2)<TOL,3) ;   
toc
isequal(I,I2)
AP
on 13 Oct 2012

Sorry, I did not noticed one of the statements had been changed. I get the same results too. Thanks so much.


Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!