将参数(即笛卡尔积)排列成多维数组 [英] Permutations of parameters (i.e. Cartesian product) into a multi-dimensional array

查看:104
本文介绍了将参数(即笛卡尔积)排列成多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我感兴趣的是根据一系列参数值的排列来计算函数.我想让它对N个维度通用,但是让我从3个维度开始写出来.使用meshgrid生成排列很容易,但是我不知道如何将结果数组重塑为多维?这是一个起点:

I am interested in calculating a function on a bunch of permutations of parameter values. I want to keep it generic to N dimensions, but let me write it out in 3 dimensions to start with. Generating the permutations is easy enough with meshgrid, but I can't figure out how to reshape the resulting array back to the multidimensions? Here is a starting point:

%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)

推荐答案

您要在这种情况下,使用ndgrid 代替 meshgrid

meshgrid的语法为[X,Y] = meshgrid(xgv,ygv),这会导致Y(:)变化最快,而不是X(:).有关更多详细信息,请参见网格数据表示. .换句话说,您正在得到

meshgrid's syntax is [X,Y] = meshgrid(xgv,ygv) which causes Y(:) to vary fastest rather than X(:). See Gridded Data Representation for more details. In other words, you are getting

>> [vec1, vec2, vec3] = meshgrid(params1, params2, params3)
vec1(:,:,1) =
   100   200   300
   100   200   300
vec1(:,:,2) =
   100   200   300
   100   200   300
vec2(:,:,1) =
    10    10    10
    20    20    20
vec2(:,:,2) =
    10    10    10
    20    20    20
...

但是你想得到:

>> [vec1, vec2, vec3] = ndgrid(params1, params2, params3)
vec1(:,:,1) =
   100   100
   200   200
   300   300
vec1(:,:,2) =
   100   100
   200   200
   300   300
vec2(:,:,1) =
    10    20
    10    20
    10    20
vec2(:,:,2) =
    10    20
    10    20
    10    20
...

如果切换到ndgrid,则将得到预期的f_vals(2,1,1) == 211.

If you switch to ndgrid, then you get f_vals(2,1,1) == 211 as intended.

可以概括为N维:

    params = {[100, 200, 300],[10, 20],[1, 2]};
    vecs = cell(numel(params),1);
    [vecs{:}] = ndgrid(params{:});
    parameter_values = reshape(cat(numel(vecs)+1,vecs{:}),[],numel(vecs));
    raw_vals = sum(parameter_values,2);
    f_vals = reshape(raw_vals,cellfun(@numel,params))

这篇关于将参数(即笛卡尔积)排列成多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆