select several groups in a Vector

7 Ansichten (letzte 30 Tage)
hamed
hamed am 6 Sep. 2017
Bearbeitet: hamed am 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 Kommentar
Stephen23
Stephen23 am 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).

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 6 Sep. 2017
Bearbeitet: Stephen23 am 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 Kommentar
hamed
hamed am 6 Sep. 2017
Bearbeitet: hamed am 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by