将 Matlab 中的矩阵导入 Julia

Importing a matrix in Matlab to Julia

我得到了一个应该包含一些矩阵的 Matlab 文件。我在 Matlab 在线打开它,它看起来像一个 excel sheet,其中每个单元格都有一个变量 class double,并被称为 sparse double。如果我尝试打印它,它会给我一个坐标列表,后跟 1。例如:

(100,1)   1
(123,132) 1

我正在使用的矩阵只能有 0,1 作为元素,所以我假设所有其他坐标都为零。但是,我不知道如何将其显示为矩阵或以某种方式将其作为数组导入 Julia。我对 Matlab 一无所知,我什至不想在 Matlab 上工作,因为我的程序的其余部分无论如何都在 Julia 中。

编辑:正如评论所建议的那样,我只是留下我正在使用的代码以便尝试导入它。在 Matlab 程序中,我有一个“单元格”格式的单个变量,其大小为 1x10,称为 modmat。其中每一个都包含 1 个 266x266 sparse double 矩阵,我以 modmat{1}modmat{2} 等方式访问它

Matlab:

writematrix(modmat{1},"Mat1.txt")

朱莉娅:

> using DelimitedFiles
> M1 = open(readdlm,"Mat1.txt")

输出是一个266×1 Matrix{Any}:变量

我会推荐 MAT.jl 包来安全有效地读入 mat 文件。看起来它也可以读取稀疏矩阵,甚至可以一次性读取整个元胞数组。

为了完整起见(如果您出于某种原因无法执行上述操作),这里是您如何读取包含格式行的文件的方法

(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