Call fields of struct more efficiently in a loop

조회 수: 26 (최근 30일)
Tejas
Tejas 2020년 8월 22일
편집: Tejas 2020년 8월 22일
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