MATLAB: Sparse and binary mask

efficiencymaskmultiplicationprofilersavingssparsespeed

I am working on saving computations and speeding up my Matlab code. Here's what I do Perform thresholding on an image and make most of its components as zero run it inside a loop with element by element multiplication with another matrix(full matrix) of the same size
Here is a detailed version of what I am doing
CASE I:When I dont avoid multiplication with zeros
matrix(matrix<threshold) = 0 ;
while the condition is true
matrix = matrix.*phase;
other lines of code ;
end
Result: From MATLAB profiler I see that matrix = matrix.*phase; takes 80 seconds
CASE II:When I avoid multiplication with zeros using SPARSE
matrix(matrix<threshold) = 0 ;
matrix = sparse(matrix);
while the condition is true
matrix = matrix.*phase;
other lines of code ;
end
Result: From MATLAB profiler I see that matrix = matrix.*phase takes 110 seconds
CASE III:When I avoid multiplication with zeros using a mask
matrix(matrix<threshold) = 0 ;
mask = matrix~=0;
while the condition is true
matrix(mask) = matrix(mask).*phase(mask);
other lines of code ;
end
Result: From MATLAB profiler I see that matrix = matrix.*phase takes 130 seconds
Why is my code slow if I try to avoid multiplications with zeros? Since the matrix after thresholding has 75% zeros my speed should be up by 75% as I am avoiding multiplication with zeros. But my time is increased Is there any other way to achieve avoiding multiplication with zeros and speeding up of the code?
MY PRIORITY IS TO SPEED UP THE CODE EXECUTION AND SAVE MUTLIPLICATIONS

Best Answer

Instead of matrix(mask) = matrix(mask).*phase(mask)
you might work on index
idx = find(mask & matrix~=0);
while ...
matrix(idx) = matrix(idx).*phase(idx);
end
You might want to compute phase(idx) outside the loop if they do not change, or update idx if the matrix elements become zero. As you don't give any detail, we have no idea if those are applicable for you.
If matrix does not share any copy, you might do element inplace replacement using MEX.