#/*********************************************************** # statutil.rb -- 多変量データ #***********************************************************/ require "matutil.rb" # 行列用の小道具集 INT_MAX = 2147483647 READERROR = -1.00E+37 # 読込エラー MISSING = -0.98E+37 # 欠測値 def readerror(x); (x < -0.99E+37) ? true : false; end def missing(x); (x < -0.97E+37) ? true : false; end $line = [] def scanf(datafile) if $line == [] inpt = datafile.gets return nil if inpt == nil $line = inpt.split end $line.shift end def getnum(datafile) data = scanf(datafile) if data == nil return READERROR elsif data.size > 81 return READERROR elsif data == "." return MISSING elsif data =~ /^\D+$/ return READERROR elsif data.to_f.abs > 0.97E+37 return READERROR else return data.to_f end end def open_data(filename) begin datafile = open(filename, "r") rescue $stderr.printf("データファイルが開きません.\n") exit 1 end n = getnum(datafile) m = getnum(datafile) n = n.to_i; m = m.to_i if (n <= 0 || n > INT_MAX || m <= 0 || m > INT_MAX) $stderr.printf("行数・列数が読めません.\n") datafile.close; return nil end $stderr.printf("%d 行 %d 列のデータです.\n", n, m) return datafile, n, m end def read_data(datafile, m, n, x) missings = 0 for i in 0...n for j in 0...m t = getnum(datafile) if readerror(t) x[j][i] = READERROR $stderr.printf("読込みエラー(%d,%d)\n", i+1, j+1) elsif missing(t) missings += 1; x[j][i] = MISSING else x[j][i] = t end end end $stderr.printf("読込み終了 (欠測値 %d 個)\n", missings) end # 以下は使用例 =begin # matrix x; \tt matrixend 型は \tt matutil.cend で定義 printf("データファイル名? ") filename = gets.chomp datafile, n, m = open_data(filename) # データファイルを開く if (datafile == nil); exit 1; end # 失敗 x = new_matrix(n, m); # 行列を生成 read_data(datafile, n, m, x); # データを読む datafile.close for i in 0...n for j in 0...m if (readerror(x[j][i])); printf(" E") # 読込失敗 elsif (missing(x[j][i])); printf(" .") # 欠測値 else; printf(" %g", x[j][i]) # 正常 end end printf("\n") end exit 0 =end