Octave : Vectorized implementation of the cartesian product of two vectors

Viewed 126

Is it possible to achieve what the code below does without using a for loop ?

Basically we take each pair of row vectors from the matrices a and b, broadcasting them into a matrix, do a component wise multiplication and set the result to the result vector.

Thanks

m = 4;
n1 = 3;
n2 = 2;

% result is a 3d array of dimensions m * n1 * n2
result = reshape(1:24, m, n1, n2);

a = reshape(1:12, m, n1)
b = reshape(1:8, m, n2)

for i = 1:m
 mat = a(i, :)' .* b(i, :);

 result(i, :, :) = mat;
endfor
1 Answers

Broadcasting can also be applied to multiply multidimensional arrays:

 result  = a .* reshape (b, m, 1, n2);
Related