How to add multiple variables to a structure

47 visualizaciones (últimos 30 días)
Afzal
Afzal el 13 de En. de 2023
Comentada: Stephen23 el 14 de En. de 2023
I have a cell ('varNames') containing variable names that I want to add to a structure ('s'). I am currently acheiving this using the evaluate command as:
for i=1:length('varNames')
eval(strcat('s.',varNames{i},'=',varNames{i},';'));
end
However, I want to avoid using the evaluate command, as I will be using this code inside a parfor loop to speed up Simulink simulations. I have so far tried the solution here with a method to extract variable names described here as:
getname = @(x) inputname(1);
makeStruct = @(x) struct(getname(x),x);
s = cellfun(makeStruct, varNames);
But it just adds the variable names to the structure 's', not the actual variables. The variables are structures themseleves generated by the ToWorkspace blocks of Simulink.
  1 comentario
Stephen23
Stephen23 el 13 de En. de 2023
Editada: Stephen23 el 13 de En. de 2023
EVAL is completely unnecessary, the approaches you link to are... very complex.
As Jiri Hajek shows, all you need is INPUTNAME() and this:

Iniciar sesión para comentar.

Respuestas (1)

Jiri Hajek
Jiri Hajek el 13 de En. de 2023
Hi, eval is indeed completely unnecessary for your assignment.To create a new field in a structure, for which you have a name defined by a character vector or a string, use parentheses.
s.(newFieldName) = newData;
The newData may of course by a struct. The newFieldName must be string or character vector, which you may supply in a variable, e.g. varNames{i} as in your example.
  7 comentarios
Stephen23
Stephen23 el 14 de En. de 2023
"...as there are many variables, and don't want to assign each variable to the structure without a loop."
That is a sign that your data design probably need to be improved. Instead of creating lots of separate variables, you should probably create one array in the first place. For example, if you are LOADing data from a MAT file, then simply LOAD into an output variable (which is a scalar structure):
S = load(..);
If you only have a handful of variables, then you could use a function like this (untested):
function S = mystruct(varargin)
S = struct();
for k = 1:nargin
S.(inputname(k)) = varargin{k};
end
end

Iniciar sesión para comentar.

Categorías

Más información sobre Simulink Environment Customization en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by