Split array into cell arrays of different size
2 ビュー (過去 30 日間)
古いコメントを表示
I have an array A that I am trying to divide into different lengths arrays. To do so, I have another array B filled with 0 and 1. 1 tells me that this is the place I need to do my cut and this is the place where subarray has to end. Example
A=[1 2 4 5 8 3 4 6 7 3 3 5 7 8 8 2]
B=[1 0 0 0 1 0 0 1 0 0 1 0 0 0 0 1]
Expected_Result = {1 2 4 5 8} {3 4 6} {7 3 3} {5 7 8 8 2}
To do so, I'm using this code
Result = mat2cell( A, 1, diff( [find(B(1:end)==1), numel(B)+1] ));
This gives me sligthly wrong answer. It considers 1 as a start of a new array, not the end of the old one, and i'm getting this result:
Wrong_Result = {1 2 4 5} {8 3 4} {6 7 3} {3 5 7 8 8} {2}
Could you please help me with my problem?
0 件のコメント
採用された回答
Honglei Chen
2017 年 11 月 13 日
To do what you want, you can use the following lines, which is a slightly modified version of yours.
Bi = find(B==1)
Result = mat2cell( A, 1, Bi(2:end)-[0 Bi(2:end-1)]);
However, the issue is you are not interpreting the '1' in B consistently. Why is the first 1 grouped with the first cell, shouldn't it be by itself if the definition were consistent with others?
HTH
その他の回答 (1 件)
the cyclist
2017 年 11 月 13 日
編集済み: the cyclist
2017 年 11 月 13 日
Use this diff instead:
diff(find([B(1) 0 B(2:end)]))
I would say your definition of "B" is slightly inconsistent, in that the first occurrence of a "1" carries a different meaning than the other occurrences, because is does not signify the endpoint of an interval. So, a slightly more elegant approach would possible with
B = [0 0 0 0 1 0 0 1 0 0 1 0 0 0 0 1]
and then
diff(find([1 B]))
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Resizing and Reshaping Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
