What's the best way to build a block sparse matrix whose entries are diagonal matrices?

조회 수: 6 (최근 30일)
I want to construct a square block matrix out of square matrices, whose entries all lie on their respective diagonals. For example,
clear
N = 3;
M = 5;
MFull = zeros(N * M, N * M);
for n = 1 : M
for m = 1 : M
Mblock = rand(N,1) * m * n;
MFull((n - 1) * N + 1:n * N, (m - 1) * N + 1:m * N) = diag(Mblock);
end
end
When this matrix becomes big, this is clearly inefficient. I would like to define MFull as a sparse matrix to avoid memory issues and speed things up. Any suggestions are appreciated! To clarify: I would like to avoid creating MFull as a full matrix, and then converting it to a sparse matrix.

채택된 답변

David Cyncynates
David Cyncynates 2020년 12월 20일
Here's a solution that seems to work for me:
clear
N = 3;
M = 5;
BlockContainer = zeros(N * M, 2 * M - 1);
for n = 1 : M
for m = 1: M
row = m;
column = M + m - n;
Mblock = rand(N,1) * m * n;
BlockContainer((row - 1) * N + 1:(row) * N,column) = Mblock;
end
end
MFull = spdiags(BlockContainer,-(M - 1) * N:N:(M - 1) * N, N * M, N * M)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by