Split array into cell arrays of different size
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Tom Lichen
el 13 de Nov. de 2017
Editada: Tom Lichen
el 13 de Nov. de 2017
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 comentarios
Respuesta aceptada
Honglei Chen
el 13 de Nov. de 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 comentario
Más respuestas (1)
the cyclist
el 13 de Nov. de 2017
Editada: the cyclist
el 13 de Nov. de 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 comentarios
Ver también
Categorías
Más información sobre Resizing and Reshaping Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!