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