How to address the fields of a struct with function input arguments

10 views (last 30 days)
Hallo
i have a function with input arguments like
function FUNC(x,y)
and trying to work with struct fields within the function. I can load it with:
load(['Struct_Nr' num2str(x)]);
but i cant adress the fields using x, y
ans = mean(['Struct_Nr' num2str(x) 'Field_Nr' num2str(y)]) %does not work for example
I need char to variable or something like that.

Accepted Answer

Guillaume
Guillaume on 17 Jan 2015
You shouldn't be using dynamic variable names in the first place as you lose syntax checking, optimisation and ease of debugging. But anyway, to access dynamic variables you have to use eval:
s = eval(sprintf('Struct_Nr%d.Field_Nr%d', x, y))
Note that dynamic fields can be accessed using brackets:
s = struct('Field_1', 0, 'Field_2', 1)
fidx = 1;
fldval = s.(sprintf('Field_%d', fidx))
Finally, don't use ans as variable name. It's used by matlab.

More Answers (2)

Geoff Hayes
Geoff Hayes on 17 Jan 2015
Immelmann - to be clear, you have a number of structs that have been saved to individual files named (for example), Struct_Nr1.mt, Struct_Nr2.mat, etc., and each file has a single structure of the same name? What are the field names? Are they individually numbered like Field_Nr1, Field_Nr2, etc.?
I guess the problem that you are experiencing is that when you load the file as
load(['Struct_Nr' num2str(x)]);
you now have a local variable whose name is Struct_Nr1 (for example), with no real way to access it or its fields without referring back to the x. If you can't format all of your struct data in to some sort of matrix or cell array (and so avoid all the multiple files), then you could try the following
function FUNC(x,y)
% create a structure that will have the single variable loaded from file
myStruct = load(['Struct_Nr' num2str(x)]);
% get the fields of this structure (and there will just be one, that which
% corresponds to the structure loaded from file)
varNameCellArray = fields(myStruct);
% so you know the variable name, and you wish to access a particular field
% from it to calculate the mean
avg = mean(myStruct.(char(varNameCellArray)).(['Field_Nr' num2str(y)]));
% etc.
Note how we use char to wrap varNameCellArray to convert the single element cell array to a string. We then access the Field_Nr in a similar manner.
Try the above and see what happens!

Immelmann
Immelmann on 17 Jan 2015
Thanks a lot!
eval(sprintf()) is what i coudnt find. I just tried this functions individually.
It is all about a engine test block data, which is packed in a struct witch fields in a struct witch fields in a struct witch fields .... . So i think
eval(sprintf('Struct_Nr%d.Field_Nr%d', x, y))
is the best way for me.
One other problem i have is here catool but no one has an advice for me :'(

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!