0

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.

Rek
  • 45
  • 4

2 Answers2

2

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);
Sardar Usama
  • 19,536
  • 9
  • 36
  • 58
  • In this case, `Element.id = '5'; Element.type = 'Mainframe'; Element.manufacturer = 'IBM'; Element.model = 'z14'; ` – Rek Apr 15 '19 at 14:36
0

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
Anthony
  • 3,595
  • 2
  • 29
  • 38