# [Haskell-cafe] HMatrix Vector/Matrix interpolation ala Matlab interp/interp2 ??

Tue Jan 25 22:26:31 CET 2011

```On Tuesday 25 January 2011 22:05:34, gutti wrote:
> Hi,
>
> I created some code from scratch - probably "ugly" beginners style - so
> I'm keen to get
> tips how to make it more pretty and faster
>
> Cheers Phil
>
> import Data.List
>
> -- Input Data
> xi :: [Double]
> xi = [0 .. 10]
> yi :: [Double]
> yi = [2, 3, 5, 6, 7, 8, 9, 10 , 9, 8, 7]
> x = 11 :: Double
>
> -- Functions
> limIndex xi idx
>     | idx < 0 = 0
>     | idx > (length xi)-2 = (length xi)-2
>     | otherwise = idx

limIndex xi idx = max 0 (min idx (length xi - 2))

not necessarily better, but different

>
> getIndex xi x = limIndex xi (maybe (length xi) id (findIndex (>x) xi)-1)

maybe val id

is the same as

fromMaybe val

>
> getPnts xi yi idx = [xi !! idx, xi !! (idx+1), yi !! idx, yi !! (idx+1)]

getPnts xi yi idx =
case drop idx \$ zip xi yi of
((x1,y1):(x2,y2):_) -> [x1,x2,y1,y2]
_ -> error "Not enough points"

>
> interp xi yi x =
> 	let pts = getPnts xi yi (getIndex xi x)
> 	in (pts!!3-pts!!2)/(pts!!1-pts!!0)*(x-pts!!0)+pts!!2

let (x1:x2:y1:y2:_) = getPnts xi yi (getIndex xi x)
in (y2 - y1)/(x2 - x1)*(x-x1) + y1

>
> -- Calc
> y = interp xi yi x
>
> main = do
> 	-- Output Data
>     	print (y)

```