Documentation
ยถ
Overview ยถ
Package matlab provides a library for reading and writing MATLAB .mat files. It supports both v5 (MATLAB v5-v7.2) and v7.3+ (HDF5-based) formats.
Example ยถ
Example demonstrates basic usage of the MATLAB file library.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/scigolib/matlab"
"github.com/scigolib/matlab/types"
)
func main() {
tmpfile := filepath.Join(os.TempDir(), "example.mat")
defer os.Remove(tmpfile)
// Create a simple v5 MATLAB file
writer, _ := matlab.Create(tmpfile, matlab.Version5)
defer writer.Close()
// Write a variable
writer.WriteVariable(&types.Variable{
Name: "data",
Dimensions: []int{3},
DataType: types.Double,
Data: []float64{1.0, 2.0, 3.0},
})
fmt.Println("MATLAB file created successfully")
}
Output: MATLAB file created successfully
Index ยถ
Examples ยถ
Constants ยถ
This section is empty.
Variables ยถ
var ErrInvalidFormat = errors.New("invalid MAT-file format")
ErrInvalidFormat indicates an invalid MAT-file format.
var ErrUnsupportedVersion = errors.New("unsupported MAT-file version")
ErrUnsupportedVersion indicates an unsupported MAT-file version.
Functions ยถ
This section is empty.
Types ยถ
type MatFile ยถ
type MatFile struct {
Version string // MAT-file version (e.g., "5.0", "7.3")
Endian string // Byte order indicator ("MI" or "IM")
Description string // File description from header
Variables []*types.Variable // List of variables in the file
}
MatFile represents a parsed MAT-file.
func Open ยถ
Open reads and parses a MAT-file from an io.Reader.
Example ยถ
ExampleOpen demonstrates reading a MATLAB file.
package main
import (
"fmt"
"os"
"github.com/scigolib/matlab"
)
func main() {
file, _ := os.Open("testdata/generated/simple_double.mat")
defer file.Close()
matFile, _ := matlab.Open(file)
fmt.Printf("Found %d variable(s)\n", len(matFile.Variables))
}
Output: Found 1 variable(s)
Example (MultipleVariables) ยถ
ExampleOpen_multipleVariables demonstrates handling multiple variables.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/scigolib/matlab"
"github.com/scigolib/matlab/types"
)
func main() {
tmpfile := filepath.Join(os.TempDir(), "example_multi.mat")
defer os.Remove(tmpfile)
// Write multiple variables
writer, _ := matlab.Create(tmpfile, matlab.Version5)
writer.WriteVariable(&types.Variable{
Name: "x",
Dimensions: []int{3},
DataType: types.Double,
Data: []float64{1, 2, 3},
})
writer.WriteVariable(&types.Variable{
Name: "y",
Dimensions: []int{3},
DataType: types.Double,
Data: []float64{4, 5, 6},
})
writer.Close()
// Read all variables
file, _ := os.Open(tmpfile)
defer file.Close()
matFile, _ := matlab.Open(file)
fmt.Printf("Total variables: %d\n", len(matFile.Variables))
for _, v := range matFile.Variables {
fmt.Printf("- %s\n", v.Name)
}
}
Output: Total variables: 2 - x - y
Example (RoundTrip) ยถ
ExampleOpen_roundTrip demonstrates writing and reading back data.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/scigolib/matlab"
"github.com/scigolib/matlab/types"
)
func main() {
tmpfile := filepath.Join(os.TempDir(), "example_roundtrip.mat")
defer os.Remove(tmpfile)
// Write
writer, _ := matlab.Create(tmpfile, matlab.Version5)
writer.WriteVariable(&types.Variable{
Name: "test",
Dimensions: []int{2},
DataType: types.Double,
Data: []float64{3.14, 2.71},
})
writer.Close()
// Read
file, _ := os.Open(tmpfile)
defer file.Close()
matFile, _ := matlab.Open(file)
data := matFile.Variables[0].Data.([]float64)
fmt.Printf("Read back: %.2f, %.2f\n", data[0], data[1])
}
Output: Read back: 3.14, 2.71
func (*MatFile) GetVariable ยถ added in v0.3.0
GetVariable retrieves a variable by name. Returns nil if the variable is not found.
Example:
matFile, _ := matlab.Open(file)
data := matFile.GetVariable("mydata")
if data != nil {
fmt.Println("Found:", data.Name)
}
func (*MatFile) GetVariableNames ยถ added in v0.3.0
GetVariableNames returns the names of all variables in the file. Useful for listing available data without accessing values.
Example:
matFile, _ := matlab.Open(file)
names := matFile.GetVariableNames()
fmt.Println("Variables:", names) // ["x", "y", "z"]
func (*MatFile) HasVariable ยถ added in v0.3.0
HasVariable checks if a variable with the given name exists.
Example:
if matFile.HasVariable("results") {
data := matFile.GetVariable("results")
// process data
}
type MatFileWriter ยถ
type MatFileWriter struct {
// contains filtered or unexported fields
}
MatFileWriter represents a MATLAB file opened for writing.
The writer automatically selects the appropriate backend based on the requested version (v5 or v7.3). After creating a writer, use WriteVariable to add variables to the file, then Close to finalize.
func Create ยถ
func Create(filename string, version Version, opts ...Option) (*MatFileWriter, error)
Create creates a new MATLAB file for writing with optional configuration.
The version parameter specifies the format: Version5 or Version73. Optional parameters can be provided using functional options.
Supported options:
- WithEndianness(binary.ByteOrder) - v5 byte order (default: LittleEndian)
- WithDescription(string) - v5 file description (max 116 bytes)
- WithCompression(int) - compression level 0-9 (not yet implemented)
Example (basic):
writer, err := matlab.Create("output.mat", matlab.Version5)
Example (with options):
writer, err := matlab.Create("output.mat", matlab.Version5,
matlab.WithEndianness(binary.BigEndian),
matlab.WithDescription("Simulation results"))
Example (v7.3):
writer, err := matlab.Create("output.mat", matlab.Version73)
Example ยถ
ExampleCreate demonstrates creating a MATLAB file.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/scigolib/matlab"
)
func main() {
tmpfile := filepath.Join(os.TempDir(), "example_create.mat")
defer os.Remove(tmpfile)
writer, err := matlab.Create(tmpfile, matlab.Version5)
if err != nil {
panic(err)
}
defer writer.Close()
fmt.Println("File created")
}
Output: File created
Example (V5) ยถ
ExampleCreate_v5 demonstrates creating a v5 format file.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/scigolib/matlab"
"github.com/scigolib/matlab/types"
)
func main() {
tmpfile := filepath.Join(os.TempDir(), "example_v5.mat")
defer os.Remove(tmpfile)
writer, _ := matlab.Create(tmpfile, matlab.Version5)
defer writer.Close()
writer.WriteVariable(&types.Variable{
Name: "matrix",
Dimensions: []int{2, 3},
DataType: types.Double,
Data: []float64{1, 2, 3, 4, 5, 6},
})
fmt.Println("v5 file created")
}
Output: v5 file created
Example (V73) ยถ
ExampleCreate_v73 demonstrates creating a v7.3 HDF5 format file.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/scigolib/matlab"
"github.com/scigolib/matlab/types"
)
func main() {
tmpfile := filepath.Join(os.TempDir(), "example_v73.mat")
defer os.Remove(tmpfile)
writer, _ := matlab.Create(tmpfile, matlab.Version73)
defer writer.Close()
writer.WriteVariable(&types.Variable{
Name: "data",
Dimensions: []int{100},
DataType: types.Double,
Data: make([]float64, 100),
})
fmt.Println("v7.3 file created")
}
Output: v7.3 file created
Example (WithOptions) ยถ
ExampleCreate_withOptions demonstrates using functional options.
package main
import (
"encoding/binary"
"fmt"
"os"
"path/filepath"
"github.com/scigolib/matlab"
)
func main() {
tmpfile := filepath.Join(os.TempDir(), "options.mat")
defer os.Remove(tmpfile)
writer, _ := matlab.Create(tmpfile, matlab.Version5,
matlab.WithEndianness(binary.BigEndian),
matlab.WithDescription("Simulation results"),
)
defer writer.Close()
fmt.Println("File created with custom options")
}
Output: File created with custom options
func (*MatFileWriter) Close ยถ
func (w *MatFileWriter) Close() error
Close closes the MATLAB file and flushes all data to disk.
After calling Close, the writer cannot be used anymore. Any subsequent calls to WriteVariable or Close will fail.
It is safe to call Close multiple times - subsequent calls will be no-ops.
Returns:
- error: If flushing or closing fails
func (*MatFileWriter) WriteVariable ยถ
func (w *MatFileWriter) WriteVariable(v *types.Variable) error
WriteVariable writes a variable to the MATLAB file.
The variable must have valid Name, Dimensions, DataType, and Data fields. The data is written immediately to the underlying storage.
Parameters:
- v: Variable to write (must not be nil)
Returns:
- error: If writing fails or variable is invalid
Supported types:
- Double, Single (float64, float32)
- Int8, Uint8, Int16, Uint16, Int32, Uint32, Int64, Uint64
- Complex numbers (use types.NumericArray with Real/Imag)
Example:
// Simple array
writer.WriteVariable(&types.Variable{
Name: "A",
Dimensions: []int{2, 3},
DataType: types.Double,
Data: []float64{1, 2, 3, 4, 5, 6},
})
// Complex numbers
writer.WriteVariable(&types.Variable{
Name: "C",
Dimensions: []int{2},
DataType: types.Double,
IsComplex: true,
Data: &types.NumericArray{
Real: []float64{1.0, 3.0},
Imag: []float64{2.0, 4.0},
},
})
Example ยถ
ExampleMatFileWriter_WriteVariable demonstrates writing a simple array.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/scigolib/matlab"
"github.com/scigolib/matlab/types"
)
func main() {
tmpfile := filepath.Join(os.TempDir(), "example_array.mat")
defer os.Remove(tmpfile)
writer, _ := matlab.Create(tmpfile, matlab.Version5)
defer writer.Close()
err := writer.WriteVariable(&types.Variable{
Name: "mydata",
Dimensions: []int{5},
DataType: types.Double,
Data: []float64{1.0, 2.0, 3.0, 4.0, 5.0},
})
if err == nil {
fmt.Println("Variable written")
}
}
Output: Variable written
Example (Complex) ยถ
ExampleMatFileWriter_WriteVariable_complex demonstrates writing complex numbers.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/scigolib/matlab"
"github.com/scigolib/matlab/types"
)
func main() {
tmpfile := filepath.Join(os.TempDir(), "example_complex.mat")
defer os.Remove(tmpfile)
writer, _ := matlab.Create(tmpfile, matlab.Version73)
defer writer.Close()
complexData := &types.NumericArray{
Real: []float64{1.0, 2.0, 3.0},
Imag: []float64{4.0, 5.0, 6.0},
}
writer.WriteVariable(&types.Variable{
Name: "signal",
Dimensions: []int{3},
DataType: types.Double,
Data: complexData,
IsComplex: true,
})
fmt.Println("Complex variable written")
}
Output: Complex variable written
Example (Int32) ยถ
ExampleMatFileWriter_WriteVariable_int32 demonstrates writing integer data.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/scigolib/matlab"
"github.com/scigolib/matlab/types"
)
func main() {
tmpfile := filepath.Join(os.TempDir(), "example_integers.mat")
defer os.Remove(tmpfile)
writer, _ := matlab.Create(tmpfile, matlab.Version5)
defer writer.Close()
writer.WriteVariable(&types.Variable{
Name: "counts",
Dimensions: []int{4},
DataType: types.Int32,
Data: []int32{10, 20, 30, 40},
})
fmt.Println("Integer array written")
}
Output: Integer array written
Example (Matrix) ยถ
ExampleMatFileWriter_WriteVariable_matrix demonstrates writing a 2D matrix.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/scigolib/matlab"
"github.com/scigolib/matlab/types"
)
func main() {
tmpfile := filepath.Join(os.TempDir(), "example_matrix.mat")
defer os.Remove(tmpfile)
writer, _ := matlab.Create(tmpfile, matlab.Version5)
defer writer.Close()
// 3x4 matrix in column-major order (MATLAB standard)
writer.WriteVariable(&types.Variable{
Name: "A",
Dimensions: []int{3, 4},
DataType: types.Double,
Data: []float64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
})
fmt.Println("Matrix written")
}
Output: Matrix written
type Option ยถ added in v0.3.0
type Option func(*config)
Option configures optional parameters for Create.
func WithCompression ยถ added in v0.3.0
WithCompression enables compression with specified level (0-9). 0 = no compression, 9 = maximum compression
Note: Compression is not yet implemented. This option is reserved for future use.
Default: 0 (no compression)
Example:
writer, _ := matlab.Create("file.mat", matlab.Version73,
matlab.WithCompression(6))
func WithDescription ยถ added in v0.3.0
WithDescription sets the file description (v5 only, max 116 bytes). If longer than 116 bytes, it will be truncated.
Default: "MATLAB MAT-file, created by scigolib/matlab vX.X.X"
Example:
writer, _ := matlab.Create("file.mat", matlab.Version5,
matlab.WithDescription("Simulation results"))
Example ยถ
ExampleWithDescription demonstrates custom file description.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/scigolib/matlab"
)
func main() {
tmpfile := filepath.Join(os.TempDir(), "described.mat")
defer os.Remove(tmpfile)
writer, _ := matlab.Create(tmpfile, matlab.Version5,
matlab.WithDescription("My experimental data from 2025"),
)
defer writer.Close()
fmt.Println("File with custom description created")
}
Output: File with custom description created
func WithEndianness ยถ added in v0.3.0
WithEndianness sets the byte order for v5 files. Valid values: binary.LittleEndian, binary.BigEndian
Default: binary.LittleEndian
Example:
writer, _ := matlab.Create("file.mat", matlab.Version5,
matlab.WithEndianness(binary.BigEndian))
Example ยถ
ExampleWithEndianness demonstrates setting byte order.
package main
import (
"encoding/binary"
"fmt"
"os"
"path/filepath"
"github.com/scigolib/matlab"
)
func main() {
tmpfile := filepath.Join(os.TempDir(), "bigendian.mat")
defer os.Remove(tmpfile)
writer, _ := matlab.Create(tmpfile, matlab.Version5,
matlab.WithEndianness(binary.BigEndian),
)
defer writer.Close()
fmt.Println("Big-endian file created")
}
Output: Big-endian file created
Directories
ยถ
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
example
command
Package main provides an example of using the MATLAB file reader library.
|
Package main provides an example of using the MATLAB file reader library. |
|
write-complex
command
|
|
|
internal
|
|
|
v5
Package v5 implements MATLAB v5 format parser (v5-v7.2).
|
Package v5 implements MATLAB v5 format parser (v5-v7.2). |
|
v73
Package v73 provides internal v7.3 MAT-file parsing and writing via HDF5.
|
Package v73 provides internal v7.3 MAT-file parsing and writing via HDF5. |
|
scripts
|
|
|
generate-testdata
command
Package main - Generate minimal test MAT-files
|
Package main - Generate minimal test MAT-files |
|
verify-roundtrip
command
Package main - Critical verification script for v7.3 read/write
|
Package main - Critical verification script for v7.3 read/write |
|
Package types provides common data structures for MATLAB variables and arrays.
|
Package types provides common data structures for MATLAB variables and arrays. |