Clear Filters
Clear Filters

Split array into cell arrays of different size

2 views (last 30 days)
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?
Code taken from Source

Accepted Answer

Honglei Chen
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
  1 Comment
Tom Lichen
Tom Lichen on 13 Nov 2017
Edited: Tom Lichen on 13 Nov 2017
Well you might be right, but i'm not sure. This is my homework of Signal processing class that I'm taking. Basically I have a heart beat pulse wave (blue one) and another signal(red one) that shows where each individual pulse ends and begins. My task is to divide that huge signal ( close to 100k values) into individual pulses. Each pulse has 55-60 values. So I can't have just one value at the start by itself, nor can I have one at the end. This is just the way I decided to deal with this problem. Maybe I need to think about that "1" as the end of one pulse and as the start of another one at the same time? But then again, I have no idea how to implement this.

Sign in to comment.

More Answers (1)

the cyclist
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]))

Community Treasure Hunt

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

Start Hunting!