将行(数组)添加到空矩阵

时间:2013-04-15 08:57:56

标签: ruby arrays matrix row add

我想在一个空矩阵中添加一行(数组)。

就像将数组添加到空数组一样:

a = []
a << [1,2,3]

=> [[1,2,3]]

所以我尝试了以下内容:

require 'Matrix'
m = Matrix[]
m.to_a << [1,2,3]

# => Matrix.empty(0, 0)

然后是以下内容:

m = Matrix[]
Matrix.rows(m.to_a << [1,2,3])

# => Matrix.empty(0, 0)

但它不起作用!它应该创建以下矩阵:

# => Matrix[[1,2,3]]

# and then with each add:
# => Matrix[[1,2,3], [2,3,4], ...]

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

require 'Matrix'
m = Matrix[]
p m.object_id #=> 6927492
p m.to_a.class #=> Array
p m.class #=> Matrix
p m.to_a.object_id #=> 6927384
p m.to_a << [1,2,3] #[[1, 2, 3]]
p m #=> Matrix.empty(0, 0)

见上文object_id不同。 m.to_a不转换矩阵m本身,而是给出给定矩阵的新数组表示。

现在在下面,Matrix.rows(m.to_a << [1,2,3])创建了一个新矩阵,而不是向m矩阵本身添加任何行。因此p m显示了预期的结果。

p Matrix.rows(m.to_a << [1,2,3]).class #=> Matrix
p Matrix.rows(m.to_a << [1,2,3]).object_id #=> 6926640
p Matrix.rows(m.to_a << [1,2,3]) #=>Matrix[[1, 2, 3]]
p m #=> Matrix.empty(0, 0)

现在要做到这一点,请执行以下操作:

m = Matrix.rows(m.to_a << [1,2,3]) #=>Matrix[[1, 2, 3]]
p m #=>Matrix[[1, 2, 3]]

答案 1 :(得分:0)

怎么样

m = [[1,2,3], [2,3,4]]
matrix = Matrix.rows(m)

m << [4,5,6]
matrix = Matrix.rows(m)

答案 2 :(得分:0)

它适用于Ruby 1.9.3p392

1.9.3p392 :001 > require 'matrix'
 => true 
1.9.3p392 :002 > m = Matrix[]
 => Matrix.empty(0, 0) 
1.9.3p392 :003 > m = Matrix.rows(m.to_a << [1,2,3])
 => Matrix[[1, 2, 3]] 
1.9.3p392 :004 > m = Matrix.rows(m.to_a << [2,3,4])
 => Matrix[[1, 2, 3], [2, 3, 4]]

2.0.0p0也很好

2.0.0p0 :001 > require 'matrix'
 => true 
2.0.0p0 :002 > m = Matrix[]
 => Matrix.empty(0, 0) 
2.0.0p0 :003 > m = Matrix.rows(m.to_a << [1,2,3])
 => Matrix[[1, 2, 3]] 
2.0.0p0 :004 > m = Matrix.rows(m.to_a << [2,3,4])
 => Matrix[[1, 2, 3], [2, 3, 4]]