Phab
Phab

Reputation: 495

get struct data by name (Matlab)

Is there an easy way to get the data out of a struct by searching for his name?

I'm thinking of a struct like this:

test = struct('A', ...
[struct('Name','Adam','Data',[1 2 3]) ...
struct('Name','Eva','Data',[11 12 13])]);

Now I want to access the Data field by searching for 'Adam' or 'Eva'.

something like this:

getStructDataByName(test,'Adam')

Does someone know a script or has an idea doing this with not too much effort?

Edit:

This is my current solution:

function getDataByName(struct,fieldname)

    names = getAllDataNames(struct);

    thisIdx = strcmp(names,fieldname);
    % or
    % thisIdx = ismember(names,fieldname);

    struct.A(thisIdx).Data

end


function names = getAllDataNames(struct)

    for idx = 1:length(struct.A)
        names(idx,:) = {struct.A(idx).Name};
    end

end

Should I use strcmp() or ismember()?

Upvotes: 0

Views: 1234

Answers (1)

Dan
Dan

Reputation: 45752

Try this:

test.A(strcmp({test.A.Name}, 'Eva')).Data

Basically if you call test.A.Name it will return a comma separated list of all the names. So by putting {} around that we concatenate all those into a cell matrix. We can then use strcmp to find the indices that match the name you're after. Note that if your names can be repeated then this will return a comma separated list over all so you might want to put the curly braces around the entire expression in that case.

Upvotes: 5

Related Questions