MATLAB: Can this GPU code snippet be redone without nested loops

gpuarraynested loops

Hello, I have two matrices: matrix1 is a logical array of 1s and 0s (1000 x 800) matrix2 is a different logical array (2000 x 800)
I am essentially taking the first row of matrix 1 and calculating the row summation of common elements / total number of elements. Both of these arrays are gpuArrays. What I finding out:
for j=gpuArray.colon(1,x)
for k=gpuArray.colon(1,y)
output(j,k)=sum(matrix1(j,:) & matrix2(k,:)) / sum(matrix1(j,:) | matrix2(k,:))
end
end
Runs very fast for small values of x and y, but once x,y is large is takes exponentially longer to run on the GPU
I am investigating the use of repmat here but I am not sure how to implement. Any ideas here? Or if there is another option for to get rid of the nested for loops?
Thanks

Best Answer

The GPU isn't going to work well with your nested loops. This looks like a classic case for bsxfun:
matrix1 = permute(matrix1, [1 3 2]);
matrix2 = permute(matrix2, [3 1 2]);
output = sum( bsxfun(@and, matrix1, matrix2), 3 ) ./ ...
sum( bsxfun(@or, matrix1, matrix2), 3);
I can't promise it will run faster than on your CPU though, if you have a lot of cores.