How to use values from .mat file (nested struct) dependent to the variable name of value

1 visualización (últimos 30 días)
The target is to use the value of a variable in a nested struct from a .mat file. The name of variable consits a dynamic and a static part. Dynamic part is in array Components and the static part is ".fuseboxname". In the following you will find the code with the not working solution and below of this is a running solution witch is solved bad, because of the predefined position of variable name.
Components = ["SeatDriverHeatingCommon"; "SeatDriverVentilatedCommon"; "Sockets12VCommon"]; % Generate variables in vector just for demonstration. Values will handed via function.
evalin('base', 'load(''ConsumerMasterParameters.mat'')'); % Load .mat file for simulation model in workspace
for index = 1 : 3
fuseboxname_array = cat(2,string(Components(index,1)),'.fuseboxname'); % Put variable name and fix string ".fuseboxname" in an array.
fuseboxname_string = join(fuseboxname_array,""); % Generate new variable name by copple variable name with fix string ".fuseboxname"
fuseboxname_value = load('ConsumerMasterParameters',fuseboxname_string ); % Load value of new generated variable name --> doesn't work
end
SeatDriverHeatingCommon.fuseboxname % Just for demonstration, that values can be load by entering variable name
SeatDriverVentilatedCommon.fuseboxname
Sockets12VCommon.fuseboxname
% The following is a working, but bad solution, because the line of the
% variable name is predefined
for jndex = 1 : 3
cell_level_a = struct2cell(load('ConsumerMasterParameters'));
cell_level_b = struct2cell(cell_level_a{jndex,1});
[line_cell,column_cell] = size(cell_level_b);
fuseboxname_bad_solution = cell_level_b{line_cell,1}
end

Respuesta aceptada

Mohammad Sami
Mohammad Sami el 8 de Sept. de 2020
Editada: Mohammad Sami el 8 de Sept. de 2020
There are quite a few options. One option is to use the structfun to apply a function to each field of the function as follows.
a = load('ConsumerMasterParameters.mat');
fuseboxname = structfun(@(x)x.fuseboxname,a);
Second option would be as follows.
for fname = fieldnames(a)'
fusebox = a.(fname{1}).fuseboxname
end
% or if you need the index instead
fnames = fieldnames(a);
for i = 1:length(fnames)
fusebox = a.(fnames{i}).fuseboxname
end
  1 comentario
Robin
Robin el 8 de Sept. de 2020
Editada: Robin el 8 de Sept. de 2020
The third solution is exactly what was needed and works without any changes (copy paste)
fnames = fieldnames(a);
for i = 1:length(fnames)
fusebox = a.(fnames{i}).fuseboxname
end
Thank you very much.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Structures en Help Center y File Exchange.

Productos


Versión

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by