How can I use the function blkdiag without typing every single matrix?

25 views (last 30 days)
I know we can construct a block diagonal matrix using the MATLAB function blkdiag.
The way we use is
out = blkdiag(a, b, c, d, e, ...)
Here, a ~ e are matrices or vectors and Matrices are already saved in another matrix like
A = [a, b, c, d, e, f, g, ..., z, ...]
But in my case, there are so many matrices which should be put as input arguments. (more than 1000 matrices)
It is almost impossible to type every name of the matrices as the arguements of the function blkdiag.
Do we have a simple and fast way to do this operation without typing every single one?
and, I hope there is a solution not using for-loop and cell because that might make my code so slow.
  2 Comments
Stephen23
Stephen23 on 30 Oct 2018
Edited: Stephen23 on 30 Oct 2018
The basic problem is that your data is badly designed, which leads you to have one thousand separate variables that you want to access. But doing this will force you into writing slow, complex, buggy code that is hard to debug. Read this to know why:
Most likely you did not sit and write out one thousand variable names, so the solution is to fix your code where those variables are created in the workspace. Most likely it could be avoided by load-ing into an output variable:
S = load(...)
or something similar. Once you have your data in one variable then calling blkdiag is trivially easy using a comma-separated list (as my answer shows).
Sinwoo Jeong
Sinwoo Jeong on 31 Oct 2018
Thank you for your comment. Actually, there are no such numbers of variables in my code.
a, b, c,... are come from a single matrix.
What I want to do is diagonalize the matrix and multiply it with another matrix.
Anyway, your answer was very very helpful to me. That is exactly what I have been looking for.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 30 Oct 2018
Edited: Stephen23 on 23 Feb 2022
"Do we have a simple and fast way to do this operation without typing every single one?"
Of course, this is simple, just use a comma-separated list:
C = {a,b,c,d,...}; % the matrices in a cell array.
M = blkdiag(C{:})
Read more here:

More Answers (0)

Community Treasure Hunt

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

Start Hunting!