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

问题描述 投票:0回答:1

假设我有一个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的非零元素吗?

matlab sparse-matrix
1个回答
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'
© www.soinside.com 2019 - 2024. All rights reserved.