[英]Filtering sequences in 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]
這些是不間斷的序列(沒有穿插)。
這可能嗎?
使用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)
您可以這樣做:
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
這可能是另一種方法,盡管有些過於詳盡。
如果看到陣列圖,則希望保留其拓撲連接 (即由一個片段組成)的級別集(即a == const
)。
一致地,這樣的水平集正是對應於a==3
和a==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
如果您嘗試類似
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 = [3 3 3 3 4 4 4]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.