Stuart’s MATLAB Videos

Watch and Learn

Video tutorial: 3d indexing 4

Posted by Doug Hull,

The MATLAB user has this:

M(:,:,1) = [1,2;3,4];
M(:,:,2) = [21,22;23,24];
J = [1,2; 2,1];
They want this:
ans =
[1 22
23 4]
They tried this:
D = M(:,:,J) % This doesn't work,
This video discusses this solution:
[nR, nC] = size(J);
D = zeros(nR,nC);
for r = 1:nR
     for c = 1:nC
          D(r,c) = M(r,c,J(r,c));

4 CommentsOldest to Newest

Martin le Roux replied on : 1 of 4
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.
dhull replied on : 2 of 4
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
Hassan replied on : 3 of 4
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?
Hassan replied on : 4 of 4
Found the error..should be plhs[0]=mxCreateNumericArray(3,dims,mxDOUBLE_CLASS,mxREAL); instead of plhs[0]=mxCreateNumericArray(3,dims,mxINT16_CLASS,mxREAL);