0
votes

Is there a way I could vectorize this for loop and make it faster in MATLAB for large n?

for j=1:n
  % find point coordinate in a different basis
  pt_2(:,:,j) = Mat(:,:,t(j)) * pt_1(:,:,j);
end

where pt_1, pt_2 are 3x1xn arrays, Mat is a 3x3xm array, and t is a nx1 vector. The loop wants to get n point coordinates transformed from n coordinates of another linear space, and there are m different transformations.

1
Can you provide example of the inputs, so that we can execute this code. Its difficult to check it if you cant run the code. - Marcin
The values come from some prior calculations but maybe you could use some arbitrary values: e.g. n=200000; m=20; pt_1=ones(3,1,n); Mat=ones(3,3,m); pt_2=zeros(3,1,n); It's just for testing the loop execution time. - CathIAS
Thanks. But t is still missing. - Marcin
Oh sorry, maybe t=ones(n,1). Sounds silly but as long as it is accessing values every time. t is a mapping from [1,n] to [1,m], it decides which of the m categories does each number from 1 to n belong to. - CathIAS

1 Answers

0
votes

An equivalent form is to take pt_1(:,:,j) ,transpose it and repeat it 3 times and form a 3 * 3 matrix so we have:

pt_1_j = [pt_1(:,:,j).' ; pt_1(:,:,j).' ; pt_1(:,:,j).'];

then we can multiply Mat(:,:,t(j)) by pt_1_j elementwise

M = Mat(:,:,t(j)) .* pt_1_j;

then sum M along its 2nd dimension

pt_2(:,:,j) = sum(M,2);

also the same thing can be done with bsxfun

M = bsxfun(@times , Mat(:,:,t(j)) , pt_1(:,:,j).');
pt_2(:,:,j) = sum(M,2)

or

pt_2(:,:,j) = sum(bsxfun(@times , Mat(:,:,t(j)) , pt_1(:,:,j).'),2)

Generalizing the above method to 3 dimensions:

Mat is precomputed for all iterations so Mat(:,:,t) is use instead of M(:,:,t(j)) and permute is used for transpose of 3D data.

then apply sum(bsxfun...

pt_2 = sum(bsxfun(@times, Mat(:,:,t), permute(pt_1,[2 1 3])), 2);