2011-05-27 100 views
1

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

#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_dataic_datajc_data值是有必要存储在列优先格式值是多少?是否有可能以行格式存储(因为它会加快我的计算)?

+0

请张贴相关的代码** **在这里,而比链接。 – PengOne 2011-05-27 15:03:02

+0

会听从你的意见克里斯! – koder 2011-05-29 07:41:49

回答

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是包含在您的MEX-函数创建的稀疏矩阵MATLAB变量。

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

+0

谢谢@SCFrench它的工作:) – koder 2011-05-29 07:41:22

+0

当我做输出(1,1)或任何指数的值总是0!我无法得到的实际值。问题是什么?我是否以错误的方式访问值? – koder 2011-05-30 05:32:59

+0

我解决了我的问题,我认为ir数据中的值必须以索引1开始,但实际上它应该只以0索引开始......感谢您的帮助 – koder 2011-05-30 05:37:31

0

尖端从使用engGetVariable()

我有一个字段,该字段是一个矩阵一个结构的一个matlab结构得到的矩阵字段。在C++中,相应的结构是双**。尝试使用engGetVariable(engine,MyStruct.theField)访问该字段失败。我用一个临时变量来存储MyStruct.theField然后用engGetVariable(发动机,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);