2014-01-29 112 views
4

如何通過使用2d矩陣索引元素級數組的維數,這些矩陣的哪些條目表示哪些維(代表切片或2d矩陣)從中獲取值?在Matlab中使用矩陣對多維數組進行索引

I=ones(2)*2; 
J=cat(3,I,I*2,I*3); 

indexes = [1 3 ; 2 2] ; 

所以J是

J(:,:,1) = 

2  2 
2  2 


J(:,:,2) = 

4  4 
4  4 


J(:,:,3) = 

6  6 
6  6 

它的工作原理很容易地使用2 for循環

for i=1:size(indexes,1) 
    for j=1:size(indexes,2) 
     K(i,j)=J(i,j,indexes(i,j)); 
    end 
end 

其產生所期望的結果

K = 

2  6 
4  4 

但有一個量化/智能這樣做的索引方式?

%K=J(:,:,indexes) --does not work 

回答

3

只需使用linear indexing

nElementsPerSlice = numel(indexes); 

linearIndices = (1:nElementsPerSlice) + (indexes(:)-1) * nElementsPerSlice; 

K = J(linearIndices); 
1

可以使用sub2ind到矩陣索引轉換成線性指數

ind = sub2ind(size(J), [1 1 2 2], [1 2 1 2], [1 3 2 2]); 
K = resize(J(ind), [2 2]);