1

I am interested how to create a diagonal matrix from an array of matrices. I created an array of matrices in MATLAB:

X<62x62x1000> it consists of 1000 matrices with dimensions 62x62

I want to create a matrix of dimensions 62000x62000 with 1000 sub matrices from array X along main diagonal.

Do you have any clue how to do this, except M=blkdiag(X(:,:,1), X(:,:,2), X(:,:,3)...) because that would be to much writing.

1

3 Answers 3

1

A possible solution

M = kron(speye(1000),ones(62)); M(logical(M)) = X(:); 

With kron a 62000*62000 sparse matrix M is created that contains 1000 blocks of ones on its diagonal, then replace ones with elements of X.

Sign up to request clarification or add additional context in comments.

Comments

0

You can flatten out your input matrix into a column vector using (:) indexing and then pass it to diag to place these elements along the diagonal of a new matrix.

result = diag(X(:)) 

This will order the elements along the diagonal in column-major order (the default for MATLAB). If you want a different ordering, you can use permute to re-order the dimensions prior to flattening.

It's important to note that your resulting matrix is going to be quite large. You could use spdiags instead to create a sparse diagonal matrix

spdiags(X(:), 0, numel(X), numel(X)) 

Comments

0

A very controversial eval call can solve this very lazily, although I suspect there is a much better way to do this:

evalstring = ['M=blkdiag(']; for i = 1:999 evalstring = [evalstring, 'X(:,:,', num2str(i),'),']; end evalstring = [evalstring, 'X(:,:,1000));']; eval(evalstring); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.