arikabc
arikabc

Reputation: 755

Read multiple values from array dynamically in MATLAB

I have an array of structures.
I'm trying to select several records from the array, that match some condition.
I know there's this option: (For example array A with field f1):

A([A.f1]==5) 

Which would return all the records that have f1 = 5.
But I want to do it for several different fields, in a loop. I saved the fields names in a cell array, but I don't know how to do the same with a dynamic field name.
I know there's the 'getfield' function, but it only selects a field from a single structure.
Is there a way to do it?
Thanks!

Upvotes: 0

Views: 107

Answers (2)

Oleg
Oleg

Reputation: 10676

To access dynamically a field of a structure:

% Create example structure
s.a = 1;
s.b = 2;

% Suppose you retrieve the fieldnames (or hardcode them fnames = {'a','b'})
fnames = fieldnames(s);

The you can retrieve e.g. the second one:

s.(fnames{2})

In a loop

for f = 1:numel(fnames)
    s.(fnames{f})
end

In your case:

A([A.(fnames{ii})] == n)

Upvotes: 3

Hoogendijk
Hoogendijk

Reputation: 100

This code will run through the first 5 records of your dynamical names

for i=1:5
   eval(['A([A.' cell_array{i} ']==5)'])
end

Upvotes: -1

Related Questions