Find an index of a cell whose element satisfies a condition

조회 수: 25 (최근 30일)
Diaa
Diaa 2021년 6월 18일
댓글: DGM 2021년 6월 18일
Is there a way to economically fix the code below to make it work so that it returns the index of the cell element whose array has the number 1 in its second column?
c = {[1,2,3], [2,3,1], [3,1,2]};
find(c{:}(:,2)==1) % expected result is the cell index 3
The code above gets me this error:
Intermediate brace {} indexing produced a comma-separated list with 3 values, but it must produce a single value to perform subsequent indexing operations.
I came up with this one
find(~cellfun(@isempty,(cellfun(@(x) find(x(:,2)==1,1),c,'un',0))))
but I would like to find some other efficient ways of doing it.

채택된 답변

Star Strider
Star Strider 2021년 6월 18일
Try this —
c = {[1,2,3], [2,3,1], [3,1,2]};
idx = cellfun(@(x)x(:,2)==1, c, 'Unif',0)
idx = 1×3 cell array
{[0]} {[0]} {[1]}
Out = find([idx{:}])
Out = 3
.

추가 답변 (1개)

DGM
DGM 2021년 6월 18일
This is one way:
c = {[1,2,3], [2,3,1], [3,1,2], [1,2,3], [2,3,1], [3,1,2]};
idx = find(cellfun(@(x) x(2)==1,c))
idx = 1×2
3 6
  댓글 수: 2
Diaa
Diaa 2021년 6월 18일
I think your code will fail in this example
c = {[1,2,3;1,2,3], [2,3,1], [3,1,2;3,6,9]}; find(cellfun(@(x) x(2)==1,c))
DGM
DGM 2021년 6월 18일
Ah yeah. I had read "second column" as "second element".

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by