在Matlab/Octave中从向量中识别(和删除)序列 [英] Identifying (and removing) sequences from a vector in Matlab/Octave

查看:97
本文介绍了在Matlab/Octave中从向量中识别(和删除)序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Matlab(或Octave)中的数字向量中修剪长度为3或更大的任何序列.例如,给定向量 dataSet

I'm trying to prune any sequence of length 3 or more from a vector of numbers in Matlab (or Octave). For example, given the vector dataSet,

dataSet = [1 2 3 7 9 11 13 17 18 19 20 22 24 25 26 28 30 31];

删除所有长度为3或更大的序列将产生prunedDataSet:

removing all sequences of length 3 or more would yield prunedDataSet:

prunedDataSet = [7 9 11 13 22 28 30 31 ];

我可以蛮力解决一个问题,但是我怀疑使用向量/矩阵操作有一种更简洁(也许更有效)的方法,但是我总是对某个东西是产生索引还是该索引的值感到困惑.有建议吗?

I can brute force a solution, but I suspect there is a more succinct (and perhaps efficient) way to do it using vector/matrix operations, but I always get confused about whether something yields an index or the value at said index. Suggestions?

这是我想出的蛮力方法:

Here's the brute force method I came up with:

dataSet = [1 2 3 7 9 11 13 17 18 19 20 22 24 25 26 28 30 31];
benign = [];
for i = 1:size(dataSet,2)-2;
    if (dataSet(i) == (dataSet(i+1)-1) && dataSet(i) == dataSet(i+2)-2);
        benign = [benign i ] ;
    end;
end;

remove = [];
for i = 1:size(benign,2);
    remove = [remove benign(i) benign(i)+1 benign(i)+2 ];
end;

remove = unique(remove);

prunedDataSet = setdiff(dataSet, dataSet(remove));

推荐答案

以下是使用 STRFIND

%# define dataset
dataSet = [1 2 3 7 9 11 13 17 18 19 20 22 24 25 26 28 30 31];

%# take the difference. Whatever is part of a sequence will have difference 1
dds = diff(dataSet);

%# sequences of 3 lead to two consecutive ones. Sequences of 4 are like two sequences of 3
seqIdx = findstr(dds,[1 1]);

%# remove start, start+1, start+2
dataSet(bsxfun(@plus,seqIdx,[0;1;2])) = []
dataSet =

     7     9    11    13    22    28    30    31

这篇关于在Matlab/Octave中从向量中识别(和删除)序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆