# work0202.rb # @m = a.dup は、多次元配列の dup が不完全であるという Ruby の悪癖!? # ... Ruby version 1.7 からは生じないようです。 class Matrix def initialize(a=[[1,0,0],[0,1,0],[0,0,1]]) @m = [] @size = 3 for i in 0...@size do @m << a[i].dup end end attr_accessor :m def add(x) ans = Matrix.new for i in 0...@size for j in 0...@size ans.m[i][j] = @m[i][j] + x.m[i][j] # ミス end end return ans end def mult(x) ans = Matrix.new for i in 0...@size for j in 0...@size sum = 0 for k in 0...@size sum += @m[i][k] * x.m[k][j] end ans.m[i][j] = sum # ミス end end return ans end def invers ae = [[0,0,0,1,0,0],[0,0,0,0,1,0],[0,0,0,0,0,1]] for i in 0...@size for j in 0...@size ae[i][j] = @m[i][j] end end for i in 0...@size j = i while ae[j][i] == 0 j += 1 if j >= @size return nil end end if j != i for k in 0...@size*2 tmp = ae[i][k] ae[i][k] = ae[j][k] ae[j][k] = tmp end end p = Float(ae[i][i]) # ミス for k in i...@size*2 ae[i][k] /= p end for j in 0...@size if i != j r = ae[j][i] for k in i...@size*2 ae[j][k] -= ae[i][k]*r end end end end ans = Matrix.new for i in 0...@size for j in 0...@size ans.m[i][j] = ae[i][j+@size] end end return ans end def show for i in 0...@size for j in 0...@size printf(" %5.2f",@m[i][j]) # ミス end print "\n" end end end # a = [[1,1,1],[2,2,2],[3,3,3]] x = Matrix.new(a) x.show a[1][1] = 0 x.show