MATLAB: How to make sure that if creating a diagonal matrix from another, the matrices are the same size

diagonal matrices;

For example, if:
a =
1 2 3 4
4 5 6 7
7 8 9 0
and I perform the operation b = diag(diag(a,1),1)
I get: b =
0 2 0 0
0 0 6 0
0 0 0 0
0 0 0 0
but I want this matrix: b =
0 2 0 0
0 0 6 0
0 0 0 0
so be and a have the same dimensions. Thanks

Best Answer

Wanting existing code to magically know what you want it to do is nice, but is hardly likely to be successful in general. Sometimes you get lucky, but usually, not so.
When diag is applied to a vector, it always produces a square matrix, even if it is specified as an off-diagonal by use of the second argument to diag. This can be useful behavior, since diag has often been used to build up banded matrices, as the sum of several diagonals created separately.
diag cannot know where the vector came from, that in this case, the vector was derived from a diag operation applied to a non-square matrix.
You can always delete the unwanted rows after the fact.