Find the indices of elements of a cell array whose length is 1.

4 ビュー (過去 30 日間)
ashok Vardhan
ashok Vardhan 2015 年 10 月 14 日
コメント済み: Kirby Fears 2015 年 10 月 14 日
I have a cell array say, B{1}=[1,2], B{2}=[2], B{3}=3. I want to find the indices which give elements of length 1. In this case I want 2,3 as answers because B{2},B{3} have only single elements.

回答 (2 件)

the cyclist
the cyclist 2015 年 10 月 14 日
編集済み: the cyclist 2015 年 10 月 14 日
find(cellfun(@isscalar,B))
cellfun applies a function to each element of a cell. You can do more complicated things, but it just so happens that there was also a function, isscalar, that does the "test" that you want.

Kirby Fears
Kirby Fears 2015 年 10 月 14 日
You can apply an operation to each cell using cellfun(). Below is sample code that checks if each cell contains one element. The output is a logical array the same size as B. You can use find() on this logical array to get the position indices.
B{1} = [1,2];
B{2} = 2;
B{3} = 3;
idxSingles = find(cellfun(@(c) numel(c)==1 ,B));
Hope this helps.
  2 件のコメント
ashok Vardhan
ashok Vardhan 2015 年 10 月 14 日
How can I declare such a cell-array in Matlab where size of each sub-array is not equal ? I mean how do I create such an array.
Kirby Fears
Kirby Fears 2015 年 10 月 14 日
You initialize the cell array by using the cell() function. Then assign the double arrays into each cell.
B=cell(3,1); % initializes 3x1 cell array
B{1} = [1,2,3]; % 1st cell is 1x3 double array
B{2} = [4,5,6,7,8]; % 2nd cell is 1x5 double array
B{3} = [9,10]; % 3rd cell is 1x2 double array
If you are reading lots of data from somewhere, you should populate the cell array programmatically. The way to do this depends on what your data looks like and how you are reading it into Matlab.
Hope this helps.

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

カテゴリ

Help Center および File ExchangeData Type Identification についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by