在MATLAB中过滤序列

时间:2013-05-21 18:27:37

标签: matlab

是否可以使用MATLAB执行类似正则表达式的操作来过滤掉事情?基本上我正在寻找一些可以让我采用矢量的东西:

[1 2 1 1 1 2 1 3 3 3 3 1 1 4 4 4 1 1]

并将返回:

[3 3 3 3 4 4 4]

这些是不间断的序列(没有散布的地方)。

这可能吗?

4 个答案:

答案 0 :(得分:1)

使用正则表达式

使用MATLAB的内置regexp函数进行正则表达式匹配。但是,您必须先将输入数组转换为字符串,然后才将其提供给regexp

C = regexp(sprintf('%d ', x), '(.+ )(\1)+', 'match')

请注意,我将值与空格分开,以便regexp也可以匹配多个数字。然后将结果转换回数值数组:

res = str2num([C{:}])

模式字符串中的点(.)表示任何字符。要仅查找某些数字的序列,请在括号中指定它们([])。例如,仅查找3和4序列的模式将是:

([34]+ )(\1)+

更简单的方法

您可以使用diff

检查相邻元素之间的相似性,从而过滤掉连续重复的值
res = x((diff([NaN; x(:)])' == 0) | (diff([x(:); NaN])' == 0))

或者,您可以仅保留结果中的某些值,例如:

res(res == 3 | res == 4)

答案 1 :(得分:0)

你可以这样做:

v=[1 2 1 1 1 2 1 3 3 3 3 1 1 4 4 4 1 1];
vals=unique(v); % find all unique values in the vector

mask=[]; % mask of values to retain

for i=1:length(vals)
   indices=find(v==vals(i)); % find indices of each unique value

   % if the maximum difference between indices containing
   % a given value is 1, it is contiguous
   % --> add this value to the mask
   if max(indices(2:end)-indices(1:end-1))==1
       mask=[mask vals(i)];
   end
end

% filter out what's necessary
vproc=v(ismember(v,mask))

结果:

vproc =

     3     3     3     3     4     4     4

答案 2 :(得分:0)

这可能是另一种方法,虽然有点过于精细化。

如果您看到数组的图,您希望保留其拓扑连接(即由一个部分制作)的级别集(即a == const)。

相关地,此类级别集恰好与a==3a==4对应的级别集。

这是一个可能的实现

a = [1 2 1 1 1 2 1 3 3 3 3 1 1 4 4 4 1 1]

r = [];  % result
b = a;   % b will contain the union of the level sets not parsed yet
while ~isempty(b)

    m = a == b(1);  % m is the current level set

    connected = sum(diff([0 m 0]).^2) == 2;  % a condition for being a connected set:
                                             % the derivative must have 1 positive and 1
                                             % negative jump
    if connected == true   % if the level set is connected we add it to the result 
        r = [r a(m)];          
    end

    b = b(b~=b(1));

end

答案 3 :(得分:-1)

如果您尝试类似

的话
a = [1 2 1 1 1 2 1 3 3 3 3 1 1 4 4 4 1 1]    %initial vector
b = a>=3   %apply filter condition

a = a(b)   %keep values that satisfy filter

a将输出

a = [3 3 3 3 4 4 4]
相关问题