Search code examples
matlabmatlab-struct

Access elements of a vector in a structure array MATLAB


I have a structure which contains two fields one of them contains vectors,example:

myStruct(1).f1 = val1;
myStruct(1).f2 = [elt1 elt2 elt3];

I want to find the indices of the elements of myStruct where elt1 == valA and elt2 == valB


Solution

  • One way to do this would be:

    % Create a matrix whose rows are the f2 vectors in the struct array
    A = cell2mat({myStruct.f2}.');
    
    % Find which rows match your conditions
    Matches = (A(:,1) == valA) & (A(:,2) == valB);
    
    % (If required: convert logical vector to indices)
    Indices = find(Matches);