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
0 个评论
采纳的回答
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!