Skip to main content

Read matlab file in Julia

· 2 min read

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

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.

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.

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

# 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

using MAT, DataFrame
file = matopen("path/to/file.mat")

# construct variable
df = DataFrame(read(file,"variable1"),Vector{String}(vec(read(file,"name1"))))
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