Return index of cell in a cell array for which contains a desired element

조회 수: 2 (최근 30일)
hmhuang
hmhuang 2022년 2월 20일
댓글: Voss 2022년 2월 20일
I have a cell array:
C = {[1,2,4], [3,5], [8,9]}
I would like to have a function, such that:
somefunc(C, 2) % will return 1, indicating that 2 is in the 1st cell of the cell array
somefunc(C, 8) % will return 3, indicating that 8 is in the 3rd cell of the cell array
somefunc(C, 7) % will return 0 or -1 or whatever that is not 1 or 2, or 3
Is there any MATLAB built-in function that could achieve this purpose?
Thanks in advance!
(Assume the elements in the cell array are unique.)

채택된 답변

Voss
Voss 2022년 2월 20일
C = {[1,2,4], [3,5], [8,9]};
find(cellfun(@(x)ismember(2,x),C))
ans = 1
find(cellfun(@(x)ismember(8,x),C))
ans = 3
find(cellfun(@(x)ismember(7,x),C))
ans = 1×0 empty double row vector
  댓글 수: 1
Voss
Voss 2022년 2월 20일
Or, making that command into a function you can call:
C = {[1,2,4], [3,5], [8,9]};
find_cell_containing(C,2)
ans = 1
find_cell_containing(C,8)
ans = 3
find_cell_containing(C,7)
ans = 1×0 empty double row vector
function idx = find_cell_containing(C,in)
idx = find(cellfun(@(x)ismember(in,x),C));
end

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by