Creating diagonal matrix from array of matrices in MATLAB

做~自己de王妃 提交于 2020-01-05 07:20:11

问题


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:


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.




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/40614794/creating-diagonal-matrix-from-array-of-matrices-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!