For loop to access fields from structure and save them in an array
1 view (last 30 days)
Show older comments
I have a humongus structure known as
big_struct
with several fields. Each of these fields are doubles (30 x 1) dimension. So, they contain 30 numerical values.
Examples of these doubles are price_SH_many_shocks_SH, PIE_AM_many_shocks_SH, etc
In total, there are about 1000 fields in big_struct, but I only have to use a few them. I'd like store those in arrays, in this case (30 x 1) doubles, manipulate them, then append each of the selected field in a (30 x 3) double. Then, I will make plots.
impulse_len = 5;
town_vec = ["South Hadley", "Amherst", "State College"];
town_code = ["SH", "AM", "SC"];
f_SH_pie = big_struct.PIE_SH_many_shocks_SH; % (30 x 1)
f_SH_pie =[repmat(f_SH_pie(1),impulse_len,1); f_SH_pie]; % (40 x 1)
f_SH_pie = f_SH_pie(1:end-impulse_len,:); % (30 x 1)
f_AM_pie = big_struct.PIE_AM_many_shocks_SH;
f_AM_pie =[repmat(f_AM_pie(1),impulse_len,1); f_AM_pie];
f_AM_pie = f_AM_pie(1:end-impulse_len,:);
f_SC_pie = big_struct.PIE_SC_many_shocks_SH;
f_SC_pie =[repmat(f_SC_pie(1),impulse_len,1); f_SC_pie];
f_SC_pie = f_SC_pie(1:end-impulse_len,:);
pie_mat = [f_SH_pie, f_AM_pie, f_SC_pie];
Here's what I tried, but it's obviously wrong
for i = 1:length(town_code)
"f_"+ (i) + "_pie" = big_struct.PIE_ + (i) +" _many_shocks_SH";
"f_"+ (i) + "_pie" = [repmat(f_(i)_pie(1),impulse_len,1); f_(i)_pie];
"f_"+ (i) + "_pie" = f_i()_pie(1:end-impulse_len,:);
end
If you could show me how to fix it, I would really appreciate it. Thanks a lot.
Answers (1)
Walter Roberson
on 16 Aug 2022
town_codes = ["SH", "AM", "SC"];
fields = "PIE_" + town_codes + "_many_shocks_SH";
f_pie_cell = arrayfun( @(field) big_struct.(field)([ones(1,impulse_len), 1:end-impulse_len]), fields, 'uniform', 0);
pie_mat = [f_pie_cell{:}];
new_fields = "f_" + town_codes + "pie";
f_pie = cell2struct(f_pie_cell, new_fields, 2);
The result, f_pie, will be a struct with fields f_SH_pie, f_AM_pie, f_SC_pie
0 Comments
See Also
Categories
Find more on Environment and Settings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!