0

I'm trying to automate a process for getting information out of an array of structs.

I have the following code:

function [data] = extractData(struct,str)

data = {};
for i = 1:length(struct)
    data{i} = struct(i).str;
end

The problem is that I want to provide the str value referring to a pre-determined field. In it's current form, it won't accept str and say "str is an unknown field."

alvarezcl
  • 579
  • 6
  • 22
  • 1
    possible duplicate of [How do I access structure fields dynamically?](http://stackoverflow.com/questions/1882035/how-do-i-access-structure-fields-dynamically) – mbschenkel Apr 12 '14 at 22:28
  • 1
    I would recommend not to use `struct` as a variable name since it's already the name of, well, structs ... and to read [this](http://www.mathworks.ch/ch/help/matlab/matlab_prog/generate-field-names-from-variables.html). – mbschenkel Apr 12 '14 at 22:31

1 Answers1

1

The easiest way to do this would to use:

function data = extractData(struct)
str = fieldnames(struct);
data = {};
    for i = 1:numel(str)
        data{i} = struct.(str{i});
    end
end

You may also want to consider a few different things here. First, you may want to change the name of your struct to a different name as was said above. Also you might want to look into cell arrays. Cell arrays can hold variables of different types and lengths and are easier you use.

RDizzl3
  • 846
  • 8
  • 18