【问题标题】:How do I access the values inside a MATLAB array using Cgo?如何使用 Cgo 访问 MATLAB 数组中的值?
【发布时间】:2014-12-28 23:35:14
【问题描述】:

使用 MatLab C API 和 Go 的 Cgo package,我试图在我的 Go 程序的 mat 文件中读取 24x3000000 矩阵。我能够成功读取矩阵的维度,但如何访问每个单元格内的值? (最终目标是将此矩阵作为切片返回给我的 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
    }
}

供参考,here's C 矩阵库 API

【问题讨论】:

  • mxGetPr 返回一个指向 double 类型的常规 C 数组的指针,长度为 24*3000000,以列优先顺序存储
  • 你能告诉我们你得到field的部分吗?下面是从 MAT 文件中读取变量的示例:stackoverflow.com/a/26241535/97160。如果您愿意,我可以展示另一个示例(在 C 语言中,恐怕我不知道 Go),但是如果您给我们更多关于数组来自哪里的上下文,这将有所帮助..
  • @Amro 我更新了我的代码以显示我在哪里得到field。出于某种原因,C.mxGetPr(field) 返回 null。根据文档,这意味着没有真实数据。但是,我使用验证方法 mxIsDoublemxIsNumeric 测试了 field,并且都返回 true。
  • 哦,这可能是它。它没有显示在我的代码中,但我使用的是matGetNextVariableInfo,根据文档,它只读取标题信息。我可能应该使用matGetVariable
  • 我使用 matGetNextVariable 而不是 matGetNextVariableInfo 并且 C.mxGetPr(field) 不再返回 null。但是我仍然不确定如何在不使用指针自动增量的情况下访问这些值。 Go 不允许指针算术。

标签: c matlab go mat-file cgo


【解决方案1】:

未经测试,因为我没有 MatLab。例如,

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
    }
}

【讨论】:

    【解决方案2】:

    MATLAB 中的矩阵数据是按列主序存储的,也就是说数据的列是按顺序存储在内存中的(这与 C 和类似语言相反)。因此,如果您想在 C 中按顺序访问数据(不幸的是,我对 Go 语法并不熟悉),您可以执行以下操作:

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

    【讨论】:

    • 应该是col*rowCount 而不是col*colCount
    • 感谢您的澄清。有谁知道如何使用 Cgo 访问 realDataPtr 中的值?
    猜你喜欢
    • 1970-01-01
    • 2020-02-04
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    相关资源
    最近更新 更多