2015-09-06 157 views
2

如何刪除矩陣中不是全部位於一條直線中的元素,而是不通過for循環中的某一行?從矩陣的每一行中刪除一個元素,每個元素都在不同的列中

實施例:

[1 7 3 4; 
1 4 4 6; 
2 7 8 9] 

給定一個向量(例如,[2,4,3])如何可以刪除的元素的每一行(其中,向量中的每個數字對應於列編號)不經去通過每一行,並刪除每個元素?

示例輸出將是:

[1 3 4; 
1 4 4; 
2 7 9] 

回答

1

它可以使用在linear indexing如下進行。請注意,這是更好地工作下來列(因爲Matlab的column-major順序),這意味着在開始和結束時換位:

A = [ 1 7 3 4 
     1 4 4 6 
     2 7 8 9 ]; 
v = [2 4 3]; %// the number of elements of v must equal the number of rows of A 
B = A.'; %'// transpose to work down columns 
[m, n] = size(B); 
ind = v + (0:n-1)*m; %// linear index of elements to be removed 
B(ind) = []; %// remove those elements. Returns a vector 
B = reshape(B, m-1, []).'; %'// reshape that vector into a matrix, and transpose back 
+0

謝謝!你能得到這個工作的3D矩陣(元素中的所有圖層被刪除?)。或者,3D矩陣的線性索引太笨重了? – llll0

+0

我認爲這是可以做到的。但我不確定你想要什麼。由於這似乎是一個重大的改變,所以我建議你發一個新的問題。一定要包括一個例子 –

0

下面是使用bsxfunpermute解決了3D陣列情況下的一種方法,假設要在所有的3D片除去每行的索引元素 -

%// Inputs 
A = randi(9,3,4,3) 
idx = [2 4 3] 

%// Get size of input array, A 
[M,N,P] = size(A) 

%// Permute A to bring the columns as the first dimension 
Ap = permute(A,[2 1 3]) 

%// Per 3D slice offset linear indices 
offset = bsxfun(@plus,[0:M-1]'*N,[0:P-1]*M*N) %//' 

%// Get 3D array linear indices and remove those from permuted array 
Ap(bsxfun(@plus,idx(:),offset)) = [] 

%// Permute back to get the desired output 
out = permute(reshape(Ap,3,3,3),[2 1 3]) 

採樣運行 -

>> A 
A(:,:,1) = 
    4  4  1  4 
    2  9  7  5 
    5  9  3  9 
A(:,:,2) = 
    4  7  7  2 
    9  6  6  9 
    3  5  2  2 
A(:,:,3) = 
    1  7  5  8 
    6  2  9  6 
    8  4  2  4 
>> out 
out(:,:,1) = 
    4  1  4 
    2  9  7 
    5  9  9 
out(:,:,2) = 
    4  7  2 
    9  6  6 
    3  5  2 
out(:,:,3) = 
    1  5  8 
    6  2  9 
    8  4  4 
相關問題