且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用两个矩阵计算余弦相似度

更新时间:2022-02-17 09:28:38

最简单的解决方案是首先使用沿所需维度的逐元素乘法和求和来计算范数:

The simplest solution would be computing the norms first using element-wise multiplication and summation along the desired dimensions:

normA = sqrt(sum(A .^ 2, 2));
normB = sqrt(sum(B .^ 2, 1));

normAnormB现在分别是列向量和行向量.要将A * B中的相应元素除以normAnormB,请使用 bsxfun 像这样:

normA and normB are now a column vector and row vector, respectively. To divide corresponding elements in A * B by normA and normB, use bsxfun like so:

C = bsxfun(@rdivide, bsxfun(@rdivide, A * B, normA), normB);