2

I have 2 3D matrices:

A=[19,18,17;16,15,14;13,12,11];

A(:,:,2)=[9,8,7;6,5,4;3,2,1];

B=sort(A,3);

With output

A(:,:,1) =


19 18 17

16 15 14

13 12 11


A(:,:,2) =


9 8 7

6 5 4

3 2 1


B(:,:,1) =


9 8 7

6 5 4

3 2 1


B(:,:,2) =


19 18 17

16 15 14

13 12 11

and I want to find the 3rd coordinate of one of the matrices of B in A.

so

find(A==B(:,:,1))

the answer is

ans =



10

11

12

13

14

15

16

17

18

However, I want the answer to be 2, because this matrix is in the second position in the third dimension of A: A(:,:,2)

How do I do this?

I tried find(A(~,~,:)==B(:,:,1)) but that gave an error.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Jellyse
  • 839
  • 7
  • 22
  • why the secondary output of the sort function, the indices, are not what you are looking for? – Gideon Kogan Dec 16 '19 at 10:31
  • @GideonKogan if you do ´[x,y,z]=find(A==B(:,:,1))´ y=[4,4,4,5,5,5,6,6,6] which you cant fill into A because that always has a max of 3 (A(1,4,1) is impossible) – Jellyse Dec 16 '19 at 10:37

1 Answers1

3

You can use ind2sub to convert linear indices (which find() gives you) to indices per dimension:

A=[19,18,17;16,15,14;13,12,11];

A(:,:,2)=[9,8,7;6,5,4;3,2,1];

B=sort(A,3);

lin_idx = find(A==B(:,:,1));

[row,col,page] = ind2sub(size(A),lin_idx);  % page is 2 everywhere

I recommend reading this Q/A for more information on the different types of indexing which MATLAB supports.

Adriaan
  • 17,741
  • 7
  • 42
  • 75