Reputation: 97
I have a sparse matrix in MATLAB:
N=1000;
P=0.01;
A=sprand(N,N,P);
and I want to change all non zero entries at certain columns into ones.
That is, something like this:
c=randi(N,[1,round(N/10)]);
A(non zeros at columns c)=1;
Of course it can be done in a for loop, but that's clearly not the solution I'm looking for. I tried several solutions using nnz, nonzeros, spfun - but with no soccess. Can anyone come up with a simple way to do it?
Thanks, Elad
Upvotes: 3
Views: 68
Reputation: 112659
You can do it this way:
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
Equivalently,
A(:,c) = logical(A(:,c);
or
A(:,c) = A(:,c)~=0;
These may not be fast, because they process all entries in those columns, not just the nonzero entries. Dohyun's approach is probably faster.
Upvotes: 1
Reputation: 1693
Related to Luis Mendos answer, but a bit simpler
A(:,c) = ceil(A(:,c));
Upvotes: 0
Reputation: 642
You can try this
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;
Upvotes: 1