0

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.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
GitCoder
  • 121
  • 2
  • 13

3 Answers3

3

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
Benoit_11
  • 13,905
  • 2
  • 24
  • 35
2
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

Community
  • 1
  • 1
Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • 3
    I suggest a fight to the death with @Benoit_11;) – Andras Deak -- Слава Україні Oct 07 '15 at 20:43
  • Or use `bsxfun` ;) `bsxfun(@plus,1:n,zeros(n,1))` and its transpose. – Divakar Oct 07 '15 at 20:46
  • @Divakar I should've thought of that :( I just ran his code and saw it exactly matched `meshgrid`'s output, so I didn't stop to think about the great `bsxfun`. I'll add that to my answer. – Adriaan Oct 07 '15 at 20:48
  • Careful with the `n` though. You are using it as a vector with `meshgrid` and as a scalar with `bsxfun`. Since OP is using `n = 3;`, sticking to that might make sense. – Divakar Oct 07 '15 at 20:51
  • I'm on the verge of making the answer community-wiki since you added more than I did here ;) @Divakar – Adriaan Oct 07 '15 at 20:53
  • `meshgrid` would be the go-to approach here for efficiency and all that. `bsxfun` one is just for people bored of usual ways, so it's all good I think. – Divakar Oct 07 '15 at 20:54
2

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
rayryeng
  • 102,964
  • 22
  • 184
  • 193