1

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
joke
  • 41
  • 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

3 Answers3

3

How about:

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

littleO
  • 51,938
2

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
AlexR
  • 24,905
1
x=ones(3,1)*(1:3);
y=(1:3)'*ones(1,3);

Alternatively, you can set y equals transposition of x.

Lion
  • 2,148