On Fri, 17 May 2019, Riccardo (Jack) Lucchetti wrote:
I was fooling around with Octave and I realised we don't have (yet) an easy
way to perform a task like they do in
<matlab>
a = load("x.csv")
</matlab>
which would read a csv file into a matrix; we do have mread(), but back in
the day when we designed this function our inspiration was the .mat format
used in Ox, in which the first line must hold the matrix dimensions.
Of course we could achieve the desired effect by primitive functions such as
readfile() etc, but it'd be long and tiresome. What do you think? Is this
worthwhile having? And if so, should we extend the mread() syntax or have a
new function?
Answering myself: I put together a smal hansl function for doing just
that: it should work on reasonably regular csv files. It's reported below
(together with a small example): what do you guys think about adding it
to the extra package?
<hansl>
set verbose off
function string normalize_delimiters(string l)
ret = l
ret = regsub(ret, "[ ]*,[ ]*", "\t")
ret = regsub(ret, "[ ]*;[ ]*", "\t")
ret = regsub(ret, "[ ]+", "\t")
return ret
end function
function matrix csv2mat(string filename)
string s = readfile(filename)
strings lines = strsplit(s, "\n")
scalar r = nelem(lines)
### find number of columns
l = normalize_delimiters(lines[1])
scalar c = strlen(regsub(l, "[^\t]", "")) + 1
matrix ret = zeros(r,c)
i = 1
loop i = 1 ..r --quiet
l = normalize_delimiters(lines[i])
ll = strsplit(l, "\t")
loop j = 1 .. c --quiet
ret[i,j] = atof(ll[j])
endloop
endloop
return ret
end function
r = 20
c = 4
delim = " , "
test = floor(mnormal(r,c))
testfilename = "x.csv"
outfile @testfilename --quiet
loop i = 1 .. r --quiet
loop j = 1 .. c-1 --quiet
printf "%g%s", test[i, j], delim
endloop
printf "%g\n", test[i, c]
endloop
end outfile
chk = readfile(testfilename)
print s
X = csv2mat(testfilename)
print test X
eval test-X
<hansl>
-------------------------------------------------------
Riccardo (Jack) Lucchetti
Dipartimento di Scienze Economiche e Sociali (DiSES)
Università Politecnica delle Marche
(formerly known as Università di Ancona)
r.lucchetti(a)univpm.it
http://www2.econ.univpm.it/servizi/hpp/lucchetti
-------------------------------------------------------