Forming a block diagonal matrix of one certain matrix?
Show older comments
I have a matrix A which is m*n. I want to create a block diagonal matrix of size 100*100 whose diagonal elements are the matrix A.
[A,0,0,0
0,A,0,0
0,0,A,0
0,0,0,A
... ]
function, out = blkdiag(A,A,A,A,...) needs writing down the matrix so many times. Is there any other way to do this (not typing so many matrices as input arguments of blkdiag)?
2 Comments
Teun Burgers
on 18 Apr 2018
how about
kron(eye(100),A)
or
kron(eye(100),sparse(A))
Rik
on 30 Jan 2021
Comment posted as flag by @Anubhav Halder:
Worked perfectly for me. Thanks.
Accepted Answer
More Answers (2)
Teun Burgers
on 19 Apr 2018
how about:
kron(eye(100),A)
or
kron(eye(100),sparse(A))
1 Comment
Stoyan Margaretov
on 23 Jun 2020
Genious, that worked perfectly for me!
Honglei Chen
on 14 Feb 2017
eval(sprintf('Out = blkdiag(A%s);',repmat(',A',1,99)))
HTH
1 Comment
The MATLAB documentation for eval recommends that "Whenever possible, do not include output arguments within the input to the eval function, such as eval(['output = ',expression]). The preferred syntax,"
output = eval(expression)
"allows the MATLAB parser to perform stricter checks on your code, preventing untrapped errors and other unexpected behavior." Because the variable Out does not change this could easily have been achieved in this solution, and thus would follow the advice given in the MATLAB help.
Note that Star Strider's solution avoids all of these problems by simply avoiding eval entirely:
Categories
Find more on Operating on Diagonal Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!