Create a grid in a matrix with a total number of dimensions

Problem

I have a vector wcontaining elements n. I do not know nin advance.

I want to create an n-dimensional grid gwhose values ​​range from grid_minto grid_maxand get a "dimensional" product wand g.

How to do it for arbitrary n?


Examples

For simplicity, we say that grid_min = 0and grid_max = 5.

Happening: n=1

>> w = [0.75];
>> g = 0:5

ans =

     0     1     2     3     4     5

>> w * g

ans =

         0    0.7500    1.5000    2.2500    3.0000    3.7500

Happening: n=2

>> w = [0.1, 0.2];
>> [g1, g2] = meshgrid(0:5, 0:5)

g1 =

     0     1     2     3     4     5
     0     1     2     3     4     5
     0     1     2     3     4     5
     0     1     2     3     4     5
     0     1     2     3     4     5
     0     1     2     3     4     5


g2 =

     0     0     0     0     0     0
     1     1     1     1     1     1
     2     2     2     2     2     2
     3     3     3     3     3     3
     4     4     4     4     4     4
     5     5     5     5     5     5

>> w(1) * g1 + w(2) * g2

ans =

         0    0.1000    0.2000    0.3000    0.4000    0.5000
    0.2000    0.3000    0.4000    0.5000    0.6000    0.7000
    0.4000    0.5000    0.6000    0.7000    0.8000    0.9000
    0.6000    0.7000    0.8000    0.9000    1.0000    1.1000
    0.8000    0.9000    1.0000    1.1000    1.2000    1.3000
    1.0000    1.1000    1.2000    1.3000    1.4000    1.5000

Now suppose the user passes in a vector w, and we do not know how many elements ( n) it contains. How to create a grid and get a product?

+4
1
%// Data:
grid_min = 0;
grid_max = 5;
w = [.1 .2 .3];

%// Let go:    
n = numel(w);
gg = cell(1,n);
[gg{:}] = ndgrid(grid_min:grid_max);
gg = cat(n+1, gg{:});
result = sum(bsxfun(@times, gg, shiftdim(w(:), -n)), n+1);

:

( gg) ndgrid, n, . n - (gg{1}, gg{2} ..) n+1 - ( cat), gg n+1 - . w n+1 - (shiftdim), gg, bsxfun, n+1 - .

Edit:

@Divakar,

sz_gg = size(gg);
result = zeros(sz_gg(1:end-1));
result(:) = reshape(gg,[],numel(w))*w(:);

, Matlab , bsxfun (., , ).

+6

All Articles