1

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.

Romalpa Akzo
  • 599
  • 1
  • 4
  • 12

1 Answers1

1

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
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Many thanks, Luis. The code seems to work well for the given example. But if I change the size of A, for example, `A=rand(4,4,5);` and `idn = [5;1;2;4];`, the error `Index exceeds the number of array elements` is notified. Kindly give me further instructions. – Romalpa Akzo Apr 24 '22 at 23:49
  • 1
    In trying to understand the algorithm, I guess the fourth line could be: `ind = ind + size(A,1)*(0:size(A,2)-1);`. Please advise me further. Thanks. – Romalpa Akzo Apr 25 '22 at 00:28
  • 1
    @RomalpaAkzo Yes, it is as you say, sorry for the misttake. I just corrected it – Luis Mendo Apr 25 '22 at 10:15