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

78 views Asked by At

I have:

  • A matrix 3D: A = (m, n, k).

  • An array of choices for the third dimension corresponding to each index of the first dimension. idn = (m, 1) (wherein the value of any idn is a random integer in [1,k].

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.

1

There are 1 answers

3
Luis Mendo On BEST ANSWER

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