필터 지우기
필터 지우기

How to convert simple array to cell array with condition?

조회 수: 2 (최근 30일)
ANURAG DEEPAK
ANURAG DEEPAK 2022년 4월 10일
댓글: ANURAG DEEPAK 2022년 4월 10일
Respected Sir,
I want to convert the array of size( 1*37) into cell array with constraint i.e., whenever in the array 1 is encountered array should start from next cell.
For example:
I have a array:
pop = [1 28 25 15 13 17 1 31 27 8 14 22 18 1 21 6 26 11 16 23 10 19 1 7 4 3 24 29 12 9 1 2 32 20 5 30 1]
the output in form of cell array should be:

채택된 답변

Jan
Jan 2022년 4월 10일
편집: Jan 2022년 4월 10일
pop = [1 28 25 15 13 17 1 31 27 8 14 22 18 1 21 6 26 ...
11 16 23 10 19 1 7 4 3 24 29 12 9 1 2 32 20 5 30 1];
m = find(pop == 1);
n = numel(m) - 1;
C = cell(1, n);
for k = 1:n
C{k} = pop(m(k):m(k+1));
end
C
C = 1×5 cell array
{[1 28 25 15 13 17 1]} {[1 31 27 8 14 22 18 1]} {[1 21 6 26 11 16 23 10 19 1]} {[1 7 4 3 24 29 12 9 1]} {[1 2 32 20 5 30 1]}
Alterntaively:
C = splitapply(@(x) {x}, pop, cumsum(pop == 1));
But then the trailing 1 is missing and appendig it manually is a mess.
  댓글 수: 1
ANURAG DEEPAK
ANURAG DEEPAK 2022년 4월 10일
Thank you sir for timely response.
Yes sir, the altenative method is providing 1 in seperate cell.

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by