# [Haskell-cafe] Matlab Style Logic Operations ala V1.*(V2>0) on Vectors and Matrices with HMatrix ??

Henning Thielemann lemming at henning-thielemann.de
Tue Dec 21 23:15:32 CET 2010

```> thanks for the quick and comprehensive help. - I managed to implement
> Hennings suggestion with mapVector and zipWithVector.  -- However have a
> type inference problem with zipVectorWith -- probably a stupid beginners
> mistake. (have a look below). I want to look into the matrix thing as well,
> but that might take a bit.

It is
Matrix.zipWith f x y = liftMatrix2 (zipVectorWith f) x y

> I see the point, that its probably not the "cleanest" way (bool to 0 & 1)
> but its damn convinient (laziness at its best).

Is it really? Certainly, if you are used to. I am scared if someone
multiplies the result of a comparison with something else. I find the 'if'
most natural for such applications, and I like the Matrix.zipWith because
it expresses that corresponding elements of matrices are combined and that
it is no operation that is special for matrices (such as matrix
multiplication or inversion or factorization or determinant).

> Maybe there could be a haskell way to implement the "lazy" matlab matrix and
> vector operation syntax (like explicit function for bool 2 num)

You are free to implement any function, also higher order, also with infix
syntax, that you need frequently. :-)

> ######## Code
>
> import Numeric.LinearAlgebra
> import Graphics.Plot
>
> time = 101 |> [0, 0.1 .. 100 :: Double];
>
> vector1 = sin(time);
> vector2 = vector1*0.9;

I had to look twice, whether this is C or Haskell. It could be both of
them. :-) I would certainly write:

vector1, vector2 :: Vector Double
vector1 = sin time
vector2 = vector1*0.9

> posPart:: Vector Double -> Vector Double
> posPart v  =  mapVector (\a -> if a>=0 then a else 0) v

posPart = mapVector (max 0)

> v3:: Vector Double -> Vector Double -> Vector Double
> v3 v1 v2 = zipVectorWith(\a1 a2 -> if a1>=0 then a2/a1 else a1/a2) v1 v2
>
> main = do
>
>
>  -- print(v3)
> mplot [v3]

v3 is a function and 'mplot' seems to expect a vector.

> mplot [posPart vector1]

```