【问题标题】:Counting sets and vector positions in Matlab在 Matlab 中计算集合和向量位置
【发布时间】:2015-12-09 00:28:41
【问题描述】:

假设我在 Matlab 中有以下向量:

V = [0,1,0,0,0,1,...,1]。该向量仅包含01s,条目总数为125。

我需要做两件事:

首先,我需要找到第一组连续的1s,正好有八个元素,从最后一次观察开始。

例如在:

V = [0,1,...,1,1,1,1,1,1,1,1,0,1,0,...,1,1,1,1,1,1,1,1,...,0,0,1,0,1,0,0,1,0,1,...]

我有兴趣识别1s 上的第二组并检索最后一个1 在该组中的确切位置。

我的第二个问题与第一个有关。一旦我有了集合中最后一个1 的确切位置。我需要在八个连续条目中数出六个0s。

在上面给出的例子中:

V = [0,1,...,1,1,1,1,1,1,1,1,0,1,0,...,1,1,1,1,1,1,1,1,...,0,0,1,0,1,0,0,1,0,1...]

我需要识别每个条目,直到在一组 8 个中找到 6 个 0s。

【问题讨论】:

  • 所以您正在寻找一种模式,即 1,1,1,1,1,1,1,1 然后在接下来的 8 位数字中正好有 6 个零?
  • 我正在寻找八个连续 1 的模式,但从向量中的最后一个元素开始。一旦我确定了这个集合的最后一个元素。我需要扫描条目并找到一个包含八个元素的集合,其中包含六个 0
  • 您的第二个子问题的示例是错误的,因为八个数字的序列中没有六个零。
  • 对不起!我数错了我的一个数字。谢谢!

标签: matlab vector counting


【解决方案1】:

这很有趣。不确定这是最好的方法,而且我不做任何错误检查(如果没有八个 1 或六个 0 的序列):

%// Testing with this vector
v = [0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0];
n_v = numel(v);
%// The trick is to construct a vector summing eight consecutive entries
v_s = arrayfun(@(ii) sum(v((0:7) + ii)), 1:(n_v - 7));
%// when we find entries equal to 8, we have found eight consecutive 1s
v_8 = find(v_s == 8);
%// Likewise, entries equal to 2 correspond to six zeros (in any order)
v_6_0 = find(v_s == 2);
%// We then find sequence of eight 1s followed by six 0s
v_8_with_6_0 = v_8(arrayfun(@(ii) any(ii<v_6_0), v_8));
%// ... and pick the last one
v_8_with_6_0 = v_8_with_6_0(end);
%// then we get the start of that sequence of 0s
v_6_0_pos = v_6_0(find(v_8_with_6_0 < v_6_0, 1));
%// Print result (add 7 to find last of 8)
fprintf('Last sequence of eight 1s with a following sequence containing six 0s ends at %i, and the sequence of 0s starts at %i.\n', v_8_with_6_0 + 7, v_6_0_pos);

【讨论】:

  • 简洁的解决方案。一石多鸟。
猜你喜欢
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 2016-09-26
  • 1970-01-01
  • 1970-01-01
  • 2014-06-26
  • 1970-01-01
  • 2014-11-18
相关资源
最近更新 更多