How to Store Data like .mat in Julia
Overview
JLD.jl
is a package that allows the storage of temporary data created while using Julia1. It is useful for managing the input and output of data in pure Julia projects. On the other hand, JLD2.jl
, which further improves the intuitiveness of the JLD.jl
interface, is also available. 2 The content introduced in this post should be taken as a rough understanding of these functionalities, and it is recommended to use JLD2.jl
whenever possible as it supports backward compatibility without issues.
If you specifically need to read and write MATLAB’s mat files, not just files similar to mat files, then the MAT.jl
package can be referred to.
Code
using JLD
cd(@__DIR__); pwd()
numpad = reshape(1:9, 3,3)
cube = zeros(Int64, 3,3,3)
save("mydata.jld", "numpad",numpad, "cube",cube)
mydata = load("mydata.jld")
mydata["numpad"]
mydata["cube"]
Execution Result
julia> numpad = reshape(1:9, 3,3)
3×3 reshape(::UnitRange{Int64}, 3, 3) with eltype Int64:
1 4 7
2 5 8
3 6 9
julia> cube = zeros(Int64, 3,3,3)
3×3×3 Array{Int64, 3}:
[:, :, 1] =
0 0 0
0 0 0
0 0 0
[:, :, 2] =
0 0 0
0 0 0
0 0 0
[:, :, 3] =
0 0 0
0 0 0
0 0 0
julia> save("mydata.jld", "numpad",numpad, "cube",cube)
┌ Warning: JLD incorrectly extends FileIO functions (see FileIO documentation)
└ @ FileIO C:\Users\rmsms\.julia\packages\FileIO\5JdlO\src\loadsave.jl:215
The extension of the files saved should be *.jld
. The names of each data to be stored are given as strings and assigned variables are sequentially appended, bundling the data together for storage.
julia> mydata = load("mydata.jld")
┌ Warning: JLD incorrectly extends FileIO functions (see FileIO documentation)
└ @ FileIO C:\Users\rmsms\.julia\packages\FileIO\5JdlO\src\loadsave.jl:215
Dict{String, Any} with 7 entries:
"_creator\\JULIA_PATCH" => 0x00000001
"cube" => [0 0 0; 0 0 0; 0 0 0]…
"_creator\\WORD_SIZE" => 64
"numpad" => [1 4 7; 2 5 8; 3 6 9]
"_creator\\JULIA_MINOR" => 0x00000006
"_creator\\ENDIAN_BOM" => 0x04030201
"_creator\\JULIA_MAJOR" => 0x00000001
As you can see, a dictionary is returned upon loading. The names given as strings during the saving process enter as keys, and the actual data is in the values. It can be referenced as a dictionary as follows.
julia> mydata["numpad"]
3×3 reshape(::UnitRange{Int64}, 3, 3) with eltype Int64:
1 4 7
2 5 8
3 6 9
julia> mydata["cube"]
3×3×3 Array{Int64, 3}:
[:, :, 1] =
0 0 0
0 0 0
0 0 0
[:, :, 2] =
0 0 0
0 0 0
0 0 0
[:, :, 3] =
0 0 0
0 0 0
0 0 0
JLD2
In the example, the process of creating a dictionary with strings was cumbersome, but with JLD2.jl
, the same functionality can be conveniently used with named tuples.