search through an array for patterns and put into cell arrays.

조회 수: 3 (최근 30일)
lightroman
lightroman 2017년 11월 14일
답변: Kelly Kearney 2017년 11월 14일
Looking to search through a large array of integers and find patterns of up to 1-10 ( can be 1 or 1 2 3 or 1 2 3 4 5 6 .. 10, etc) and place those into cell arrays. Resulting multiple cell arrays of different lengths. A is really long so I was hoping to avoid lengthy loops, in which I figured out a way using ismember and a very very long inefficient loop.
I do not know how many patterns of 1-10 exist. Is this possible? Thanks.
if true
A = [ 1 2 3 78 28 92 1 76 89 23 87 1 2 3 4 5 6 7 8 9 10 72 91 72]
result{1} = {1 2 3}
result{2} = {1}
result{3} = {1 2 3 4 5 6 7 8 9 10}
end

채택된 답변

Kelly Kearney
Kelly Kearney 2017년 11월 14일
This sort of problem can usually be solved by using a various combinations of diff:
A = [ 1 2 3 78 28 92 1 76 89 90 23 87 1 2 3 4 5 6 7 8 9 10 72 91 72];
(I modified your example by one element to add a run that didn't start with 1, just in case...)
isnew = [true ~(diff(A) == 1)]; % is each elemet 1 greater than previous?
sidx = find(isnew); % indices of start of each run
nper = diff([sidx length(A)+1]); % number of elements in each run
is1 = A(sidx) == 1; % does run start with 1?
consec = mat2cell(A, 1, nper); % break matrix into cells of runs
consec1 = consec(is1); % keep only cells starting with 1
Result:
>> consec1{:}
ans =
1 2 3
ans =
1
ans =
1 2 3 4 5 6 7 8 9 10

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by