CopyMask - Logical indexing
Matlab's linear indexing is fast, much faster than using FIND usually.
But it can be more than twice as fast using a C-Mex function.
Y = CopyMask(X, Mask, Dim)
X: Array of type: DOUBLE, SINGLE, (U)INT8/16/32/64), LOGICAL, CHAR.
X can be complex.
Mask: Mask as LOGICAL vector.
Dim: Specify dimension for masking. If omitted or the empty matrix 
linear indexing is applied. Optional, default: .
Y: Array of same type as X. For linear indexing Y is a [N x 1] vector.
- Equivalent Matlab code: Y = X(Mask)
- Difference to Matlab's logical indexing:
* 2 to 3 times faster for linear indexing.
* A column vector is replied in every case.
* Mask cannot be longer than the array, while Matlab allows additional
trailing values, when they are FALSE.
- If Dim is specified and X is not small, this function is only some percent
faster than the equivalent Matlab code, e.g.: Y = X(:, Mask, :)
X = rand(2,3,4);
Y = CopyMask(X, X > 0.2); % Matlab: X(X > 0.2), remarkably faster
M = [true, false, true];
Z = CopyMask(X, M, 2); % Matlab: X(:, M, :), a little bit faster
I could test this under Matlab 2009a and 2011b only. Perhaps the speedup vanishes in modern Matlab versions. Please feel free to send me the output of the unit-test function to the address given in the code.
The C-file must be compiled at first. If "mex -setup" was performed before, calling CopyMask without inputs starts an automatic compilation. If compiling fails, you can download pre-compiled files at: http://www.n-simon.de/mex
Jan (2021). CopyMask (https://www.mathworks.com/matlabcentral/fileexchange/49553-copymask), MATLAB Central File Exchange. Retrieved .
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!