gpt4 book ai didi

ruby - 如何向二维 Ruby NArray 添加一行?

转载 作者:太空宇宙 更新时间:2023-11-03 17:58:10 24 4
gpt4 key购买 nike

我想向二维 NArray 添加一行。 NArray 0-7 Tutorial中描述的方式非常复杂 - 我想知道是否有更简单的方法。

所以如果我有两个 NArray:

n1 = [[ 0,  1,  2,  3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]]

n2 = [16, 17, 18, 19]

我想添加 n1 和 n2 以获得 n3:

n3 = [[ 0,  1,  2,  3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19]]

如何做到这一点?

最佳答案

require "narray"

class NArray
def concat(other)
shp = self.shape
shp[1] += 1
a = NArray.new(self.typecode,*shp)
a[true,0...-1] = self
a[true,-1] = other
return a
end
end

n1 = NArray[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]]

n2 = NArray[16, 17, 18, 19]

p n1.concat(n2)
# => NArray.int(4,5):
# [ [ 0, 1, 2, 3 ],
# [ 4, 5, 6, 7 ],
# [ 8, 9, 10, 11 ],
# [ 12, 13, 14, 15 ],
# [ 16, 17, 18, 19 ] ]

关于ruby - 如何向二维 Ruby NArray 添加一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9722808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com