简体   繁体   English

如何使用Cgo访问MATLAB数组中的值?

[英]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. 使用MatLab C API和Go的Cgo软件包 ,我试图在Go程序的mat文件中读取24x3000000矩阵。 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.) (最终目标是将此矩阵作为切片返回给我的Go程序。)

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 供参考, 这是 C的矩阵库API

Matrix data in MATLAB are stored in column major order, which means that the columns of the data are stored in sequential order in memory (this is the opposite to C and similar languages). MATLAB中的矩阵数据按列主顺序存储,这意味着数据的列按顺序存储在内存中(这与C和类似语言相反)。 Thus, if you wanted to access the data sequentially in C (I'm not immediately familiar with Go syntax, unfortunately), you could do the following: 因此,如果您想使用C顺序访问数据(不幸的是,我并不立即熟悉Go语法),则可以执行以下操作:

for(col=0;col<colTotal;++col)
{
    for(row=0;row<rowTotal;++row)
    {
        data = realDataPtr[col*rowTotal + row];
    }
}

Untested, since I don't have MatLab. 未经测试,因为我没有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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM