I have been given a Matlab file that is supposed to contain some matrices. I'm opening it on Matlab online and it looks like an excel sheet where each cell has a variable of class double
and is mentioned as sparse double
. If I try to print this, it gives me a list of coordinates followed by 1. For example:
(100,1) 1
(123,132) 1
The matrix I am working with can only have 0,1 as elements so I assume all other coordinates are zero. However, I have no idea how to display this as a matrix or somehow import this as an array into Julia. I have no knowledge of Matlab, and I don't even want to work on Matlab since the rest of my program is in Julia anyway.
EDIT: As suggested by a comment I am just leaving the code I'm using in order to try to import it. In the Matlab program I have a single variable in "cell" format which is of size 1x10 called modmat
. Each of these contains 1 266x266 sparse double
matrix, which I am accessing as modmat{1}
, modmat{2}
etc.
Matlab:
writematrix(modmat{1},"Mat1.txt")
In Julia:
> using DelimitedFiles
> M1 = open(readdlm,"Mat1.txt")
The output is a 266×1 Matrix{Any}:
variable
I would recommend the MAT.jl package to read in mat
files safely and efficiently. It looks like it can read in sparse matrices too, and even read the whole cell array in one go.
For completeness' sake (and in case you're not able to do the above for some reason), here's how you can read a file containing lines of the format
(100,1) 1
(123,132) 1
:
function readsparsemat(io::IO)
linere = r"^\((\d+),(\d+)\) # coordinates
\s+ # some number of spaces
1$ # 1 at the end of the line
"x # extended regex complete
matches = match.(linere, readlines(io))
coords = [parse.(Int, (m[1], m[2])) for m in matches]
sparse(first.(coords), last.(coords), true)
end
julia> readsparsemat(IOBuffer("(10,1) 1
(12,13) 1
")) # test with an IOBuffer
12×13 SparseMatrixCSC{Bool, Int64} with 2 stored entries:
...
julia> open(readsparsemat, "matfilename") #actual usage
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With