# copyright Sergei steshenko, 2012. # released under 3 clause BSD license. # tested under octave-3.6.2. # Matlab (tm) user are explicitly encouraged to to trivially modify the code ('#' -> '%') if they like it and wnat to use it. # the function is supposed to implement functionality similar to associative arrays in Perl/Python/C++ function os = consistent_struct(varargin) if(rem(length(varargin),2)) error("there must be even number of input arguments"); endif for struct_field_number = 1:2:length(varargin) #fprintf(stderr, "key: %s\n", varargin{struct_field_number}); key = varargin{struct_field_number}; # no check of 'key' correctness is performed val = varargin{struct_field_number + 1}; eval(sprintf("os.%s=val;", key)); # the above 'eval' is ugly, but I do not know how to do it better - I need some kind of 'add_field_value_pair_to_struct' function endfor endfunction # comment out the following test cases if you want yo just use the function os = consistent_struct("one", [1 2 3], "two", [5 6 7 8; 9 10 11 12], "three", 33, "four", {"foo", 44, "bar"}); # Przemek Klosowski's test case: samples = consistent_struct\ ( "patient", {"Bob", "Kevin", "Bob" , "Andrew"}, "age", [ 45 , 52 , 45 , 23 ], "protein", {"H2B", "CDK2" , "CDK2", "Tip60" }, "tube" , [ 3 , 5 , 2 , 18 ] );