簡體   English   中英

在Matlab / Octave中通過2維索引訪問3維矩陣

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

我有一個3維矩陣(第3維代表M x N灰度圖像的多個副本)。

我采用圖像中每個像素的最大值,從而得到了max_valmax_ix矩陣(2x2)。

我想通過max_ix值引用原始test矩陣。

示例: my_max_val = test(max_ix,:)應該等於:

     5     1
     1     1

顯然,我可以在此簡化示例中使用max_val ,但不能在實際用例中使用。 我正在更改max_ix ,因此我需要通過我創建的新索引值來引用原始3維矩陣(在此簡化示例中未進行描述)。

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

如何僅從testmax_ix重新創建max_val

一種方法-

%// Get size of 3D input array
[m,n,~] = size(test);     

%// Calculate 2D starting, offset & finally 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 into 3D input array to extract specific elements, for desired output
max_val = test(actual_idx)

因此,如果您使用緊湊的代碼,從本質上講可以為我們提供兩層解決方案-

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

請注意, bsxfun(@plus,[1:m]',[0:n-1]*m)可以替換為reshape(1:m*n,m,n)

樣品運行

輸入:

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

輸出:

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

這是一種方法。

%// Generate matrix test
test = randi(50,4,4,4);

%// Get maximum value and indices
[max_val, max_ix] = max(test, [], 3);

%// We don't know the size in general so this is the Cartesian product
[y, x] = meshgrid(1:size(test, 1), 1:size(test,2));

%// sub2ind provide the single value indices for a matrix of size(test) 
%// at positions [x(:), y(:), max_ix(:)] and reshape brings it back to the correct shape
max_val2 = reshape(test(sub2ind(size(test), x(:) , y(:), max_ix(:))), size(x));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM