File Exchange

image thumbnail


version 1.1 (1.93 KB) by

Search for a value, cell or string inside a Matlab struct



View License

 StructFind, Find the index of a certain string or value in a struct


       a : A Matlab struct, for example a(1).name='red', a(2).name='blue';
       field : The name of the field which is searched, for example 'name'
       value : The search value, for example 'blue'

       index : The Struct index which match the search



 a(2).val=[1 0];


 a(4).val=[0 0 0];

 a(5).val=[0 1 1];

 a(6).val=[1 1 0];




 disp(['index : ' num2str(index)])

 disp(['index : ' num2str(index)])

 index=structfind(a,'val',[0 0 0]);
 disp(['index : ' num2str(index)])

 disp(['index : ' num2str(index)])

 disp(['index : ' num2str(index)])

 disp(['index : ' num2str(index)])

 disp(['index : ' num2str(index)])

 disp(['index : ' num2str(index)])

Comments and Ratings (9)

Will Kinsman

Much slower than a for loop for the non-numeric case

Chad Greene

Chad Greene (view profile)

This function has proven quite helpful; thanks for sharing.


Great command!!!!! Just in case, can you search for two strings in a one liner? Like red and blue

Jordi Riba

Works really nice, it is exactly what I was missing. Many thanks !!!

Dirk-Jan Kroon

Dirk-Jan Kroon (view profile)

*Jos (10584)
Thank you for your comments. I have uploaded a version which solves all your points 1,2 and 3. This version will probably be on-line this afternoon.

Jos (10584)

Jos (10584) (view profile)

ad 2) I would suggest not to throw an error, but issue a warning and return empty
ad 3) good solution. If you catch this error, and add the solution to the help this would be great.

Dirk-Jan Kroon

Dirk-Jan Kroon (view profile)

*Jos (10584)
1) You are right.
2) The error thrown by Matlab is very clear "not a fieldname"
3) instead of structfind(a,'x.y',3), you can use structfind(a.x,'y',3). This is logical because the tag-code is a string and is not evaluated, because it can be very complex and depend on local variables, like structfind(a,'x(2).y{''d''}{3}.z(e).d',3);

Jos (10584)

Jos (10584) (view profile)

Potentially useful, but ...
1) the terminology is confusing: MatLab talks about fields, not tags, of a struct.
2) the function errors when the second argument is not a field (aka tag) of the struct. Example:
clear a ; a.x = 3 ; structfind(a,'NOTx',3)
3) it cannot deal with fields within a field. This should be mentioned in the help
clear a ; a.x.y = 3 ; structfind(a,'x.y',3)



Added solutions for problem cases by comment : Jos (10584)

MATLAB Release
MATLAB 7.11 (R2010b)

Inspired: StructFind

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video