我必須讀取一個double的矩陣,處理它的值並將它們插入一個新的矩陣,它的一個維度在開始時是未知的。mex內存分配mxRealloc
在靜態內存分配,我的代碼是:
#include <mex.h>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
const mxArray *I = prhs[0];
double *indata = mxGetPr(I);
double *submtx = mxGetPr(prhs[1]);
const int *size = mxGetDimensions(I);
int xp = (int)submtx[0], yp = (int)submtx[1], zp = (int)submtx[2];
int xi = size[0], yi = size[1], zi = size[2];
int numsubmtx = (xi - xp + 1)*(yi - yp + 1)*(zi - zp + 1);
int out_rows = xp*yp*zp;
int out_cols = numsubmtx;
mxArray *out = mxCreateDoubleMatrix(out_rows, out_cols, mxREAL);
double *outdata = mxGetPr(out);
int submtx_counter = 0;
for(int z_offset = 0; ...; z_offset++){
for(int y_offset = 0; ...; y_offset++){
for(int x_offset = 0; ...; x_offset++){
int row = 0;
for(int z_counter = 0; ...; z_counter++){
for(int y_counter = 0; ...; y_counter++){
for(int x_counter = 0; ...; x_counter++){
outdata[submtx_counter*out_rows + row] =
indata[ (x_offset+x_counter) + (y_offset+y_counter)*xi + (z_offset+z_counter)*xi*yi ];
++row;
}}}
++submtx_counter;
}}}
plhs[0] = out;
}
在一個動態的版本,我不知道out_cols
的價值,所以我必須要重新分配*out
當上indata
值的條件滿意。
我的想法是這樣的:
#include <mex.h>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
const mxArray *I = prhs[0];
double *indata = mxGetPr(I);
double *submtx = mxGetPr(prhs[1]);
const int *size = mxGetDimensions(I);
int xp = (int)submtx[0], yp = (int)submtx[1], zp = (int)submtx[2];
int xi = size[0], yi = size[1], zi = size[2];
int numsubmtx = (xi - xp + 1)*(yi - yp + 1)*(zi - zp + 1);
int out_rows = xp*yp*zp;
//int out_cols = numsubmtx; NOW UNKNOWN!
mxArray *out = NULL;
double *outdata = mxGetPr(out);
int submtx_counter = 0;
for(int z_offset = 0; ...; z_offset++){
for(int y_offset = 0; ...; y_offset++){
for(int x_offset = 0; ...; x_offset++){
int row = 0;
double condition=0;
for(int z_counter = 0; ...; z_counter++){
for(int y_counter = 0; ...; y_counter++){
for(int x_counter = 0; ...; x_counter++){
condition += indata[ (x_offset+x_counter) + (y_offset+y_counter)*xi + (z_offset+z_counter)*xi*yi ]/(xp*yp*zp);
++row;
}}}
if(coundition>0.5){
out = mxRealloc(out, (submtx_counter+1)*out_rows*sizeof(double));
double *outdata = mxGetPr(out);
int row = 0;
for(int z_counter = 0; ...; z_counter++){
for(int y_counter = 0; ...; y_counter++){
for(int x_counter = 0; ...; x_counter++){
outdata[submtx_counter*out_rows + row] = indata[ (x_offset+x_counter) + (y_offset+y_counter)*xi + (z_offset+z_counter)*xi*yi ];
++row;
}}}
++submtx_counter;
}
}}}
plhs[0] = out;
}
有什麼不對?
什麼是'patch_counter',爲什麼它永遠不會改變? – Isaac 2012-07-21 12:49:11
你說得對。 'patch_counter'是'submtx_counter'。我想在動態版本中轉換您的代碼。 – 2012-07-21 13:02:21
如果我不知道'out_cols'的數目,我該如何動態分配'* out'?使用'mxRealloc'是否正確?你可以幫幫我嗎?先謝謝你。 – 2012-07-21 14:22:52