我有一个这样的 double 数组:
C = [1 2 3 4 0 3 2 5 6 7 1 2 3 4 150 30]
我想在数组中找到模式 [1 2 3 4],然后将 2 个值存储在该模式之后:
A = [1 2 3 4 0 3]
B = [1 2 3 4 150 30]
我可以找到这样的模式,但我不知道如何获取和存储前一个值之后的 2 个值。
在找到 A、B 之后,如果我想查找数组 C 中每个数组的出现次数,我该怎么做?
indices = cellfun(@(c) strfind(c,pattern), C, 'UniformOutput', false);
谢谢!
最佳答案
假设您对元胞数组输出没问题,这可以正常工作:
C = [1 2 3 4 0 3 2 5 6 7 1 2 3 4 150 30 42 1 2 3 4 0 3]
p = [1 2 3 4]
n = 2
% full patttern length - 1
dn = numel(p) + n - 1
%// find indices
ind = strfind(C,p)
%// pre check if pattern at end of array
if ind(end)+ dn > numel(C), k = -1; else k = 0; end
%// extracting
temp = arrayfun(@(x) C(x:x+dn), ind(1:end+k) , 'uni', 0)
%// post processing
[out, ~, idx] = unique(vertcat(temp{:}),'rows','stable')
occ = histcounts(idx).'
如果数组 C
在最后一次出现模式 p
之后以至少 n
元素结束,您可以使用短格式:
out = arrayfun(@(x) C(x:x+n+numel(p)-1), strfind(C,p) , 'uni', 0)
out =
1 2 3 4 0 3
1 2 3 4 150 30
occ =
2
1
关于arrays - 从数组中提取模式和后续的 n 个元素并计算出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44985837/