arraysmatlabmatrixarray-indexing

Get Matrix 2D from Matrix 3D with a given choice of the third dimension corresponding to the first dimension


I have:

I need to capture the 2D matrix B (m,n) wherein the referred third dimension to A is taken from the corresponding choice. For example:

idn(1) = 1;
idn(2) = k;
idn(j) = k-1;

Then:

B(1,:) = A(1,:,idn(1)) = A(1,:,1);
B(2,:) = A(2,:,idn(2)) = A(2,:,k);
B(j,:) = A(j,:,idn(j)) = A(j,:,k-1);

Since idn is not constant, a simple squeeze could not help.

I have also tried the below code, but it does not work either.

B = A(:,:,idn(:));

It is very much appreciated if anyone could give me a solution.


Solution

  • This could be done with sub2ind and permute, but the simplest way I can think of is using linear indexing manually:

    A = rand(3, 4, 5); % example data
    idn = [5; 1; 2];   % example data
    ind = (1:size(A,1)).' + size(A,1)*size(A,2)*(idn(:)-1); % 1st and 3rd dimensions
    ind = ind + size(A,1)*(0:size(A,2)-1); % include 2nd dimension using implicit expansion
    B = A(ind); % index into A to get result