c# - 填充没有 double 的矩阵

标签 c# matrix

我正在开发一个基于项目的协作过滤器,为此您需要项目之间的相似性。我发现创建如下所示的矩阵效果很好,但我现在想阻止它计算 double 。

我将用一个例子来解释我的意思。假设您有一个包含 5 个项目的列表,每个项目都有基于相似性的评级。

计算相似度后,我得出了以下矩阵:

     I1 | I2 | I3 | I4 | I5 |
I1 |  1 | 0.5| 0.3| 0.2| 0.9|
I2 | 0.5|  1 | 0.2| 0.1| 0.8| 
I3 | 0.3| 0.2|  1 | 0.5| 0.1|
I4 | 0.2| 0.1| 0.5|  1 | 0.7|
I5 | 0.9| 0.8| 0.1| 0.7|  1 |

我使用以下代码来执行此操作:

//allItems is a list of the 5 items
foreach (var item1 in allItems)
    foreach (var item2 in allItems)
        ComputeSimilarity(item1, item2);

//ComputeSimilarity(); returns a double, a.k.a. the similarity between items

您可以忽略该函数的内部工作原理,因为它工作正常,我只是无法弄清楚如何更改代码,因此它不会将所有内容计算两次。

如何更改此函数以使计算的矩阵看起来像这样?

     I1 | I2 | I3 | I4 | I5 |
I1 |    | 0.5| 0.3| 0.2| 0.9|
I2 |    |    | 0.2| 0.1| 0.8| 
I3 |    |    |    | 0.5| 0.1|
I4 |    |    |    |    | 0.7|
I5 |    |    |    |    |    |

请告诉我是否需要详细说明!提前致谢!

最佳答案

这应该可以做到:

int n = allItems.Length;

double[,] similarity = new double[n,n];

for (int i = 0; i < n; ++i)
{
    for (int j = i + 1; j < n; ++j)
    {
        similarity[i, j] = computeSimilarity(allItems[i], allItems[j]);
    }
}

关于c# - 填充没有 double 的矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40509914/

相关文章:

c# - 错误 : A project with an out put type of class library

c# - 如何在 ASP.NET Core 中强制执行小写路由?

c# - ValueTypes 会导致 GC 吗?

c - 从C中的txt文件中读取未知大小的矩阵

performance - 仅计算矩阵平方的对角线的快速方法

matrix - 在 matlab/octave 中的矩阵的每 2 个元素之间添加零

javascript - 使用javascript在图像上覆盖网格,需要帮助获取网格坐标

python - 使用 numpy 数组通过索引加速获取边缘矩阵

c# - 列表框选择更改事件 : get the value before it was changed

c# - 如何使用 LINQ to Entities 包含另一个表中的一个特定行