Anatoly Yakovenko wrote:
What is the most efficient way to update a position in a matrix or a
vector? I came up with this:
updateVector :: Vector Double -> Int -> Double -> Vector Double
updateVector vec pos val = vec `add` v2
where
v2 = fromList $ (replicate (pos) 0.0) ++ ((val - (vec @>
pos)):(replicate ((dim vec)- pos - 1) 0.0))
but this seems pretty inefficient to me.
thanks,
Anatoly
It is probably more efficient to use subVector and join (implemented by
copyArray):
updateVector' v pos val
| pos == 0 = join [b,c]
| pos == dim v -1 = join [a,b]
| otherwise = join [a,b,c]
where a = subVector 0 pos v
b = fromList [val]
c = subVector (pos+1) (dim v -pos-1) v
> updateVector' (fromList [1,2,3,4,5]) 2 57
5 |> [1.0,2.0,57.0,4.0,5.0]
(The three cases are required because empty vectors are not currently
allowed.)
Something similar can be done for matrices using flatten and reshape.
Although vectors and matrices in this library are immutable and intended
to be manipulated as a whole by higher level functions, this kind of
update functions may often be useful. I will include them soon.
Alberto
_______________________________________________
Haskell-Cafe mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/haskell-cafe