Matrix as user input in Julia?

Viewed 53

In Julia, the function readline() can accept user input, but such user inputs are always cast to the string type by the readline() function. Is there any way to accept user input of multidimensional arrays/matrices, such that they won't automatically be cast as strings?

1 Answers

For reading in matrices, you can use the readdlm function from the DelimitedFiles standard library. It accepts values separated by a delimiter (default: whitespace) for each row, and the rows themselves are separated by an end-of-line character (default: \n).

julia> using DelimitedFiles

julia> readdlm(stdin)
1 2 3
4 5 6
2×3 Matrix{Float64}:
 1.0  2.0  3.0
 4.0  5.0  6.0

readdlm(stdin) accepts user input until the EOF (End-Of-File) character is pressed (Ctrl-D on Linux, I believe Ctrl-Z on Windows). You can also pass in the expected element type of the input, and a Matrix of that type will be returned (or an error raised, if the input wasn't of that type).

julia> readdlm(stdin, Int)
1 3 5
7 9 11
2×3 Matrix{Int64}:
 1  3   5
 7  9  11

julia> readdlm(stdin, Int)
1 3.14 5
7 9 11
ERROR: at row 1, column 2 : ErrorException("file entry \"3.14\" cannot be converted to Int64")
Related