Permutations of parameters (i.e. Cartesian product) into a multi-dimensional array

前端 未结 1 1582
南旧
南旧 2020-12-12 02:54

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

相关标签:
1条回答
  • 2020-12-12 03:02

    You want ndgrid instead of meshgrid in this case.

    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
    ...
    

    But you want to be getting:

    >> [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
    ...
    

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

    Generalizing to N-dimensions could be done like this:

        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))
    
    0 讨论(0)
提交回复
热议问题