如何在Haskell的Hmatrix中设置切片?

发布于 2025-01-22 07:20:57 字数 1130 浏览 2 评论 0原文

Haskell的hmatrix允许您方便地 get slices:

m ?? (All, Take 3)

但是如何 set slices ,特别是非矩形的?例如,在Python的Numpy中,我会做:

>>> x = np.arange(12).reshape(3, 4)
>>> x
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> x[[0,0], [1,3]] += x[[2,2], [1,3]]     # to ix (0, 1) add (2, 1)  and  to ix (0, 3) add (2, 3)
>>> x
array([[ 0, 10,  2, 14],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

我可以自己编写此辅助功能,但是,这是丑陋的,部分,并且需要我添加zipwith3m _,该_ 应该存在于向量库,但没有:

setSlice :: (Element t, Num t) => Matrix t -> (Extractor, Extractor) -> Vector t -> Matrix t
setSlice parent (Pos (V.map fromIntegral -> irows), Pos (V.map fromIntegral -> icols)) sub = runST $ do
  tparent <- thawMatrix parent
  zipWith3M_ (writeMatrix tparent) irows icols sub
  freezeMatrix tparent

Haskell's HMatrix allows you to conveniently get slices:

m ?? (All, Take 3)

But how can you set slices, especially non-rectangular ones? For instance, in Python's Numpy I'd do:

>>> x = np.arange(12).reshape(3, 4)
>>> x
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> x[[0,0], [1,3]] += x[[2,2], [1,3]]     # to ix (0, 1) add (2, 1)  and  to ix (0, 3) add (2, 3)
>>> x
array([[ 0, 10,  2, 14],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

I'm able to write this helper function myself, but, it's sure ugly, and partial, and required I add zipWith3M_ which should exist in the vector library but doesn't:

setSlice :: (Element t, Num t) => Matrix t -> (Extractor, Extractor) -> Vector t -> Matrix t
setSlice parent (Pos (V.map fromIntegral -> irows), Pos (V.map fromIntegral -> icols)) sub = runST $ do
  tparent <- thawMatrix parent
  zipWith3M_ (writeMatrix tparent) irows icols sub
  freezeMatrix tparent

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文