バージョン (12.8 KB) 作成者: Jan
Fast linear indexing
ダウンロード: 348
更新 2015/2/5


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:


Jan (2024). CopyMask (, MATLAB Central File Exchange. 取得済み .

MATLAB リリースの互換性
作成: R2011b
Windows macOS Linux
Help Center および MATLAB AnswersOperators and Elementary Operations についてさらに検索
タグ タグを追加

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
バージョン 公開済み リリース ノート

Fixed typos in the description