2013-03-25 96 views
0

我有一個相當大的矩陣M,我只對一些列感興趣。我有一個布爾向量V其中值1表示一個感興趣的列。例如:將矩陣的部分提取到單元陣列中

 -1 -1 -1 7 7 -1 -1 -1 7 7 7 
M = -1 -1 7 7 7 -1 -1 7 7 7 7 
     -1 -1 7 7 7 -1 -1 -1 7 7 -1 

V = 0 0 1 1 1 0 0 1 1 1 1 

如果V多個相鄰值全部1,那麼我想的M相應列被提取到另一個矩陣。這裏有一個例子,使用之前的矩陣。

 -1 7 7    -1 7 7 7 
M1 = 7 7 7  M2 = 7 7 7 7 
     7 7 7    -1 7 7 -1 

我該如何有效地做到這一點?我希望將矩陣M的所有這些部分存儲在單元陣列中,或者至少有一個有效的方法來依次生成它們。目前我正在做一個while循環,並不像我想要的那樣高效。

(請注意,我的例子僅包括價值-17只是爲了清楚起見,這是不是我用的是實際數據。)

+1

只是好奇,你使用的是什麼實現? – Justin 2013-03-26 01:27:21

+0

事實上,我之前沒有看到過這種計算方式,所以這讓我想知道你想達到什麼目的。可能有更好的方法。 – 2013-03-27 17:09:16

+0

@ DennisJaheruddin我試圖從圖像中提取字母。 – 2013-03-27 17:53:22

回答

1

您可以利用diff功能對於這一點,打破你的V載體導入塊

% find where block differences exist 
diffs = diff(V); 
% move start index one value forward, as first value in 
% diff represents diff between first and second in original vector 
startPoints = find(diffs == 1) + 1; 
endPoints = find(diffs == -1); 

% if the first block begins with the first element diff won't have 
% found start 
if V(1) == 1 
    startPoints = [1 startPoints]; 
end 

% if last block lasts until the end of the array, diff won't have found end 
if length(startPoints) > length(endPoints) 
    endPoints(end+1) = length(V); 
end 

% subset original matrix into cell array with indices 
results = cell(size(startPoints)); 
for c = 1:length(results) 
    results{c} = M(:,startPoints(c):endPoints(c)); 
end 
+1

+1:順便說一下,可以用'strfind'縮短索引的計算:'startPoints = strfind([0 V],[0 1]); endPoints = strfind([V 0],[1 0]);'。 – 2013-03-27 23:55:00

1

有一兩件事我不知道的是,如果有找到being_indicesend_indices一個更好的辦法。

代碼:

X = [1  2  3  4  5  1  2  3  4  5 
    6  7  8  9 10  6  7  8  9 10 
    11 12 13 14 15 11 12 13 14 15 
    16 17 18 19 20 16 17 18 19 20 
    1  2  3  4  5  1  2  3  4  5 
    6  7  8  9 10  6  7  8  9 10 
    11 12 13 14 15 11 12 13 14 15 
    16 17 18 19 20 16 17 18 19 20]; 

V = logical([ 1  1  0  0  1  1  1  0  1 1]); 

find_indices = find(V); 
begin_indices = [find_indices(1) find_indices(find(diff(find_indices) ~= 1)+1)]; 
end_indices = [find_indices(find(diff(find_indices) ~= 1)) find_indices(end)]; 

X_truncated = mat2cell(X(:,V),size(X,1),[end_indices-begin_indices]+1); 
X_truncated{:} 

輸出:

ans = 

    1  2 
    6  7 
    11 12 
    16 17 
    1  2 
    6  7 
    11 12 
    16 17 


ans = 

    5  1  2 
    10  6  7 
    15 11 12 
    20 16 17 
    5  1  2 
    10  6  7 
    15 11 12 
    20 16 17 


ans = 

    4  5 
    9 10 
    14 15 
    19 20 
    4  5 
    9 10 
    14 15 
    19 20 
+0

那麼,我剛剛分析了'mat2cell'函數對DMR的for循環,它似乎'mat2cell'更慢...... – Justin 2013-03-26 01:42:52