Vectorize the function call of two vectors (process the matrix as an array of a vector)

I want to calculate the cumulative cosine distance between sets of vectors.
The natural representation of many vectors is the matrix ... but how do I outline the following?

function d = cosdist(P1,P2) ds = zeros(size(P1,2),1); for k=1:size(P1,2) %#used transpose() to avoid SO formatting on ' ds(k)=transpose(P1(:,k))*P2(:,k)/(norm(P1(:,k))*norm(P2(:,k))); end d = prod(ds); end 

Of course I can write

 fz = @(v1,v2) transpose(v1)*v2/(norm(v1)*norm(v2)); ds = cellfun(fz,P1,P2); 

... as long as I rebuild my matrices as arrays of vector cells. Is there a better / fully digital way?
Also, will there be cellfun, arrayfun, etc. Use vector instructions and / or multithreading?

The note is probably redundant in the current company, but for column vectors v1'*v2 == dot(v1,v2) and significantly faster in Matlab.

+4
source share
2 answers

Since P1 and P2 are the same size, here you can perform basic operations. v1'*v is equal to sum(v1.*v2) , by the way.

 d = prod(sum(P1.*P2,1)./sqrt(sum(P1.^2,1) .* sum(P2.^2,1))); 
+5
source

@Jonas had the right idea, but the normalizing denominator might be wrong. Try instead:

 %# matrix of column vectors P1 = rand(5,8); P2 = rand(5,8); d = prod( sum(P1.*P2,1) ./ sqrt(sum(P1.^2,1).*sum(P2.^2,1)) ); 

You can compare this with the results returned by the PDIST2 function:

 %# PDIST2 returns one minus cosine distance between all pairs of vectors d2 = prod( 1-diag(pdist2(P1',P2','cosine')) ); 
+3
source

Source: https://habr.com/ru/post/1338242/


All Articles