James McMillan
James McMillan

Reputation: 11

Vectorising a double for loop in MATLAB

I'm trying to vectorise this double for loop which calculates co-ordinates, so I've got

A = zeros(100,100);  
for x = 1:100       
    for y = 1:100
        A(x,y) = x^2 + y  %or other functions with x and y
    end
end

Though trying to vectorise it by using something like meshgrid like some examples I've seen gives me a whole load of errors like "Dimensions of matrices being concatenated are not consistent."

Is there a way to vectorise this? Thanks very much for the help.

I'm actually using

A = zeros(31,31);
for x = 1:31       
    for y = 1:31
        A(y,x) = f(1.5, (x-16)/10 + i*((y-16)/10), 1000);
    end
end

where f(1.5,...) is some other function I'm using to calculate the points of A which would output just a number.

Trying something like

A = zeros(31,31);
[X,Y] = ndgrid(1:31,1:31);
A(Y,X) = f(1.5, (X-16)/10 + i*((Y-16)/10), 1000);

Gives me:

Error using horzcat Dimensions of matrices being concatenated are not consistent.

An error in f

Error in line 3: A(Y,X) = f(1.5, (X-16)/10 + i*((Y-16)/10), 1000);

Upvotes: 1

Views: 58

Answers (1)

Divakar
Divakar

Reputation: 221774

Let N = 100 be the datasize. You have few approaches here to play with.

Approach #1: bsxfun with built-in @plus

A = bsxfun(@plus,[1:N]'.^2,1:N)

Approach #2: bsxfun with anonymous function -

func = @(x,y) x.^2 + y 
A = bsxfun(func,[1:N]',1:N)

For a general function with x and y, you can use ndgrid or meshgrid as discussed next.

Approach #3: With ndgrid -

[X,Y] = ndgrid(1:N,1:N);
A =  X.^2 + Y

Approach #4: With meshgrid -

[Y,X] = meshgrid(1:N,1:N);
A =  X.^2 + Y

Upvotes: 4

Related Questions