2010-02-11 53 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