matlab - Getting the N-dimensional product of vectors -


i trying write code 'n-dimensional product' of vectors. example, if have 2 vectors of length l, x & y, '2-dimensional product' regular vector product, r=x*y', each entry of r, r(i,j) product of i'th element of x , j'th element of y, aka r(i,j)=x(i)*y(j).

the problem how elegantly generalize in matlab arbitrary dimensions. had 3 vectors, x,y,z, want 3 dimensional array, r, such r(i,j,k)=x(i)*y(j)*z(k).

same thing 4 vectors, x1,x2,x3,x4: r(i1,i2,i3,i4)=x1(i1)*x2(i2)*x3(i3)*x4(i4), etc...

also, not know number of dimensions beforehand. code must able handle arbitrary number of input vectors, , number of input vectors corresponds dimensionality of final answer.

is there easy matlab trick , avoid going through each element of r specifically?

thanks!

i think "regular vector product" mean outer product.

in case, can use ndgrid function. more using bsxfun it's little more straightforward.

% make vectors w = 1:10; x = w+1; y = x+1; z = y+1;  vecs = {w,x,y,z};  nvecs = length(vecs);  [grids{1:nvecs}] = ndgrid(vecs{:});  r = grids{1}; i=2:nvecs     r = r .* grids{i}; end;  % check results i=1:10     j=1:10         k=1:10             l=1:10                 v(i,j,k,l) = r(i,j,k,l) == w(i)*x(j)*y(k)*z(l);             end;         end;     end; end;  all(v(:))      ans = 1 

Comments