Find Index of Structure Array with multiple criteria

299 Views Asked by At

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.

2

There are 2 best solutions below

1
Sardar Usama On BEST ANSWER

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);
0
Anthony On

I'm not aware of any native function would do what you are asking, but I recommend you to break all kinds of strcmp into sub-functions:

global configStruct
find(isType('Mainframe') & isId('5'));

function val = isType(type)
global configStruct
val = strcmp({configStruct.type}, type);
end

function val = isId(id)
global configStruct
val = strcmp({configStruct.type}, id);
end