Doug’s MATLAB Video Tutorials

December 9th, 2008

Video tutorial: 3d indexing

The MATLAB user has this:

clear
clc
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));
    end
end     
MATLAB Central Files Icon

4 Responses to “Video tutorial: 3d indexing”

  1. Martin le Roux replied on :

    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.

  2. dhull replied on :

    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

  3. Hassan replied on :

    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?

  4. Hassan replied on :

    Found the error..should be
    plhs[0]=mxCreateNumericArray(3,dims,mxDOUBLE_CLASS,mxREAL);

    instead of

    plhs[0]=mxCreateNumericArray(3,dims,mxINT16_CLASS,mxREAL);

Leave a Reply

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>

If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).


Doug Hull is a proud MathWorker who is on a mission to help you with MATLAB.

Doug's picture

These postings are the author's and don't necessarily represent the opinions of The MathWorks.