Converting MATLAB ".mat" matrices to julia matrices

Hello everyone,

I am new to Julia. I have been using MATLAB for quite a while. I have few matlab matices namely, A.mat, B.mat, C.mat and so on. I have to read these matrices into Julia and then do some optimization using them. I dont know how to convert these matlab matrices to Julia matrices. I have used the pkg MAT.jl. when I use use it as: A = matopen(“A.mat”) in julia then “A” is not a matrix in julia. How do I read convert these matrices to julia matrices. Any help will be appriciated. Thanks

Have you tried matread? I.e.,

vars = matread("A.mat")

Thanks. Just tried it. vars becomes a dictionary, not a matrix. I wanted A.mat to be a matrix also in Julia

Hi Muhammad, welcome to Julia community. You write:

But note that such usage does not follow the instructions given on the MAT.jl page:

To read a single variable from a MAT file (compressed files are detected and handled automatically):

file = matopen("matfile.mat")
read(file, "varname") # note that this does NOT introduce a variable ``varname`` into scope
1 Like

In Matlab:

>> A = [1 2; 3 4]

A =

     1     2
     3     4

>> save file_with_A

In Julia:

julia> using MAT

julia> file = matopen("file_with_A.mat")
MAT.MAT_v5.Matlabv5File(IOStream(<file file_with_A.mat>), false, #undef)

julia> read(file,"A")
2×2 Matrix{Float64}:
 1.0  2.0
 3.0  4.0

julia> close(file)

1 Like

Note that A.mat is a file in “MAT” format, and not a matrix. In MATLAB, if you do

>> vars = load("A.mat")

you get a MATLAB struct containing the variables you saved. If the A.mat file contains a matrix A, then you can access it in MATLAB with

>> A = vars.A % or directly with A = load("A.mat").A

In Julia, you would do

julia> A = vars["A"] # or directly A = matread("A.mat")["A"]

That’s because MATLAB’s structs are essentially the same as Julia dictionaries, albeit with the syntactic difference to grab objects inside (i.e., vars.A in MATLAB vs vars["A"] in Julia).


Linking to Converting MATLAB ".mat" matrices to Julia Matrices - Stack Overflow

1 Like

Thank you so much