I have a large one-dimensional cell array of structs. All the structs have the same format (i.e. same fields in the same order). I would like to search for a particular value in a struct field. E.g. say one of the fields is 'name'. I would like to be able to search the cell array and get back indices of all cells which contain a struct where the 'name' field contains 'sally'. Is there a straight-forward way to do this?

 채택된 답변

per isakson
per isakson 2014년 6월 24일
편집: per isakson 2014년 6월 24일

1 개 추천

Try
cac{1} = struct( 'name', 'val1' );
cac{2} = struct( 'name', 'val2' );
cac{3} = struct( 'name', 'val3' );
cac{4} = struct( 'name', 'sally' );
strcmp( cellfun( @(sas) sas.name, cac, 'uni', false ), {'sally'} )
which returns
ans =
0 0 0 1
Straight-forward - maybe not.

댓글 수: 5

Ben
Ben 2014년 6월 28일
Could you elaborate a bit on this? I haven't looked into cellfun at all. Is 'sas' the name of the function? What is cac?
per isakson
per isakson 2014년 6월 28일
There is a good description together with examples in the documentation: cellfun, Apply function to each cell in cell array
cac and sas are names of variables.
Ben
Ben 2014년 6월 28일
편집: Ben 2014년 6월 28일
I've looked at that, and still don't understand 'uni'. Is that a valid shortening of 'UniformOutput'? Also, where do I find out about the function handle 'sas'?
per isakson
per isakson 2014년 6월 29일
Yes, 'uni' is a valid shortening of 'UniformOutput'
@(sas) sas.name is the definition of a anonymous function and sas is just an argument.
Ben
Ben 2014년 7월 1일
I've run across a problem using this idea. It works fine in the if statement, but throws an error in the loop. I put a break at line 8, and if I hover over "restaurants", Matlab knows it's a cell array of structs, just like "reviews" is. Any ideas on why I'm getting this error?

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

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Structures에 대해 자세히 알아보기

질문:

Ben
2014년 6월 24일

댓글:

Ben
2014년 7월 1일

Community Treasure Hunt

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

Start Hunting!

Translated by