I have a .txt file containing information for 10 matrices of different dimensions.
Each row of the .txt file corresponds to a row of a matrix, with whitespace distinguishing the elements. The matrices are seperated by a single blank line.
An example of what a 2x2 matrix and 3x3 matrix would look like within this .txt file is:
1 0
0 1
1 0 0
0 1 0
0 0 1
Does anyone know of a function that could do this?
Thank you for your answer. I agree that slicing does seem plausible, however the example in my question isn’t representitive of the dimensions of the intended use case. The dimensions of the 10 matrices vary from a 50x50 matrix to a 2147x2147 matrix, hence reading in the matrices via readdlm() returns a 6148x2147 with a lot of whitespace. Do you still think slicing is the way to go forward?
Hi, below is the function that I used to do what I needed. I have two particular things I would be interested in improving in order to make the function more general:
Is storing the matrices in an Array which holds elements of type Any an efficient way to do this?
I got around having to deal with whitespaces by hard coding the number of rows of each individual matrix and the number of matrices within the file.
function parse_whitespace_matrices(matrices)
seperate_matrix_ind = [533;428;517;165;237;95;67;105;2147;2147]
seperate_matrices = [] # array of type `Any`
N = size(matrices) # dimensions of the .txt file which has been read in
running_ind = 1
for i in 1:10
current_matrix = matrices[running_ind:(running_ind+seperate_matrix_ind[i]-1),1:seperate_matrix_ind[i]]
push!(seperate_matrices,current_matrix)
running_ind = running_ind + seperate_matrix_ind[i]
end
return seperate_matrices
end
using DelimitedFiles
matrices = Matrix{Int}[]
open("file.txt", "r") do io
while !eof(io)
str = readuntil(io, "\n\n")
push!(matrices, readdlm(IOBuffer(str)))
end
end