Search code examples
matlabstructmatlab-struct

Find Index of Structure Array with multiple criteria


I have a structure array as follows:

configStruct = 
20x1 struct array with fields:
    type
    id
    manufacturer
    model

How do I find the index of an element with fields, for example:

            type: 'Mainframe'
              id: '5'
    manufacturer: 'IBM'
           model: 'z14'

I've figured out how to find the indices of a structure using only one criteria:

find(strcmp({configStruct.type},'Mainframe'))

Scaling it up to two criteria would be something like:

find(strcmp({configStruct.type},'Mainframe') & strcmp({configStruct.id},'5'))

Scaling that up will get pretty cumbersome if I continue to add fields and criteria for those fields.


Solution

  • Just loop over it.

    LogIdx = arrayfun(@(n) isequal(configStruct(n),Element), 1:numel(configStruct));
    %where Element is the struct that you want to find in configStruct
    

    The above line gives logical indices. If linear indices are required, further use:

    LinIdx = find(LogIdx);