1

我按照此处显示的示例在 MEX 文件中创建了一个稀疏矩阵。现在我如何从整个 MATLAB 访问这个矩阵。

#define NZMAX 4
#define ROWS  4
#define COLS  2

int            rows=ROWS, cols=COLS;
mxArray       *ptr_array; /* Pointer to created sparse array. */
static double  static_pr_data[NZMAX] = {5.8, 6.2, 5.9, 6.1};
static int     static_ir_data[NZMAX] = {0, 2, 1, 3};
static int     static_jc_data[COLS+1] = {0, 2, 4};
double        *start_of_pr;
int           *start_of_ir, *start_of_jc;
mxArray       *array_ptr;

/* Create a sparse array. */    
array_ptr = mxCreateSparse(rows, cols, NZMAX, mxREAL); 

/* Place pr data into the newly created sparse array. */ 
start_of_pr = (double *)mxGetPr(array_ptr); 
memcpy(start_of_pr, static_pr_data, NZMAX*sizeof(double));

/* Place ir data into the newly created sparse array. */ 
start_of_ir = (int *)mxGetIr(array_ptr); 
memcpy(start_of_ir, static_ir_data, NZMAX*sizeof(int));

/* Place jc data into the newly created sparse array. */ 
start_of_jc = (int *)mxGetJc(array_ptr); 
memcpy(start_of_jc, static_jc_data, NZMAX*sizeof(int));

/* ... Use the sparse array in some fashion. */
/* When finished with the mxArray, deallocate it. */
mxDestroyArray(array_ptr);

另外,在将值存储在 中时static_pr_data,是否有必要以列主要格式存储值?是否可以以行主要格式存储(因为它会加快我的计算速度)?ic_datajc_data

4

2 回答 2

1

在您链接到的示例中,最后一条语句是

mxDestroyArray(array_ptr);

您需要将其作为 MEX 函数的输出返回,而不是破坏数组。您的 MEX 函数 C/C++ 源代码应该有一个名为mexFunction(MEX 函数的入口点)的函数,如下所示:

void mexFunction(int nlhs, mxArray * plhs[], int nrhs, const mxArray * prhs[])

要从 MEX 函数返回输出,请将其分配到plhs数组中,如下所示:

plhs[0] = array_ptr; // instead of mxDestroyArray(array_ptr);

将代码编译成 MEX 函数(我们称之为sparsetest)。像这样从 MATLAB 调用它:

>> output = sparsetest;

现在output是一个 MATLAB 变量,其中包含您在 MEX 函数中创建的稀疏矩阵。

至于以行主要格式存储数据,这是不可能的。MATLAB 仅处理以列为主的稀疏矩阵。

于 2011-05-28T23:41:03.750 回答
0

使用从 matlab 结构中获取矩阵字段的提示engGetVariable()

我有一个结构体,它的字段是一个矩阵。例如,在 C++ 中,相应的结构是 double**。尝试使用 engGetVariable(engine,MyStruct.theField) 访问该字段失败。我使用一个临时变量来存储 MyStruct.theField,然后使用 engGetVariable(engine, tempVar),从结构中获取矩阵字段的代码看起来像这样

// Fetch struct field using a temp variable
std::string tempName = std::string(field_name) + "_temp";
std::string fetchField = tempName + " = " + std::string(struct_name) 
        + "." + std::string(field_name) + "; ";
matlabExecute(ep, fetchField);
mxArray *matlabArray = engGetVariable(ep, tempName.c_str());

// Get variable elements
const int count = mxGetNumberOfElements(matlabArray);
T *data = (T*) mxGetData(matlabArray);
for (int i = 0; i < count; i++)
    vector[i] = _isnan(data[i]) ? (T) (int) -9999 : (T) data[i];

// Clear temp variable
std::string clearTempVar = "clear " + tempName + "; ";
matlabExecute(ep, clearTempVar);

// Destroy mx object
mxDestroyArray(matlabArray);
于 2014-11-13T08:24:22.347 回答