select several groups in a Vector

4 views (last 30 days)
hamed
hamed on 6 Sep 2017
Edited: hamed on 6 Sep 2017
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 Comment
Stephen23
Stephen23 on 6 Sep 2017
"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).

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 6 Sep 2017
Edited: Stephen23 on 6 Sep 2017
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 Comment
hamed
hamed on 6 Sep 2017
Edited: hamed on 6 Sep 2017
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

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!