Accessing 3-dimensional matrix by a 2-dimensional index in matlab/octave -


i have 3 dimensional matrix (3rd dimension represents multiple copies of m x n grayscale image).

i'm taking max value of each pixel across images, giving me max_val , max_ix matrix (2x2).

i want reference original test matrix max_ix values.

example: my_max_val = test(max_ix,:) should equal:

     5     1      1     1 

obviously can use max_val in simplified example, not in real use case. i'm altering max_ix, need reference original 3-dimensional matrix new index values create (not depicted in simplified example).

>> test  test(:,:,1) =       1     1      1     1   test(:,:,2) =       1     1      1     1   test(:,:,3) =       5     1      1     1   test(:,:,4) =       1     1      1     1  >> [max_val, max_ix] = max(test, [], 3)  max_val =       5     1      1     1   max_ix =       3     1      1     1 

how recreate max_val test , max_ix?

one approach -

%// size of 3d input array [m,n,~] = size(test);       %// calculate 2d starting, offset & actual indices array start_idx = bsxfun(@plus,[1:m]',[0:n-1]*m);  %//' offset_idx = m*n*(max_ix-1); actual_idx = start_idx + offset_idx;  %// index 3d input array extract specific elements, desired output max_val = test(actual_idx) 

thus, giving two-liner solution, if compact codes -

[m,n,~] = size(test);      max_val = test( bsxfun(@plus,[1:m]',[0:n-1]*m) + m*n*(max_ix-1) ) 

please note bsxfun(@plus,[1:m]',[0:n-1]*m) replaced reshape(1:m*n,m,n).

sample run

inputs:

test(:,:,1) =     12    66    75    98     65    75    24    87     33    59    74     9 test(:,:,2) =     37    60    21    21     37    79     9    39     69    37    78    56 test(:,:,3) =     23    16    30    10     65    79    24    41     49    11    54    11 test(:,:,4) =     12    61    70    66     79    97    76    11     30    44    44    94 max_ix =      1     2     2     2      2     4     1     2      4     2     3     3 

output:

max_val =     12    60    21    21     37    97    24    39     30    37    54    11 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -