How to address the fields of a struct with function input arguments
9 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Immelmann
el 17 de En. de 2015
Comentada: Stephen23
el 13 de Abr. de 2017
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.
1 comentario
Respuesta aceptada
Guillaume
el 17 de En. de 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.
0 comentarios
Más respuestas (2)
Geoff Hayes
el 17 de En. de 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!
Ver también
Categorías
Más información sobre Scope Variables and Generate Names en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!