0
votes

I have a large sparse matrix that I'm working on, but for simplicity I have written it below as shown:

row = [1,3];
col = [1,3];
val = [22,33];

B = sparse(row,col,val,3,3)

22     0     0
 0     0     0
 0     0    33

This matrix is singular and does not have an inverse that I can use for a solution of:

[A]=[B][C] => [B]\[A] = [C].

To remedy this, all of the rows and columns containing only zero need to be removed. So, in the example above, I would remove row 2 and column 2 before I create the sparse matrix.

But if I try this, the index described by the row and col vectors (3,3) will point outside the matrix dimensions and give me an error. What is something I can do to solve this problem?

2

2 Answers

1
votes

You could first construct your matrix the way that you have, and then remove the empty rows and columns with the following

C = B(any(B, 2), any(B, 1));

This is very efficient (space-wise) since any applied to a sparse matrix yields a sparse result and the indexing operation above yields C which is also sparse

Although, depending on your problem, this will not guarantee a non-singular matrix.

Update

If you want to remove a row or column if both the row and corresponding column are zero (to keep your matrix square)

tokeep = any(B, 2).' | any(B, 1);

C = B(tokeep, tokeep);
0
votes

A possible solution

row = [1,3];
col = [1,3];
val = [22,33];
[ur,~,u_row] =  unique(row);
[uc,~,u_col] =  unique(col);
B =sparse( u_row,u_col,val,numel(ur),numel(uc));