MATLAB Answers


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

Asked by Sinwoo Jeong on 30 Oct 2018
Latest activity Commented on by Sinwoo Jeong on 31 Oct 2018
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.


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).
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.

1 Answer

Answer by Stephen Cobeldick on 30 Oct 2018
Edited by Stephen Cobeldick on 30 Oct 2018
 Accepted Answer

"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:


Sign in to comment.