Create a Struct Iteratively

조회 수: 8 (최근 30일)
Johnathan Viernik
Johnathan Viernik 2016년 9월 25일
댓글: Stephen23 2016년 9월 25일
Hello, I'm trying to compare the performance of different algorithms and different parameters at a specific task.
For that, I want to create structs that will contain the results of the different configurations, so that I'll have more convenient access to the results (compared to multidimensional arrays for example).
So let's say for a given algorithm I have 3 configurations for a certain parameter, and 5 options for some other feature. My desired struct should then look something like:
myStruct.param2.feat3 = 50;
where I chose param2 as my desired parameter and the 3rd option for the extra feature, and the result of the algorithm for this set of choices is 50.
I'd like to iterate over the different configuration in a nested for-loop and save the results to the struct according to the state of the loop. I tried defining the different parameters as vectors, and let the indices run through them, but I can't figure out how to pass the value of each index as the field name instead of the index name itself being the field name. That is, I want to have something like
params = [par1,par2,par3];
for i = params
myStruct.i = runAlg(...);
(or myStruct.eval(i) = runAlg(...); or whatever)
end
Is there a way to achieve this? Thanks!
  댓글 수: 1
Stephen23
Stephen23 2016년 9월 25일
Rather than accessing the fieldnames (see answer below), and much better idea would be to simply use non-scalar arrays, which would let you use indexing (fast and efficient).

댓글을 달려면 로그인하십시오.

답변 (1개)

Walter Roberson
Walter Roberson 2016년 9월 25일
params = {'par1','par2','par3'} ;
for idx = 1:length(params)
i = params{idx};
myStruct.(i) = runAlg(...);
end

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by