我按照 here 中所示的示例在 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_data
和 jc_data
中时,是否有必要以列主要格式存储值?是否可以以行主要格式存储(因为它会加快我的计算速度)?
最佳答案
在您链接到的示例中,最后一条语句是
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 仅处理列主稀疏矩阵。
关于c - 从 MATLAB 访问在 MEX 中创建的稀疏矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6154072/