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.
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.
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
 
    
    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