Yes, in MATLAB there are often many ways of doing the same thing. I do not know which one is faster, I suspect that the difference is negligible.
As you said, your code is harder to read, so that would make me want to do it another way. Personally, I try to write code that is easy to read and understand. Once it is working, then if there are sections that are slow, I will try more advanced maneuvers like you pointed out to trade readability for speed.
What about the following:
[nR,nC] = size(J);
[r,c] = ndgrid(1:nR,1:nC);
M(sub2ind(size(M),r,c,J))
Admittedly it’s harder to read, but it might be faster if J is large.
Martin,
Yes, in MATLAB there are often many ways of doing the same thing. I do not know which one is faster, I suspect that the difference is negligible.
As you said, your code is harder to read, so that would make me want to do it another way. Personally, I try to write code that is easy to read and understand. Once it is working, then if there are sections that are slow, I will try more advanced maneuvers like you pointed out to trade readability for speed.
As always, thanks for reading and adding,
Doug
I am have problem populating 3D matrix using mex file. I have a 3D int array
double *outArray;
dims[0]=4;dims[1]=2;dims[2]=3;
plhs[0]=mxCreateNumericArray(3,dims,mxINT16_CLASS,mxREAL);
outArray = mxGetPr(plhs[0]);
outArray[0]=12;
It gives random numbers in the output. If i do it using 2D matrix I have no problem.. any ideas?
Found the error..should be
plhs[0]=mxCreateNumericArray(3,dims,mxDOUBLE_CLASS,mxREAL);
instead of
plhs[0]=mxCreateNumericArray(3,dims,mxINT16_CLASS,mxREAL);