Alon
Alon

Reputation: 2929

Haskell - Convert between matrix types

I am using the Numeric.LinearAlgebra library. This is my code:

customConv :: Matrix Z
customConv = conv2 ((3><3)[1..]) ((1><1)[1.1]) 

My problem is that I want that the output will be from type Matrix Z.

Now the type is not Z because the conv is with 1.1

Is there any function to round all the values of the matrix and make it from this type?

Upvotes: 0

Views: 77

Answers (1)

Lemming
Lemming

Reputation: 4205

It depends on how you want to round the values. If you want to round to the nearest integer, then you can use cmap round:

λ> cmap round $ conv2 ((3><3)[1..]) ((1><1)[1.1 :: R]) :: Matrix Z
(3><3)
 [ 1, 2,  3
 , 4, 6,  7
 , 8, 9, 10 ]

cmap has the following signature:

cmap :: (Element b, Container c e) => (e -> b) -> c e -> c b

Which means it's like fmap only constrained to types that can be held by hmatrix containers.

If, instead, you want to crop the decimals, you can use toZ:

λ> toZ $ conv2 ((3><3)[1..]) ((1><1)[1.1 :: R]) :: Matrix Z
(3><3)
 [ 1, 2, 3
 , 4, 5, 6
 , 7, 8, 9 ]

toZ has the following signature:

toZ :: Container c e => c e -> c Z

Which means it will convert anything to a container of Z. It does so by cropping the decimals.

Upvotes: 2

Related Questions