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

조회 수: 4 (최근 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에서 Data Types에 대해 자세히 알아보기

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by