Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab Special Matrix

Tags:

matrix

matlab

Is there a MATLAB function to generate this matrix?:

[1 2 3 4 5 6 7 ... n;
 2 3 4 5 6 7 8 ... n+1;
 3 4 5 6 7 8 9 ... n+2;
 ...;
 n n+1 n+2     ... 2*n-1];

Is there a name for it?

Thanks.

like image 455
Brethlosze Avatar asked Mar 15 '23 07:03

Brethlosze


2 Answers

Yes indeed there's a name for that matrix. It's known as the Hankel matrix.

Use the hankel function in MATLAB:

out = hankel(1:n,n:2*n-1);

Example with n=10:

out = 

     1     2     3     4     5     6     7     8     9    10
     2     3     4     5     6     7     8     9    10    11
     3     4     5     6     7     8     9    10    11    12
     4     5     6     7     8     9    10    11    12    13
     5     6     7     8     9    10    11    12    13    14
     6     7     8     9    10    11    12    13    14    15
     7     8     9    10    11    12    13    14    15    16
     8     9    10    11    12    13    14    15    16    17
     9    10    11    12    13    14    15    16    17    18
    10    11    12    13    14    15    16    17    18    19

Alternatively, you may be inclined to want a bsxfun based approach. That is certainly possible:

out = bsxfun(@plus, (1:n), (0:n-1).');

The reason why I wanted to show you this approach is because in your answer, you used repmat to generate the two matrices to add together to create the right result. You can replace the two repmat calls with bsxfun as it does the replication under the hood.

The above solution is for older MATLAB versions that did not have implicit broadcasting. For recent versions of MATLAB, you can simply do the above by:

out = (1:n) + (0:n-1).';
like image 79
rayryeng Avatar answered Mar 19 '23 05:03

rayryeng


My standard approach is

repmat(1:n,n,1)+repmat((1:n)',1,n)-1
like image 37
Brethlosze Avatar answered Mar 19 '23 06:03

Brethlosze