在matlab中仅打印数组中的连续数字

时间:2014-02-04 08:20:35

标签: arrays matlab

我的matlab代码中有一个数组,我想要做的是, 我们可以说阵列是:

wf_array = [1 2 3 4 5 6 7 8 9 10 11  25 26 28 29 45 46 47 48 49 50 51 52 53 54 55 56 57]

预期输出为:1 2 3 4 5 6 7 8 9 10 11 and 45 46 47 48 49 50 51 52 53 54 55 56 57

因此,如果该系列连续至少10个数字,那么o / p应包含该数组的连续数字。

我试过以下

v = wf_array;
x = [0 cumsum(diff(v)~=1)];
final = v(x==mode(x));

但它只打印来自array的最长连续流,因为它应该打印至少10个数字的所有连续流。请帮忙......

提前致谢

1 个答案:

答案 0 :(得分:2)

好吧,当至少有一个值不连续时,你的cumsum会计算在内。这意味着,您的每个流在x中都会有不同的数字。另一方面,mode只找到最频繁的数字,并且找到它们中最小的一个(所以如果有几个相同长度的流,则第一个将被采用)。根据{{​​1}}的文档,“mode函数不适合在具有多种模式的分布中查找峰值。”

因此,有3种方法可以解决这个问题。第一种方法是以一种使所有流具有相同数字的方式改变x。第二种是用可以找到多种模式的东西替换mode。第三是采取完全不同的方法并拆分数组。

我会选择第三个,因为我认为这是“最简单的”。

mode

请注意,此尝试不够健壮,仅适用于大小为w = find( diff(v)~=1 ); %// this contains all indices where the data jumps x = diff([0 w length(v)]); %// this contains the lengths of the streams y = mat2cell(v,1,x); %// creates a cell array with each consecutive stream z = y( cellfun('size',y,2)>=10 ) %// picks those cells with length of at least 10 final = cell2mat(z); %// revert it back to an array 的数组。如果原始输入数组的形状不同,则应首先对其进行重新整形:

1xN

例如,如果您输入

v = input_array_of_arbitrary_size(:)'; %'// reshapes into row vector columnwise

结果将是:

in = [1 4 7
      2 5 8
      3 6 9];

这适用于任何维度的数组,并且会在每个维度的末尾追加每个维度。有关详细信息,请查看线性索引。