I have a MATLAB code which is
%% 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
By using vectorized method, the above code can be
alpha = theta .* [h(1:N-1,:) + h(2:N,:); h(N,:)];
To speed up the code, I want to rewrite it in MEX file using C++. The main different between MATLAB and C++ in 2D array is row-major order (MATLAB) and column-major order(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]);
}
}
Are my Mex code and MATLAB code equivalent? If not, could you help me to fix it?