[Haskell-cafe] Re: hmatrix
Anatoly Yakovenko
aeyakovenko at gmail.com
Sun Jun 1 14:45:09 EDT 2008
do you have any plans to provide an interface for inplace updates?
On Sun, Jun 1, 2008 at 3:20 AM, Alberto Ruiz <aruiz at um.es> wrote:
> 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
>
More information about the Haskell-Cafe
mailing list