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只是为了清楚起见;这不是我使用的实际数据。)

4

2 回答 2

1

我不确定的一件事是是否有更好的方法来找到being_indicesand end_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
于 2013-03-26T01:06:21.170 回答
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
于 2013-03-26T00:20:47.350 回答