Extract the pattern and subsequent n elements from the array and count the number of occurrences
I have an array of doubles like this:
C = [1 2 3 4 0 3 2 5 6 7 1 2 3 4 150 30]
I want to find pattern [1 2 3 4] in an array and then store 2 values after that pattern with it like:
A = [1 2 3 4 0 3]
B = [1 2 3 4 150 30]
I can find a pattern like this, but I don't know how to get and store 2 values after that with the previous one.
And after finding A, B, if I want to find the number of occurrences of each array in array C, how can I do that?
indices = cellfun(@(c) strfind(c,pattern), C, 'UniformOutput', false);
Thank!
+3
source to share
2 answers
Assuming you're fine with the output of the cell array, this works great:
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).'
If the array C
ends with at least n
elements after the last occurrence of the pattern p
, you can use the short form:
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
+3
source to share
A simple solution might be:
C = [1 2 3 4 0 3 2 5 6 7 1 2 3 4 150 30]; pattern = [1 2 3 4]; numberOfAddition = 2; outputs = zeros(length(A),length(pattern)+ numberOfAddition); % preallocation numberOfFoundPattern = 1; lengthOfConsider = length(C) - length(pattern) - numberOfAddition; for i = 1:lengthOfConsider if(sum(C(i:i+length(pattern)) - pattern) == 0) % find pattern outputs(numberOfFoundPattern,:) = C(i:i+length(pattern)+numberOfAddition); numberOfFoundPattern = numberOfFoundPattern + 1; end end outputs = outputs(1:numberOfFoundPattern - 1,:);
0
source to share