Clear Filters
Clear Filters

How to create a semi-diagonal matrix

8 views (last 30 days)
Hi all,
I have been trying to create a semi-diagonal matrix; Now I know this may not be the right terminology for it, however here it is (also, the matrix doesnt have to be square. I want to have control over its m x n dimensions. The example is thus of a semi-diagonal 3 x 6 matrix):
M_3x6 = [1 1 0 0 0 0
0 0 1 1 0 0
0 0 0 0 1 1] ;
Or for a larger matrix:
M_4x7 = [1 1 0 0 0 0 0
0 0 1 1 0 0 0
0 0 0 0 1 1 0
0 0 0 0 0 0 1] ;
Thanks for your help in advance,
KMT.

Accepted Answer

Stephen23
Stephen23 on 21 Nov 2017
Edited: Stephen23 on 21 Nov 2017
Method one: blkdiag:
>> blkdiag([1,1],[1,1],[1,1])
ans =
1 1 0 0 0 0
0 0 1 1 0 0
0 0 0 0 1 1
>>
You can easily supply the inputs as a comma-separated list:
>> C = repmat({[1,1]},1,4);
>> blkdiag(C{:})
ans =
1 1 0 0 0 0 0 0
0 0 1 1 0 0 0 0
0 0 0 0 1 1 0 0
0 0 0 0 0 0 1 1
>>
Then use indexing to select a part of the matrix.
Method two: repelem: With newer MATLAB versions you could use eye and repelem, and then use indexing as above.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!