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

2 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Mohammad Sami
Mohammad Sami il 8 Set 2020
Modificato: Mohammad Sami il 8 Set 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 Commento
Robin
Robin il 8 Set 2020
Modificato: Robin il 8 Set 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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Structures in Help Center e File Exchange

Prodotti


Release

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by