select several groups in a Vector

7 vues (au cours des 30 derniers jours)
hamed
hamed le 6 Sep 2017
Modifié(e) : hamed le 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 commentaire
Stephen23
Stephen23 le 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).

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 6 Sep 2017
Modifié(e) : Stephen23 le 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 commentaire
hamed
hamed le 6 Sep 2017
Modifié(e) : hamed le 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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by