GitCoder
GitCoder

Reputation: 121

Vectorize code in MATLAB

How to vectorize this code in MATLAB?

n = 3;
x = zeros(n);
y = x;
for i = 1:n
  x(:,i) = i;
  y(i,:) = i;
end

I am not able to vectorize it. Please help.

Upvotes: 0

Views: 125

Answers (3)

rayryeng
rayryeng

Reputation: 104503

If I can add something to the mix, create a row vector from 1 to n, then use repmat on this vector to create x. After, transpose x to get y:

n = 3;
x = repmat(1:n, n, 1);
y = x.';

Running this code, we get:

>> x

x =

     1     2     3
     1     2     3
     1     2     3

>> y

y =

     1     1     1
     2     2     2
     3     3     3

Upvotes: 2

Adriaan
Adriaan

Reputation: 18177

n=3;
[x,y]=meshgrid(1:n);

This uses meshgrid which does this automatically.

Or you can use bsxfun as Divakar suggests:

bsxfun(@plus,1:n,zeros(n,1))

Just as a note on your initial looped code: it's bad practise to use i as a variable

Upvotes: 2

Benoit_11
Benoit_11

Reputation: 13945

You can use meshgrid :

n = 3;
[x,y] = meshgrid(1:n,1:n)

x =

     1     2     3
     1     2     3
     1     2     3


y =

     1     1     1
     2     2     2
     3     3     3

Upvotes: 3

Related Questions