Creation of a block-diagonal sparse matrix

3 Ansichten (letzte 30 Tage)
Jasper
Jasper am 6 Dez. 2014
Bearbeitet: Jasper am 8 Dez. 2014
I would like to create a block-diagonal matrix with the following properties:
  • The matrix must consist of submatrices A1, A2, ... on the diagonal and zeroes elsewhere.
  • Each submatrix will be square, but dimensions vary.
  • Each n-by-n submatrix takes the following shape:
eye(n) - ones(1/n)
  • Since there are many such submatrices, the overall matrix must be sparse.
What I have is a vector which holds the dimensions of each submatrix. So, if the vector is, say, b=[1,5,3,...], then the first submatrix A1 would have to be 1-by-1, A2 is 5-by-5, A3 is 3-by-3, and so on. How do I go from there to the creation of my matrix?
Two answers were given on a related quation. The first, based upon blkdiag, won't work, because it would involve temporarily creating the full matrix, and I run out of memory. The second seems preferable, but I can't wrap my head around how to adopt it to my setting.
  2 Kommentare
Matt J
Matt J am 7 Dez. 2014
What is ones(1/n)? Taken literally, it should give an error for any integer n>1,
>> ones(1/2)
Error using ones
Size inputs must be integers.
Jasper
Jasper am 8 Dez. 2014
Bearbeitet: Jasper am 8 Dez. 2014
Good catch, that was a typo. It should have read:
eye(n) - ones(n).*(1/n)

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Matt J
Matt J am 6 Dez. 2014
The first, based upon blkdiag, won't work, because it would involve temporarily creating the full matrix, and I run out of memory.
BLKDIAG will give you a sparse result if you first convert its inputs to sparse type, like below,
>> A=sparse(ones(3)); B=sparse(ones(2)); C=blkdiag(A,B)
C =
(1,1) 1
(2,1) 1
(3,1) 1
(1,2) 1
(2,2) 1
(3,2) 1
(1,3) 1
(2,3) 1
(3,3) 1
(4,4) 1
(5,4) 1
(4,5) 1
(5,5) 1
>> full(C)
ans =
1 1 1 0 0
1 1 1 0 0
1 1 1 0 0
0 0 0 1 1
0 0 0 1 1
  1 Kommentar
Matt J
Matt J am 7 Dez. 2014
Bearbeitet: Matt J am 8 Dez. 2014
So, you could do,
n=length(b);
B=cell(1,n);
for i=1:n
B{i}=sparse(MakeNextBlock( b(i) );
end
finalresult = blkdiag(B{:});

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Sparse Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by