Read matlab file in Julia

Convert Matlab file to Julia

In this situation, you should use MAT.jl package to introduce Matlab variables into the Julia system.

MATLAB Table and dataset are not supported in the MAT.jl, you should transfer it to Cell or Array.

Preparation

Transfer table or dataset to cell, but it will cost extremely large storage and time. I think a double array is a better choice, and you can save the column names as a cell for convenience.

1
2
variable1 = table2array(x);
name1 = table2cell(x);

Import the variable

In Julia, I use MAT.jl to read .mat files and DataFrames.jl to create dataframe tables.

1
2
3
4
5
6
7
using MAT
using DataFrames
file = matopen("path/to/file.mat") # this is the path to the .mat file

# import variables you want.
arr = read(file, "variable1") # import variable1 as matrix array.
name = Vector{String}(vec(read(file,"name1"))) # import the name or the key of the first variable. The original name cell is row vector in Matlab. You should reshape it to column vector in Julia.

Construct dataframe

1
2
# construct the dataframe in julia like matlab table 
df = DataFrame(arr, name)

One-line import

Or you can construct the data frame with one line code

1
2
3
4
5
using MAT, DataFrame
file = matopen("path/to/file.mat")

# construct variable
df = DataFrame(read(file,"variable1"),Vector{String}(vec(read(file,"name1"))))

Most of the variables are imported as Float64, you can change the type manually if you need.

1
2
3
4
5
6
7
8
9
df.v1 = convert.(Int,df.v1)# if you know the key of the specific column.

# you can create a for loop to change multi columns together

var = [:v1, :v2, :v3, :v4]
var_type = [Int, Int, String, Char]
for i in length(var)
df[:,var[i]] = convert.(var_type[i], df[:,var[i]])# you can use ! to replace :
end

Read matlab file in Julia
https://www.pengjiaxin.com/2023/02/03/matfiletojulia/
Author
Peng Jiaxin
Posted on
February 3, 2023
Licensed under