更改稀疏矩阵某些列中的非零值
Changing nonzeros in certain columns of a sparse matrix
我在 MATLAB 中有一个稀疏矩阵:
N=1000;
P=0.01;
A=sprand(N,N,P);
并且我想将某些列中的所有非零条目更改为一个。
也就是像这样:
c=randi(N,[1,round(N/10)]);
A(non zeros at columns c)=1;
当然可以在 for 循环中完成,但这显然不是我正在寻找的解决方案。
我尝试了几种使用 nnz、nonzeros、spfun 的解决方案——但没有成功。
谁能想出一个简单的方法来做到这一点?
谢谢,
埃拉德
你可以试试这个
N = 1000;
P = 0.01;
A = sprand(N,N,P);
c = unique(randi(N,[1,round(N/10)]))'; % sorted column index
[r,cind] = find(A(:,c));
A(sub2ind([N,N],r,c(cind)))=1;
你可以这样做:
A(:,c) = abs(sign(A(:,c))); % take the absolute value of the sign for all entries
% in the submatrix defined by the columns in c, and
% then assign the result back
等价地,
A(:,c) = logical(A(:,c);
或
A(:,c) = A(:,c)~=0;
这些可能并不快,因为它们处理这些列中的所有条目,而不仅仅是非零条目。 可能更快。
与相关,但更简单
A(:,c) = ceil(A(:,c));
我在 MATLAB 中有一个稀疏矩阵:
N=1000;
P=0.01;
A=sprand(N,N,P);
并且我想将某些列中的所有非零条目更改为一个。
也就是像这样:
c=randi(N,[1,round(N/10)]);
A(non zeros at columns c)=1;
当然可以在 for 循环中完成,但这显然不是我正在寻找的解决方案。 我尝试了几种使用 nnz、nonzeros、spfun 的解决方案——但没有成功。 谁能想出一个简单的方法来做到这一点?
谢谢, 埃拉德
你可以试试这个
N = 1000;
P = 0.01;
A = sprand(N,N,P);
c = unique(randi(N,[1,round(N/10)]))'; % sorted column index
[r,cind] = find(A(:,c));
A(sub2ind([N,N],r,c(cind)))=1;
你可以这样做:
A(:,c) = abs(sign(A(:,c))); % take the absolute value of the sign for all entries
% in the submatrix defined by the columns in c, and
% then assign the result back
等价地,
A(:,c) = logical(A(:,c);
或
A(:,c) = A(:,c)~=0;
这些可能并不快,因为它们处理这些列中的所有条目,而不仅仅是非零条目。
与
A(:,c) = ceil(A(:,c));