select several groups in a Vector

조회 수: 7 (최근 30일)
hamed
hamed 2017년 9월 6일
편집: hamed 2017년 9월 6일
Hi all
I have a vector like this:
x=[0 0 0 1 1 1 0 0 1 1 0 1 1 1 0 0 0 0 1 1 1 1]
I'm trying to save each part of ones in a Row. for instance, the result of this vector should be a matrix with 4 rows.
1th row = 1 1 1
2th row = 1 1
3rd row = 1 1 1
4th row = 1 1 1 1
how can I do that automatically with a loop.
could you please help me.
Cheers
  댓글 수: 1
Stephen23
Stephen23 2017년 9월 6일
"the result of this vector should be a matrix with 4 rows."
That is impossible, as all rows of a matrix must have the same number of elements. Instead you could:
  • store the vectors in a cell array.
  • pad each vector with some value (e.g. see padcat).

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

채택된 답변

Stephen23
Stephen23 2017년 9월 6일
편집: Stephen23 2017년 9월 6일
Method one: diff and arrayfun:
>> x = [0 0 0 1 1 1 0 0 1 1 0 1 1 1 0 0 0 0 1 1 1 1];
>> d = diff([0,x,0]);
>> C = arrayfun(@(b,e)x(b:e-1),find(d>0),find(d<0),'uni',0);
>> C{:}
ans =
1 1 1
ans =
1 1
ans =
1 1 1
ans =
1 1 1 1
Method two: regexp and cellfun:
>> C = regexp(char(x),sprintf('\1+'),'match');
>> C = cellfun(@double,C,'uni',0);
>> C{:}
ans =
1 1 1
ans =
1 1
ans =
1 1 1
ans =
1 1 1 1
  댓글 수: 1
hamed
hamed 2017년 9월 6일
편집: hamed 2017년 9월 6일
Thanks a lot Stephen
The code that you sent me works perfectly. Actually, I have a vector of the numbers like the following vector:
X=[NaN NaN 2.66 3.12 1.03 NaN NaN NaN -2.66 1.32 -0.14 NaN 3.55 -0.25]);
For this vector, I should categorize indexes of each group of numbers separately in a vector for example:
Z(1,:)= [3 4 5]
Z(2,:)= [9 10 11]
Z(3,:)= [13 14]
I'd like to make a code to search on the vector and find the indexes of continuous numbers, each zero or NaN cuts the chain of numbers and the first next group should categorize in the next row. I've tried to solve this problem with your code but I can't.
Best Regards,
Hamed

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by