gpt4 book ai didi

ruby - 替换 Matrix 对象的内部状态

转载 作者:数据小太阳 更新时间:2023-10-29 08:46:57 25 4
gpt4 key购买 nike

类似于Array#pop(),我想创建一个删除矩阵最后一列的破坏性方法:Matrix#hpop()(h代表水平)。

我怎样才能使这个方法具有破坏性?没有像 Matrix#replace() 这样的方法可以用来修改对象的内部状态。

  # Removes trailing columns from a Matrix.
# @param number_of_columns [Integer] number of trailing columns to be removed
# @return [Matrix] matrix
# @raise [ErrDimensionMismatch] if Matrix does not have enough columns for operation
def hpop(number_of_columns = 1)
Matrix.Raise ErrDimensionMismatch unless number_of_columns < self.column_count

columns = []
last_column_to_be_included = self.column_count - number_of_columns
self.column_vectors.each_with_index do |column, index|
break if index + 1 > last_column_to_be_included
columns << column.to_a
end

Matrix.columns(columns) # should be destructive
end

最佳答案

您可以修补 Matrix 类以删除列...

class Matrix
def drop_column
@rows.each {|r| r.pop}
end
end


my_matrix = Matrix.build(3,5) { 1 }
=> Matrix[[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]

my_matrix.drop_column

p my_matrix
=> Matrix[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]

或类似地删除一行

class Matrix
def drop_row
@rows.pop
end
end

编辑

所以实际上 hpop 会是...

def hpop(number_of_columns = 1)        
Matrix.Raise ErrDimensionMismatch unless number_of_columns < column_count

dropped_columns = []
number_of_columns.times do
dropped_column = []
@rows.each {|r| dropped_column << r.pop}
dropped_columns << dropped_column
end

@column_count -= number_of_columns

Matrix.columns(dropped_columns.reverse)
end

(代码取自您自己的源代码,只是添加了 @column_count -= ... 行)

编辑 #2

vpop 方法可能是...

class Matrix
def vpop(number_of_rows = 1)
Matrix.Raise ErrDimensionMismatch unless number_of_rows < @rows.size
dropped_rows = []
number_of_rows.times { dropped_rows.unshift @rows.pop }
Matrix.columns(dropped_rows)
end
end

关于ruby - 替换 Matrix 对象的内部状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25062392/

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