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

Time:04-25

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 coresponding choice. Given idn is not constant, it is clear that a simple squeeze could not help.

So, 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);

It is very much appreciated if anyone could teach me how to do that. Many thanks.

Added: I have tried the below code, but it clearly does not work.

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

CodePudding user response:

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
  • Related