2012-06-29 30 views
1

假設一個3-d矩陣:有沒有辦法在MatLab中使用線性索引返回許多列?

>> a = rand(3,4,2) 

a(:,:,1) = 

    0.1067 0.7749 0.0844 0.8001 
    0.9619 0.8173 0.3998 0.4314 
    0.0046 0.8687 0.2599 0.9106 


a(:,:,2) = 

    0.1818 0.1361 0.5499 0.6221 
    0.2638 0.8693 0.1450 0.3510 
    0.1455 0.5797 0.8530 0.5132 

我用線性索引同時有許多元素:

>> index1 = [1 ; 2 ; 1 ; 3]; 
>> index2 = [1 ; 4 ; 2 ; 3]; 
>> index3 = [1 ; 1 ; 2 ; 1]; 

>> indices = sub2ind(size(a), index1, index2, index3) 

>> a(indices) 

ans = 

    0.1067 
    0.4314 
    0.1361 
    0.2599 

我願做同樣的事情,把返回的所有值第一個維度。這個尺寸的大小可能會有所不同。在這種情況下,退貨應該是:

>> indices = sub2ind(size(a), ??????, index2, index3); 

>> a(indices) 

ans = 

    0.1067 0.9619 0.0046 % a(:,1,1) 
    0.8001 0.4314 0.9106 % a(:,4,1) 
    0.1361 0.8693 0.5797 % a(:,2,2) 
    0.0844 0.3998 0.2599 % a(:,3,1) 

任何方式在MatLab中做到這一點?

+0

'index1之間= [1; 2; 1; 3];'相當於'index1 = [1 2 1 3]';'(不是一個解決方案,但很好知道) – Jacob

回答

2
ind1 = repmat((1:size(a,1)),length(index2),1); 
ind2 = repmat(index2,1,size(a,1)); 
ind3 = repmat(index3,1,size(a,1)); 

indices = sub2ind(size(a),ind1,ind2,ind3) 

indices = 

1  2  3 
10 11 12 
16 17 18 
7  8  9 

a(indices) 


ans = 

    0.1067 0.9619 0.0046 
    0.8001 0.4314 0.9106 
    0.1361 0.8693 0.5797 
    0.0844 0.3998 0.2599 
1

您可以通過對與前兩個維度分開的最後兩個維度執行線性索引來獲得所需的結果。即使在您期望通過a(:,:,:)參考的3d數據塊中,您也可以通過a(:)(如您所知)a(:,:)來參考。以下代碼找到最後兩個維度的sub2ind,然後使用meshgrid重複使用它們。這種最終被非常類似於由@tmpearce提出的解決方案,但明確地示出了半線性索引和使用meshgrid代替repmat

dim1 = 3; 
dim2 = 4; 
dim3 = 2; 

rand('seed', 1982); 
a = round(rand(dim1,dim2,dim3)*10) 

% index1 = : 
index2 = [1 ; 4 ; 2 ; 3]; 
index3 = [1 ; 1 ; 2 ; 1]; 

indices = sub2ind([dim2 dim3], index2, index3) 
a(:, indices) % this is a valid answer 

[X,Y] = meshgrid(1:dim1, indices) 
indices2 = sub2ind([dim1, dim2*dim3], X,Y); 

a(indices2) % this is also a valid answer, with full linear indexing 
+0

另一個說明:記住'meshgrid'是一個特殊的繪圖'ndgrid'的面向對象版本。函數'meshgrid'與'ndgrid'的功能相同,但翻轉最後兩個輸出。這是因爲對數據的情節導向或數據結構理解之間存在解釋性「不匹配」;例如行是MATLAB中數組的第一個維度,但也可以認爲是y軸(這是歐幾里德幾何中的第二個軸)。這就是爲什麼'meshgrid'翻轉兩個輸出。你應該使用'ndgrid'嗎? –

相關問題