Reputation: 61111
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:
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
Upvotes: 3
Views: 643
Reputation: 14678
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 .
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. Firstly install it using the hmatrix installation instructions.
This is how you would write your program using 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
Upvotes: 11
Reputation: 11726
Have you tried Data.Vector.map (* (-1))
?
For a matrix defined as m :: Vector [Integer]
, that is a Data.Vector.Vector
of lists of Integers, you can
Data.Vector.map (Prelude.map negate) m
The outer map
maps function (Prelude.map negate)
over the vector. The inner map
negates all elements of a list.
Upvotes: 4