MATLAB: Help to vectorize this matrix operation

geometric transformationvectorization

Hello, I am trying to translate a shape's convex hull to a bunch of different locations to analyze all the translated convex hulls.
Here is the code I have so far:
TCH=[];
for t=1:3:length(tmat)/3
TCH=[TCH;(CH*tmat(i:i+2,:))'];
end
tmat is a matrix that holds all of the different affine matrices for each different translation so it looks something like this:
tmat =
1 0 0
0 1 0
-94 -64 1
1 0 0
0 1 0
-93 -63 1
1 0 0
0 1 0
-92 -62 1
1 0 0
0 1 0
-91 -61 1
1 0 0
0 1 0
-90 -60 1......
CH is the x y coordinates of the original convex hull with an additional column of 1's so it can be multiplied by the affine matrices. CH looks like this:
CH =
155.0000 124.5000 1.0000
151.0000 124.5000 1.0000
149.5000 126.0000 1.0000
149.5000 138.0000 1.0000
150.5000 152.0000 1.0000
151.5000 155.0000 1.0000
152.5000 157.0000 1.0000
153.0000 157.5000 1.0000
155.0000 157.5000 1.0000
171.0000 151.5000 1.0000
188.0000 144.5000 1.0000
192.0000 142.5000 1.0000
192.5000 142.0000 1.0000
193.5000 140.0000 1.0000
193.5000 139.0000 1.0000
193.0000 138.5000 1.0000
185.0000 134.5000 1.0000
177.0000 131.5000 1.0000
155.0000 124.5000 1.0000
Can someone help me vectorize this loop so it runs faster? It doesn't run too slowly now but this is part of an ongoing effort to increase the efficiency of a VERY slow part of my image processing code. Any help would be greatly appreciated.
THANKS!

Best Answer

  • variant
    [m n] = size(CH);
    k = size(tmat,2);
    out = CH*reshape(permute(reshape(tmat.',n,k,[]),[2 1 3]),3,[]);
    TCH = reshape(permute(reshape(out,m,k,[]),[1 3 2]),[],k);