# How to write this efficiently in MATLAB?

I would like to re-write this efficiently in MATLAB.

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


I tried to run it in MATLAB and get this output below

x =

 1     0     0
1     0     0
1     0     0


y =

 1     1     1
0     0     0
0     0     0


x =

 1     2     0
1     2     0
1     2     0


y =

 1     1     1
2     2     2
0     0     0


x =

 1     2     3
1     2     3
1     2     3


y =

 1     1     1
2     2     2
3     3     3

• The Help Center says that questions about "Software that mathematicians use" is on-topic. We also have a good answer. – robjohn Feb 24 '14 at 17:47

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

• +1 Or use just [x,y] = meshgrid(1:n); – Luis Mendo Mar 2 '14 at 4:24

When hard-coded,

x=[1 2 3;1 2 3;1 2 3]; y=x';


will do. If not (n arbitrary), you can use

x=1:n;           % Creates a "template row" [1 2 3 ... n]
x=repmat(x,n,1); % Stacks this row n times [1 2 3 ... n;
1 2 3 ... n;
... ;
1 2 3 ... n] (n-by-n matrix)
y=x';            % Creates the transpose

• I tried I dont get the same results – joke Feb 24 '14 at 0:11
• @joke Well, what do you get then? Maybe use help repmat to ensure the syntax is correct. – AlexR Mar 3 '14 at 18:18
x=ones(3,1)*(1:3);
y=(1:3)'*ones(1,3);


Alternatively, you can set y equals transposition of x.