1

In Julia, I would like to write a function that prompts the user multiple times for matrix input, and then stores their inputs into an array. I have tried the following so far:

function acceptlist()
    matrix_array=[]
    while true:
        matrix_input=read() #don't know what function to use?
        if matrix_input="quit"
            break
        end
        push!(matrix_array, matrix_input)
    end
end

However, I am not sure how to accept matrix inputs in the way I desire. Is there any way for me to accept matrix inputs from the user? Also, I would like to user to NOT have to manually enter the matrices into the function (using readdlm or something similar). For example, I want the user to be able to read in the matrix from another file, assign it to some variable, and then enter that variable into this function acceptlist() as user input.

James Rider
  • 633
  • 1
  • 9
  • Does this answer your question? [Reading data matrix from text file in Julia](https://stackoverflow.com/questions/35309635/reading-data-matrix-from-text-file-in-julia) or even https://stackoverflow.com/q/24295276/11747148. – Shayan Jan 13 '23 at 04:10

2 Answers2

0

This code might provide an example of what you need (sorry, but a bit tired for a full answer):

m = Matrix{Int}(undef,0,0)
while true
    s = readline()
    if length(s)<1
           break
    end
    r = hcat(parse.(Int, split(s))...)
    m = size(m,1)>0 ? vcat(m,r) : r
end

After running, m should have an Int matrix. Same logic would apply to Float64, and many more validations can be added depending on the level and context of the code.

For example, a run could look like:

1 2 3
2 3 4
4 5 6


julia> m
3×3 Matrix{Int64}:
 1  2  3
 2  3  4
 4  5  6
Dan Getz
  • 17,002
  • 2
  • 23
  • 41
0

If you are on Linux or Mac you can just be using DelimitedFiles and run readdlm(stdin). The user will need to press Ctrl+D once she or he is done.

See this sample Julia session on Ubuntu:

julia> readdlm(stdin;comments=true)
1 2 3
4 5 6 # I now press Ctrl+D
2×3 Matrix{Float64}:
 1.0  2.0  3.0
 4.0  5.0  6.0

This will however not work on Windows as creators of some operating systems never found out how to make a working text terminal ;-)

Przemyslaw Szufel
  • 40,002
  • 3
  • 32
  • 62