Split array into cell arrays of different size
2 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Honglei Chen
on 13 Nov 2017
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
More Answers (1)
the cyclist
on 13 Nov 2017
Edited: the cyclist
on 13 Nov 2017
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 Comments
See Also
Categories
Find more on Array Geometries and Analysis in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!