Matlab:将零行(或列)添加到稀疏矩阵的最有效方法是什么?

时间:2018-03-05 09:54:52

标签: matlab sparse-matrix

假设我有一个N x N稀疏矩阵。以A = speye(N)为例。 我的一般问题是:将零行(或列)添加到稀疏矩阵的最有效方法是什么?

在矩阵右侧添加jj列和/或在矩阵底部添加ii行只会更改稀疏矩阵的大小。所以在代码中这将是

    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);

在左侧和顶部添加列也会更改索引。

    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);

对于这两种情况中的任何一种,是否有更有效的方法?例如,我可以跳过某种方式找到A的非零元素吗?

1 个答案:

答案 0 :(得分:2)

您可以像使用标准矩阵一样添加列

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

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

请注意,find仍将仅返回2个非零值,但size(A)=[2,3],即我们已成功添加列。

变体:

% 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'
相关问题