Search code examples
cmatlabgomat-filecgo

How do I access the values inside a MATLAB array using Cgo?


Using the MatLab C API and Go's Cgo package, I'm attempting to read a 24x3000000 matrix inside a mat-file in my Go program. I'm able to successfully read the dimensions of the matrix but how do I access the values inside each cell? (The goal is ultimately to return this matrix as a slice to my Go program.)

var realDataPtr *C.double
var field *C.mxArray

fieldName := C.CString("data")
field = C.mxGetField(pa, 0, fieldName)

rowTotal := C.mxGetM(field) // outputs 24
colTotal := C.mxGetN(field) // outputs 3000000

// get pointer to data in matrix
realDataPtr = C.mxGetPr(field)

// Print every element in the matrix
for row := 0; row < int(rowTotal); row++ {
    for col := 0; col < int(colTotal); col++ {
        // This is where I get stuck
    }
}

For reference, here's the Matrix Library API for C


Solution

  • Untested, since I don't have MatLab. For example,

    import (
        "fmt"
        "unsafe"
    )
    
    // Print every element in the matrix
    ptr := uintptr(unsafe.Pointer(realDataPtr))
    for col := 0; col < int(colTotal); col++ {
        for row := 0; row < int(rowTotal); row++ {
            // This is where I get stuck
            elem := *(*float64)(unsafe.Pointer(ptr))
            fmt.Println(elem)
            ptr += 8
        }
    }