我有一個MATLAB代碼是如何表示MATLAB在MEX代碼的2D陣列
%% Inputs are theta and h (size NxM)
alpha=zeros(N,M);
h_tmp=zeros(N,M);
h_tmp(1:N-1,:)=h(2:N ,:);
for i=1:N
alpha(i,:)=theta.*(h_tmp(i,:)+h(i,:));
end
通過使用向量化方法中,上述代碼可以是
alpha = theta .* [h(1:N-1,:) + h(2:N,:); h(N,:)];
爲了加快代碼,我想用C++在MEX文件中重寫它。在2D陣列MATLAB和C++之間的主要不同是行優先順序(MATLAB)和列主順序(C++)
double *h, *alpha, *h_temp;
int N,M;
double theta;
N = (int) mxGetN(prhs[0]); //cols
M = (int) mxGetM(prhs[0]); //rows
h = (double *)mxGetData(prhs[0]);
theta = (double)*mxGetPr(prhs[1]);
/* Initial zeros matrix*/
plhs[0] = mxCreateDoubleMatrix(M, N, mxREAL); alpha = mxGetPr(plhs[0]);
//////////////Compute alpha/////////
for (int rows=0; rows < M; rows++) {
//h[N*rows+cols] is h_tmp
for (int cols=0; cols < N; cols++) {
alpha[N*rows+cols]=theta*(h[N*rows+cols+1]+h[N*rows+cols]);
}
}
是我的墨西哥代碼和MATLAB等效代碼?如果不是,你能幫我解決嗎?
它不是'行+行* N',是嗎?如果我正確理解你的代碼,你必須有一個列循環,並將行數乘以列索引。它應該像'alpha [N * rows + col]'其中'col'是第二個內部循環的計數器...... – kkuilla
如何表示h和h_tmp?這是對的嗎。我現在將更正它,並再次檢查 – Jame
此外,第二個for循環中的條件絕不能是'rows