2013-03-25 78 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