Split array into cell arrays of different size
8 次查看(过去 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!
