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