How to write this efficiently in MATLAB?

89 Views Asked by At

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
3

There are 3 best solutions below

2
On

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
1
On

How about:

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

0
On
x=ones(3,1)*(1:3);
y=(1:3)'*ones(1,3);

Alternatively, you can set y equals transposition of x.