我正在尝试计算协方差矩阵
运算符'expr。[idx]'已用于不确定对象
类型基于此程序点之前的信息。考虑添加
进一步的类型约束CovMatrix.[a,b]
如何解决这个问题以及为什么会发生?
let FirstSeq = {1.0..10.0}
let SecondSeq = {20.0..30.0}
let All = seq {yield (0,FirstSeq); yield (1,SecondSeq)}
let cov(first:seq<float>)(second:seq<float>) =
Seq.map2 (*) first second
|> Seq.average
|> fun x -> x - Seq.average first * Seq.average second
let CreateCovMatrix(strangeList:seq<int * seq<float>>) =
let Size = Seq.length strangeList
let CovMatrix = Array2D.init Size Size
let CalculateCovMatrix =
for (a, i) in strangeList do
for (b, j) in strangeList do
CovMatrix.[a,b]=cov(i)(j)
CalculateCovMatrix
let result = CreateCovMatrix(All)
printf "%A" result
最佳答案
函数Array2D.init
具有3个参数,您缺少最后一个参数,即初始化函数。
您可以通过编写以下内容快速修复它:
let CovMatrix = Array2D.init Size Size (fun _ _ -> 0.)
然后,您将发现下一个问题:可变引用的分配是
<-
运算符,而不是=
运算符,用于比较和进行绑定。因此,您的函数将如下所示:
let CreateCovMatrix(strangeList:seq<int * seq<float>>) =
let Size = Seq.length strangeList
let CovMatrix = Array2D.init Size Size (fun _ _ -> 0.)
let CalculateCovMatrix =
for (a, i) in strangeList do
for (b, j) in strangeList do
CovMatrix.[a,b] <- cov(i)(j)
CalculateCovMatrix
但是,您可以使用函数
Array2D.zeroCreate
来代替指定忽略输入并始终返回零的函数:let CovMatrix = Array2D.zeroCreate Size Size
关于arrays - F#在多维数组中写入值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47003597/