1
$\begingroup$

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
$\endgroup$
  • $\begingroup$ The Help Center says that questions about "Software that mathematicians use" is on-topic. We also have a good answer. $\endgroup$ – robjohn Feb 24 '14 at 17:47
3
$\begingroup$

How about:

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

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

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

Alternatively, you can set y equals transposition of x.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.