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

1 次查看(过去 30 天)
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

采纳的回答

Mohammad Sami
Mohammad Sami 2020-9-8
编辑:Mohammad Sami 2020-9-8
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 个评论
Robin
Robin 2020-9-8
编辑:Robin 2020-9-8
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by