フィルターのクリア

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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by