繁体   English   中英

否定haskell中的矩阵?

[英]Negate a matrix in haskell?

如果我使用矢量包,我怎么能得到矩阵的负数? 只是“缩小”它不起作用。

所以来自:

 1 2 3
 3 4 5
 6 7 8

我想得到:

 -1 -2 -3
 -3 -4 -5
 -6 -7 -8

不,乘以-1也不起作用:

let m = fromList [[10,20,30], [11,12, 13]]
Prelude Data.Vector> :t m
m :: Vector [Integer]
Prelude Data.Vector> (-1)*m


<interactive>:1:3:
    No instance for (Num (Vector [Integer]))
      arising from the literal `1'
    Possible fix:
      add an instance declaration for (Num (Vector [Integer]))
    In the expression: 1
    In the first argument of `(*)', namely `(- 1)'
    In the expression: (- 1) * m

我认为你对矢量库的目的感到困惑。 它的描述是:

Int-indexed数组(可变和不可变)的有效实现,具有强大的循环优化框架。

所以它只是一个数组类 - 如果你想对它执行矩阵运算,你将不得不自己编写解决方案。

你真正想要的是使用真正的矩阵库。 hmatrix是一个执行此操作的库。 首先使用hmatrix安装说明进行安装

这是你用hmatrix编写程序的方法:

> import Data.Packed.Matrix
> let matrix = (3><3)[1,2,3,3,4,5,6,7,8]
> mapMatrix negate matrix
(3><3)
 [ -1.0, -2.0, -3.0
 , -3.0, -4.0, -5.0
 , -6.0, -7.0, -8.0 ]

有大量的矩阵操作与库,只需读取Data.Packed.MatrixNumeric.Container文档

你试过Data.Vector.map (* (-1))吗?


对于定义为m :: Vector [Integer]的矩阵,即整数列表的Data.Vector.Vector ,你可以

Data.Vector.map (Prelude.map negate) m

外部map将向量上的函数(Prelude.map negate)映射。 内部map否定了列表的所有元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM