Cell array: select only 1x3 double cells

Hi everyone,
i have a 1x4 cell array like this:
{[0.1]} {1×3 double} {[0.02]} {1×3 double}
and i want to extract only the 1x3 double cells (of which I do not know the exact location into cell array).
Thank's a lot!
Riccardo Rossi

 採用された回答

Stephen23
Stephen23 2019 年 1 月 15 日
編集済み: Stephen23 2019 年 1 月 15 日

0 投票

Where C is your cell array:
X = cellfun('length',C)==3;
out = C(X)

7 件のコメント

TADA
TADA 2019 年 1 月 15 日
Why Not
X = cellfun(@length,C)==3;
Riccardo Rossi
Riccardo Rossi 2019 年 1 月 15 日
Thank you very much!
Stephen23
Stephen23 2019 年 1 月 15 日
編集済み: Stephen23 2019 年 1 月 15 日
@TADA: that would also work perfectly, although if using a function handle I would recommend to use numel rather than length. The reason to use 'length' is purely one of speed: the inbuilt "Backward Compatibility" syntaxes are faster than calling cellfun with a function handle.
TADA
TADA 2019 年 1 月 15 日
So It should Be Faster Because There's No Overloading Involved?
Riccardo Rossi
Riccardo Rossi 2019 年 1 月 15 日
I'm sorry, just another question.
If i have a cell array like this:
{1×3 double} {1×3 double} {2×3 double} {1×3 double} {4×3 double}
how can i extract only the 1x3 double cells (of which I do not know the exact location into cell array)?
Thank's a lot!
Stephen23
Stephen23 2019 年 1 月 15 日
F = @(v)isnumeric(v)&&isrow(v)&&numel(v)==3;
X = cellfun(F,C);
out = C(X)
Guillaume
Guillaume 2019 年 1 月 15 日
So It should Be Faster Because There's No Overloading Involved?
It is faster because cellfun use a different algorithm when using the backward compatible syntax. The built-in code does not call any other function when iterating over the elements, it's got its own implementation of length.
One side effect of that is that if you've overloaded length for a type in the cell array, that overload won't get called. For that reason, I personally wouldn't recommend using the old syntax unless you're 100% certain that your cell array will never ever contain objects. There's a reason the old syntax has been deprecated.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

製品

リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by