如何比较f#矩阵中的单个值? [英] How to compare individual values in f# matrices?
问题描述
我正在尝试自学f#. 对于我正在研究的程序,我想逐点比较2个矩阵的各个元素. 矩阵的大小均为1 * N.这些是矩阵的原因是因为它们是使用标准F#PowerPack执行的先前计算的结果.经过这些计算,我很乐意将它们转换为其他集合,或者使用其他Matrix数学库. 我需要的是一个函数,它接收2个矩阵(本质上是向量),并输出两个向量不相等的索引位置的列表.
I am trying to teach myself f#. For a program I am working on, I want to compare individual elements of 2 matrices, point wise. The matrices are both of size 1*N. The reason these are matrices is because they are the result of previous computations, performed using the standard F# PowerPack. I am happy to convert them to some other collection after these computations or use some other Matrix math library. What I need is a function that takes 2 matrices (which are essentially vectors) and outputs a List of index positions where the 2 vectors are not equal.
例如: 输入:[[5; 6; 7; 8; 9]]; [[3; 6; 3; 8; 3]] 输出:[1; 3; 5]
For example: Input: [[5;6;7;8;9]]; [[3;6;3;8;3]] Output: [1;3;5]
我的大脑仍然以命令式的风格思考很多,我还没有完全了解模式匹配!
My brain still thinks very much in the imperative style and I haven't quite got my head around pattern matching yet!
推荐答案
如果您使用的是Powerpack,则可以执行以下操作:
If you're using Powerpack you can do this:
let getDifferences x y =
Matrix.Generic.foldi (fun _ j s e -> if e = 0 then s else (j+1)::s) [] (x-y)
|> List.rev // if you care about the order
通过查看样本数组,我假设您的矩阵x
和y
是类型为int
的通用矩阵.
By looking at your sample arrays I assume your matrices x
and y
are Generic matrices of type int
.
如果不是这种情况,请删除.Generic
并将0
更改为0.0
,但要注意
If this is not the case, remove .Generic
and change 0
for 0.0
but be aware that comparing floats for equality might be not a good idea, depending on your specific scenario.
这篇关于如何比较f#矩阵中的单个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!