NETLOGO:读取从matlab导出的csv文件并将其存储为列表列表

NETLOGO: Reading a csv file exported from matlab and store it as a list of lists

我正在尝试读取从 matlab 导出的 csv 文件,其中包含 35040 行和 5 列(此文件的每个元素都是一个数字)。之后我想将此类文件存储为 Netlogo 中的列表列表。 我尝试这样做的方式是:

globals[mylist]

set mylist (csv:from-file "output.csv" )
show mylist

此代码实际读取 csv 文件并将其保存为此类列表的列表:

[[a1 a2 a3 a4 a5] [b1 b2 b3 b4 b5]]

问题是每个嵌套列表的最后一个元素在末尾存储了一系列分号。例如,在第一个嵌套列表中,最后一个元素应该是 0.7980,但它存储为“0.7980;;;;;;;;;;;”所以作为一个字符串。 我该如何解决?这是与我正在阅读的 csv 文件相关的问题还是与我正在使用的代码有关的问题?我该怎么办?

是的,问题出在您的 CSV 文件上,根据它的来源,最好的解决方案可能是从源头上修复它。

也就是说,您也可以在 NetLogo 中以去掉分号的方式处理它。这是您如何执行此操作的示例:

to demo
  let list-of-lists [[1 2 3 4 "5;;;;"] [6 7 8 9 "10;;;;;"]]
  let new-list-of-lists map [ xs -> map parse xs ] list-of-lists
  print word "Old list: " list-of-lists
  print word "New list: " new-list-of-lists
end

to-report parse [ value ]  
  report ifelse-value (is-string? value and (position ";" value != false)) [
    ; if the value is a string containing a ";", take the string
    ; up to the position of the ";" and try to convert it to a number
    read-from-string substring value 0 position ";" value
  ] [
    ; otherwise, leave the value alone
    value
  ]
end

这不是世界上最强大的代码,但如果您的文件遵循常规格式,它就可以工作。如果没有,您可以随时根据您的具体情况对其进行调整。

除了map, the key primitives used here are position and read-from-string。如果你查字典,你应该能弄清楚它是如何工作的...