Matlab:将零行(或列)添加到稀疏矩阵的最有效方法是什么?
Matlab: What is the most efficient way to add zero rows (or column) to a sparse matrix?
假设我有一个 N x N
稀疏矩阵。以 A = speye(N)
为例。
我的一般问题是:将零行(或列)添加到稀疏矩阵的最有效方法是什么?
在矩阵右侧添加 jj
列 and/or 在矩阵底部添加 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
的非零元素?
您可以像使用标准矩阵一样添加列
% Create a sparse matrix
A = speye(3);
% Add a column of zeros to the end
A(:, end+1) = 0;
请注意,find
仍将仅 return 2 个 non-zero 值,但 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'
假设我有一个 N x N
稀疏矩阵。以 A = speye(N)
为例。
我的一般问题是:将零行(或列)添加到稀疏矩阵的最有效方法是什么?
在矩阵右侧添加 jj
列 and/or 在矩阵底部添加 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
的非零元素?
您可以像使用标准矩阵一样添加列
% Create a sparse matrix
A = speye(3);
% Add a column of zeros to the end
A(:, end+1) = 0;
请注意,find
仍将仅 return 2 个 non-zero 值,但 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'