[英]Negate a matrix in haskell?
If I am using a vector package, how can I get a negative of a matrix? 如果我使用矢量包,我怎么能得到矩阵的负数? Just "Minusing" it doesn't work.
只是“缩小”它不起作用。
So from: 所以来自:
1 2 3
3 4 5
6 7 8
I want to get: 我想得到:
-1 -2 -3
-3 -4 -5
-6 -7 -8
No, multiplying by -1 doesn't work either: 不,乘以-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
I think you are confused about the purpose of the vector library. 我认为你对矢量库的目的感到困惑。 The description of it is:
它的描述是:
An efficient implementation of Int-indexed arrays (both mutable and immutable), with a powerful loop optimisation framework .
Int-indexed数组(可变和不可变)的有效实现,具有强大的循环优化框架。
So it is just an array class - if you want to perform matrix operations on it you will have to code the solutions yourself. 所以它只是一个数组类 - 如果你想对它执行矩阵运算,你将不得不自己编写解决方案。
What you really want is to use a true matrix library. 你真正想要的是使用真正的矩阵库。 hmatrix is a library that does this.
hmatrix是一个执行此操作的库。 Firstly install it using the hmatrix installation instructions .
首先使用hmatrix安装说明进行安装 。
This is how you would write your program using 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 ]
There are heaps of matrix operations with the library, just read the Data.Packed.Matrix and the Numeric.Container docs 有大量的矩阵操作与库,只需读取Data.Packed.Matrix和Numeric.Container文档
Have you tried Data.Vector.map (* (-1))
? 你试过
Data.Vector.map (* (-1))
吗?
For a matrix defined as m :: Vector [Integer]
, that is a Data.Vector.Vector
of lists of Integers, you can 对于定义为
m :: Vector [Integer]
的矩阵,即整数列表的Data.Vector.Vector
,你可以
Data.Vector.map (Prelude.map negate) m
The outer map
maps function (Prelude.map negate)
over the vector. 外部
map
将向量上的函数(Prelude.map negate)
映射。 The inner map
negates all elements of a list. 内部
map
否定了列表的所有元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.