Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I express this large number of computations without for loops?

I work primarily in MATLAB but I think the answer should not be too hard to carry over from one language to another.

I have a multi-dimensional array X with dimensions [n, p, 3]. I would like to calculate the following multi-dimensional array.

T = zeros(p, p, p)
for i = 1:p
for j = 1:p
for k = 1:p
T(i, j, k) = sum(X(:, i, 1) .* X(:, j, 2) .* X(:, k, 3));
end
end
end

The sum is of the elements of a length-n vector. Any help is appreciated!

like image 761
Open Season Avatar asked Dec 08 '22 13:12

Open Season


1 Answers

You only need some permuting of dimensions and multiplication with singleton expansion:

T = sum(bsxfun(@times, bsxfun(@times, permute(X(:,:,1), [2 4 5 3 1]), permute(X(:,:,2), [4 2 5 3 1])), permute(X(:,:,3), [4 5 2 3 1])), 5);

From R2016b onwards, this can be written more easily as

T = sum(permute(X(:,:,1), [2 4 5 3 1]) .* permute(X(:,:,2), [4 2 5 3 1]) .* permute(X(:,:,3), [4 5 2 3 1]), 5);
like image 112
Luis Mendo Avatar answered Jan 18 '23 03:01

Luis Mendo