Create a Struct Iteratively

15 次查看(过去 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