我有兴趣在一堆参数值的排列上计算一个函数。我想保持它对 N 维的通用性,但让我从 3 维开始写出来。使用 生成排列很容易meshgrid
,但我不知道如何将生成的数组重新整形为多维?这是一个起点:
%These are the 3 variations of parameters, with some values.
params1 = [100, 200, 300];%Picking these so it is easy to correlate to the function
params2 = [10, 20];
params3 = [1, 2];
%This generates parameter_values as the cartesian productpermutations.
[vec1, vec2, vec3] = meshgrid(params1, params2, params3);
parameter_values = [vec1(:) vec2(:) vec3(:)];
%Calculates functions on the set of parameters.
%Would have a fancier function, of course, this just makes it easy to see the results.
raw_vals = parameter_values(:,1) + parameter_values(:,2) + parameter_values(:,3);
%Rearrange into a multiarray to access by parameter indices.
f_vals = reshape(raw_vals, [length(params1), length(params2), length(params3)]) %WRONG?
%THE FOLLOWING FAIL BUT WOULD BE EXPECTED WITH THESE PARAMETERS AND THE FUNCTION.
assert(f_vals(2,1,1) == 211)
assert(f_vals(3,2,2) == 322)