0
votes

Suppose I have an N x N sparse matrix. Take for example A = speye(N). My general question is: what is the most efficient way to add zero rows (or column) to a sparse matrix?

Adding jj columns on the right side of the matrix and/or adding ii rows at the bottom of the matrix simply changes the size of the sparse matrix. So in code this would be

    N=2;
    A=speye(N);
    [rows,cols,vals] = find(A);
    % Add ii = 3 zero rows at the bottom
    % and jj = 2 zero columns at the left of A
    ii = 3; jj=2;
    B = sparse(rows,cols,vals,N+ii,N+jj);

Adding columns on the left and at the top, also changes the indices.

    N=2;
    A=speye(N);
    [rows,cols,vals] = find(A);
    % Add ii = 3 zero rows at the top
    % and jj = 2 zero columns at the right of A
    ii = 3; jj=2;
    B = sparse(rows+ii,cols+jj,vals,N+ii,N+jj);

Is there a more efficient way, for either of the two cases? For example, can I skip somehow finding the non-zero elements of A?

1

1 Answers

2
votes

You can add a column as you would with a standard matrix

% Create a sparse matrix
A = speye(3);

% Add a column of zeros to the end
A(:, end+1) = 0;

Note that find will still only return the 2 non-zero values, but size(A)=[2,3], i.e we've successfully added a column.


Variants:

% Still adding a column on the right, by concatenating with another sparse matrix. 
% However: this is less memory efficient with A on the right hand side
A = [A, sparse(3,1)];

% Adding column on the left
A = [sparse(3,1), A];         % comma is equivalent of 'horzcat'
% Adding a row on the top
A = [sparse(1,size(A,2)); A]; % semi-colon is equivalent of 'vertcat'