Reputation: 159
I have a very large sparse matrix (each row is several thousand elements--most of the elements are 0's). In addition, I have a vector of row indexes, and I need to perform the following operation on each row:
Flip half the non-zero elements (randomly chosen from all non-zero elements in the row) to zero, and save the column indexes of the flipped elements.
Thanks for any pointers.
Upvotes: 3
Views: 1223
Reputation: 350
You can use randperm()
to generate a random order of columns that you want to zero out in a row.
% A: sparse matrix (assume 2d)
% ri = vector or row indices
for i = 1:numel(ri) % Edit one row of A at a time
row = A( ri(i), : );
c = find( row ); % Find column index of all non-zero elements a row
cdel = randperm(length(c)); % Random rearrangement of column index
cdel(1:end/2) = []; % Only want to zero out half the columns, so ignore the other half
% c(cdel) will give the column index of elements to be zeroed.
row( 1, c(cdel) ) = 0; % Zero out selected columns
A( ri(i), : ) = row; % Update A
end
There maybe some bug in the code as I haven't tested it out. Also some steps are redundant and can be combined.
c(cdel)
will give you the required index of the columns that were flipped. You can save it in a cell vector as it size may change for each row. You can do this by,
fcol{i} = c(cdel);
Upvotes: 2