How to avoid a for-loop in MATLAB, when performing a operation on each row in a very large matrix? -
i using matlab. have very large sparse matrices, , want perform logical
or bsxfun
on each column of matrix. there single for
loop in single operation of logical
fill sparse matrix. here include sample function fake small data see trying do;
function maskmat() graph_temp = round(rand(10,10)); tic; com_mat = round(rand(10,10)); com = round(rand(10,1)); ii=1:length(graph_temp) com_mat(:,ii) = logical(com ~= com(ii)); %bsxfun works slower %com_mat(:,ii) = bsxfun(@ne,com,com(ii)); end toc; com_mat = graph_temp .* com_mat;
graph_temp
, com_mat
bigger around 1m rows , columns , code horribly slow for
loop. there relevant question here on so, have not understood theory behind see if can apply solutions problem well.
i thinking either write mex
c++ function or try sort of nested arrayfun
each logical
/bsxfun
operation called subroutine of greater function avoid loop bottle neck.
i'm not sure followed code way. so, make sure, com_mat(ii,jj)
equals com(ii) ~= com(jj)
?
if try following options
com_mat = bsxfun( @ne, com, com' ); %' creates entire matrix @ once com_mat = graph_temp .* com_mat; % masking
since dealing sparse matrices, why don't take advantage of it
[ii jj] = find( graph_temp ); [m n] = size( graph_temp ); com_mat = sparse( ii, jj, com(ii) ~= com(jj), m, n );