2010-02-11 47 views
4

我一直在NetLogo中運行遊戲理論模擬,現在我有很多數據文件,包含交叉製表數據 - 每列存儲一個不同變量的值,有c。包含數據的1000行。我正在嘗試編寫一個程序來獲取這些文件並計算每列的平均值。NetLogo:從可變行數的輸入文件讀取數據

我有一個程序,只要在每個文件中有恆定數量的數據行就能工作。該程序使用文件讀取命令循環來計算運行總數,然後在讀取所有行之後讀取行的nuber進行讀取。

但是,我的真實數據文件具有可變數量的行。我一直在嘗試使用文件結尾來修改我的代碼?讓它在最後一行之後退出正在運行的總循環,但是我一直沒有找到任何可以使用它的方法 - 我只是得到一個錯誤,說文件已經結束了。

請問有人可以提出一種處理方法嗎?我粘貼了下面的工作代碼。

-

globals [target-file-name 
current-tally-file 
lines-read 
coops-fixed-run cheats-fixed-run either-fixed-run coop-freq-min-run 
coop-freq-max-run coop-freq-mean-run ticks-run 
num-lines 
] 

to setup 
set target-file-name user-input "Type a name for the target file" 
file-open target-file-name 
file-print("TallyFile Reps pFixCoop pFixCheat pFixEither MeanMinCoop MeanMaxCoop MeanMeanCoop") 
file-close 
set num-lines read-from-string user-input "How many lines in the file to be processed?" 
end 

to go 
set current-tally-file user-file 
file-open current-tally-file 
set lines-read 0 

while [lines-read < num-lines][ 
let in1 file-read set coops-fixed-run (coops-fixed-run + in1) 
let in2 file-read set cheats-fixed-run (cheats-fixed-run + in2) 
let in3 file-read set either-fixed-run (either-fixed-run + in3) 
let in4 file-read set coop-freq-min-run (coop-freq-min-run + in4) 
let in5 file-read set coop-freq-max-run (coop-freq-max-run + in5) 
let in6 file-read set coop-freq-mean-run (coop-freq-mean-run + in6) 
let in7 file-read set ticks-run (ticks-run + in7)  
set lines-read (lines-read + 1) 
] 

stop-and-clear 
end 


to stop-and-clear 

let pfixcoop (coops-fixed-run/lines-read) 
let pfixcheat (cheats-fixed-run/lines-read) 
let pfixeither (either-fixed-run/lines-read) 
let mean-of-mins (coop-freq-min-run/lines-read) 
let mean-of-maxs (coop-freq-max-run/lines-read) 
let mean-of-means (coop-freq-mean-run/lines-read) 
let mean-of-ticks (ticks-run/lines-read) 

file-open target-file-name 
file-print (word current-tally-file " " lines-read " " pfixcoop " " pfixcheat " 
" pfixeither " " mean-of-mins " " mean-of-maxs " " mean-of-means " " 
mean-of-ticks) 
file-close 


set coops-fixed-run 0 
set cheats-fixed-run 0 
set either-fixed-run 0 
set coop-freq-min-run 0 
set coop-freq-max-run 0 
set coop-freq-mean-run 0 
set ticks-run 0 
set lines-read 0 

stop 

end 

回答

4

讀取所有行從文件看起來像一個方法:

to read-file [filename] 
    file-open filename 
    while [not file-at-end?][ 
    ;read one line 
    let in1 file-read 
    let in2 file-read 
    ;and so one, at the end you will probably want to put these into some global variable 
    set global-in1 fput in1 global-in1 
    ] 
    file-close filename 
end 

這是假設所有的行具有完全相同的數據項的名稱數量,你知道是什麼那個數字是。否則就用文件讀取線代替文件讀取

+1

非常感謝!我沒有意識到我可以使用不是文件 - 最後。我確實每行都有一定數量的數據項,所以這看起來很完美。 – 2010-02-11 13:07:00