필터 지우기
필터 지우기

Testing for a string in a cell array in a structure

조회 수: 8 (최근 30일)
dormant
dormant 2022년 3월 18일
댓글: Voss 2022년 3월 22일
I want to find the matches to a string in a cell array of strings which is part of a structure.
Strcmp works when I give it the cell array, but not when I use the structure.
>> CellArray = { 'one' 'two' 'three' 'one' };
>> S = struct( 'CA', CellArray );
>> strcmp( CellArray, 'one' )
ans =
1×4 logical array
1 0 0 1
>> strcmp( S.CA, 'one' )
Error using strcmp
Too many input arguments.
>>
What am I doing wrong?
I don't have to use a structure - I just use it as a way of returing lots of variables from a function.

채택된 답변

Voss
Voss 2022년 3월 18일
편집: Voss 2022년 3월 18일
Enclose cell array arguments in the call to struct() with {} to make them scalar cell arrays, because struct() will create an array of structs for cell array inputs, one per element of the cell array given.
CellArray = { 'one' 'two' 'three' 'one' };
S = struct( 'CA', CellArray ) % 1-by-4 struct array
S = 1×4 struct array with fields:
CA
S = struct( 'CA', {CellArray} ) % scalar struct
S = struct with fields:
CA: {'one' 'two' 'three' 'one'}
strcmp( CellArray, 'one' )
ans = 1×4 logical array
1 0 0 1
strcmp( S.CA, 'one' )
ans = 1×4 logical array
1 0 0 1
  댓글 수: 2
dormant
dormant 2022년 3월 22일
Many thanks. Cell arrays are my Kryptonite!
Voss
Voss 2022년 3월 22일
You're welcome! If it's working now, do you mind marking the answer as 'Accepted'? I appreciate it!
Honestly, the behavior of struct() you ran into here - where passing a cell array to the struct() function creates an array of structs rather than a scalar struct with a cell array field - is one thing that bugs me about MATLAB (and there aren't very many things that bug me about MATLAB).

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by