3
votes

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

3

3 Answers

1
votes

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.

1
votes

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;
0
votes

Related to Luis Mendos answer, but a bit simpler

A(:,c) = ceil(A(:,c));