Call fields of struct more efficiently in a loop

23 Ansichten (letzte 30 Tage)
Tejas
Tejas am 22 Aug. 2020
Bearbeitet: Tejas am 22 Aug. 2020
I want to do the following more efficiently.
vec.time = [1000,5000];
vec.nest = {'center','corner'};
vec.grid = [50,100,1000];
for i.time = 1:length(vec.time)
p.time = vec.time(i.time);
for i.nest = 1:length(vec.nest)
p.nest = vec.nest(i.nest);
for i.grid = 1:length(vec.grid)
p.grid = vec.grid(i.grid);
%Code
end
end
end
Essentially, the fields of the structs vec, i, p will be the same. The vec struct contains all the values that I want to run in a loop, the i struct acts as a counter for them, and the p struct runs the code with the particular value selected. Is there a way such that I can call the fields by their order number rather than their name? Though, I do want the p struct with all the field names in the end, since the rest of the code depends on it. Thank you!
Edit: I've been looking into similar problems, and I think it might be done using struct2cell and cell2struct. For this particular example, if I have an array as
order = [1 1 1 ; 1 1 2 ; 1 1 3 ; 1 2 1 ; 1 2 2 ; 1 2 3 ;
2 1 1 ; 2 1 2 ; 2 1 3 ; 2 2 1 ; 2 2 2 ; 2 2 3];
then what I can do is
vec_cell = struct2cell(vec);
fields = fieldnames(vec);
p_cell = cell(length(vec_cell),1);
for i_order = 1:length(order)
for i_cell = 1:length(vec_cell)
p_cell{i_cell} = vec_cell{i_cell}(order(i_order,i_cell));
end
p = cell2struct(p_cell,fields);
%Code
end
While this may not be as efficient, it certainly seems more robust, since I only need to add information to the vec struct, and it would calculate the p struct for every iteration. I do need help with constructing the order array, given the number of fields in the vec struct, and the length of each field. Thank you!
Edit2: I realised that values in vec.nest cannot be assigned this way, since they are in a cell, while others are in an array. But I can resolve this by assigning values to them (1 is 'center', 2 is 'corner').
  1 Kommentar
Walter Roberson
Walter Roberson am 22 Aug. 2020
It is not permitted to use a structure field as a for loop control variable. Only simple unindexed variables can be used.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Walter Roberson
Walter Roberson am 22 Aug. 2020
Is there a way such that I can call the fields by their order number rather than their name?
fn = fieldnames(appropriate_structure);
for K = 1 : length(fn)
appropriate_structure.(fn{K}) %effectively call by number
end
Though, I do want the p struct with all the field names in the end
Consider using structfun()
Note that structfun() is not necessarily more efficient than a for loop: it is more compact than a for loop, but structfun does a for loop internally.

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by