Split an array according to a logic

조회 수: 17 (최근 30일)
TV8
TV8 2021년 11월 1일
편집: Jon 2021년 11월 1일
Is there a way to split a vector ,
say;
[1 2 3 6 7 8 12 13 14 15 ] ....( the actual vector is much longer )
into preassigned groups or cells such that cosecutive numbers
{1 2 3 } { 6 7 8} {12 13 14 15} .... are grouped in different cells.
Thanks a ton.

채택된 답변

Jon
Jon 2021년 11월 1일
편집: Jon 2021년 11월 1일
If the numbers are ordered as you show them you can just use reshape() to make them into a m by 3 array. If you really need it to be a cell you can convert that using mat2cell
So for example
x = 1:30
X = reshape(x,10,3)
Xcell = mat2cell(X,ones(10,1))
  댓글 수: 9
Jon
Jon 2021년 11월 1일
Oh, I see, I don't catch the last element in each group. I have to think about how to fix that.
Jon
Jon 2021년 11월 1일
편집: Jon 2021년 11월 1일
I think this now catches the end of each consecutive group too. Most of the logic is the same, but I realized you have to look forward and backward to see if they are consecutive and not miss the ends of the groups
% example vector containing groups of consectutive numbers
x = [1 2 3 6 7 8 12 13 14 15 18 19 20 31 35 36 40 41];
% elements are consecutive if they the next element is one larger than they
% are
idlFwd = [diff(x)== 1 0];
% elements are also consecutive if the one before them is one less than they are
idlBwd = [0 flip(diff(flip(x))== -1)]
% elements are consecutive if either criteria is met
idl = idlFwd|idlBwd;
% mark where beginning of each group of consecutive elements occurs, these
% are jumps from 0 to 1
iStart = diff([0 idlFwd])==1;
% count up jumps to form group numbers
groupCount = cumsum(iStart);
% assign group number, but only to ones that belong to a group (the
% consecutive values)
% (for non-members groupCount.*idl is zero so these are assigned to group
% zero)
group = groupCount.*idl ;
% loop through to assign to cell array by group
numGroups = max(group);
X = cell(numGroups,1);
for k = 1:numGroups
X{k} = x(k==group);
end
disp(X)
1 2 3 6 7 8 12 13 14 15 18 19 20 31 35 36 40 41
{[ 1 2 3]}
{[ 6 7 8]}
{[12 13 14 15]}
{[ 18 19 20]}
{[ 35 36]}
{[ 40 41]}

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by