MATLAB中的余弦相似性



我有一个1000x1000x3 3D矩阵。我想计算一个集合的每个3D向量与每个3D矢量之间的角度的余弦,我可以从3D矩阵中垂直提取。然后,我应该能够使用具有最大余弦相似性(即最小角度(的向量索引创建一个1000x1000矩阵。

如何对此计算或至少某些部分进行矢量化?目前,我用嵌套的循环(大量时间和开销(来做。

我找不到在第三维上使用标准的函数,但我认为这也有效。

a = rand(1000,1000,3)-.5; %dataset
na = sqrt(a(:,:,1).^2+a(:,:,2).^2+a(:,:,3).^2); %the norm of each vector
b = [1.2,1,3]; %vector to compare angle against
nb = norm(b); %the norm of the compare vector
b = repmat(b,[1000,1000]);
b = reshape(b,[1000,1000,3]); %1000x1000 copies of b
pl = a.*nb + na.*b; 
mn = a.*nb - na.*b;
npl = sqrt(pl(:,:,1).^2+pl(:,:,2).^2+pl(:,:,3).^2);  
nmn = sqrt(mn(:,:,1).^2+mn(:,:,2).^2+mn(:,:,3).^2);  
theta = 2 * atan(nmn./npl); %angle between [0 and pi] as expected

数学是此公式的改编:

theta = 2 * atan(norm(x*norm(y) - norm(x)*y) / norm(x * norm(y) + norm(x) * y))

最新更新