提取部分矩阵到细胞阵列



我有一个相当大的矩阵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;这不是我使用的实际数据。)

您可以使用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

我不确定的一件事是,如果有更好的方法来找到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

最新更新