Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to flatten a 2D matrix to 1D when sliced from a 3D matrix variable

I have a 3D matrix in Matlab to store a sequence of 2D arrays. I'm having to find the maximal value and its row and column indices, which is pretty straightforward for a single variable that holds a 2D array as in

A = rand(10,10);
[m,i] = max(A(:));
[I,J] = ind2sub( size(A) , i )

The trouble is that I cannot use this syntax for the 3D matrix

A = rand(10,10,3);
[m,i] = max( A(:,:,1)(:) );
[I,J] = ind2sub(size( A(:,:,1) ), i )

Error: ()-indexing must appear last in an index expression.

I could create a temporary variable to store the 2D slice, but I'd thought I'd see if there's a better means of doing this, maybe making a call to reshape? Is there any way to use the simple linearizing/flattening operator (:) in this context?

like image 321
jxramos Avatar asked Jul 23 '15 20:07

jxramos


2 Answers

Here's what I'd do:

[B i]=max(reshape(A,[],size(A,3)));
[II,JJ]=ind2sub(size(A),i );

The only limitation is that it wont treat well cases where there is more than one max per 2D slice.

like image 96
bla Avatar answered Sep 29 '22 00:09

bla


You could convert it to a cell array and use cellfun

B=mat2cell(reshape(A,[1, size(A,2).^2, size(A,3)]),[1],[size(A,2).^2], [ones(size(A,3),1)]);
[M,I]= cellfun(@max,B)
[R,C] = ind2sub(size(A),I);

M contains the maximum value and I the corresponding index.


Assuming that A is a 3x3x2 array.

A =[

    0.7952    0.4456    0.7547
    0.1869    0.6463    0.2760
    0.4898    0.7094    0.6797];

A(:,:,2) =[

    0.6551    0.4984    0.5853
    0.1626    0.9597    0.2238
    0.1190    0.3404    0.7513];

Convert each slice into a 1x9x2 cell array

B=mat2cell(reshape(A,[1, size(A,2).^2, size(A,3)]),[1],[size(A,2).^2], [ones(size(A,3),1)]);

B(:,:,1) = 

    [1x9 double]


B(:,:,2) = 

    [1x9 double]

Take the maximum of each slice. R is the row and C is the column for the respective maximum value in M.

[M,I]= cellfun(@max,B)
[R,C] = ind2sub(size(A),I)

R(:,:,1) =

     1

R(:,:,2) =

     2

C(:,:,1) =

     1

C(:,:,2) =

     2
like image 39
kkuilla Avatar answered Sep 28 '22 23:09

kkuilla