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

adressfieldinput argumentsstruct

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.

Best Answer

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.