Call fields of struct more efficiently in a loop

23 次查看(过去 30 天)
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 个评论
Walter Roberson
Walter Roberson 2020-8-22
It is not permitted to use a structure field as a for loop control variable. Only simple unindexed variables can be used.

请先登录,再进行评论。

回答(1 个)

Walter Roberson
Walter Roberson 2020-8-22
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.

类别

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

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by