How to split array into sub arrays?

how to split principal vector "a" into sub vectors a1, a2, a3 and a4
exemple:
a=[1 3 5 8 11 12 15 17 18 19 20 21 24 29 31 32 33 34 35 36 38 39];
a1=[1 3 5 8];
a2=[11 12 15 17 18 19 20];
a3=[21 24 29];
a4=[31 32 33 34 35 36 38 39];
thnkx

3 comentarios

Stephen23
Stephen23 el 30 de En. de 2024
Editada: Stephen23 el 30 de En. de 2024
What is the rule for splitting into those vectors?
For example:
  • why is 20 in a2 and not in a3 ?
  • why is 21 in a3 and not in a2 ?
Note that creating numbered variables is not a good approach. Much better to use a cell array.
benghenia aek
benghenia aek el 30 de En. de 2024
I want to split the big array "a" into:
a1 "the numbers between 0 and 10"
a2 "the numbers between 11 and 20"
a3 "the numbers between 21 and 30"
and make it into cell arrays
Dyuman Joshi
Dyuman Joshi el 19 de Feb. de 2024
Any updates, @benghenia aek?

Iniciar sesión para comentar.

 Respuesta aceptada

Dyuman Joshi
Dyuman Joshi el 30 de En. de 2024
Editada: Dyuman Joshi el 19 de Feb. de 2024
a = [1 3 5 8 11 12 15 17 18 19 20 21 24 29 31 32 33 34 35 36 38 39 69].';
%bin the data into groups of 10
k = findgroups(floor((a-1)/10));
z = accumarray(k, a, [], @(x) {x.'})
z = 5×1 cell array
{[ 1 3 5 8]} {[ 11 12 15 17 18 19 20]} {[ 21 24 29]} {[31 32 33 34 35 36 38 39]} {[ 69]}

Más respuestas (1)

Matt J
Matt J el 30 de En. de 2024
Editada: Matt J el 19 de Feb. de 2024
a = [1 3 5 8 11 12 15 17 18 19 20 21 24 29 31 32 33 34 35 36 38 39];
G=findgroups(discretize(a,[0:10:max(a)+10],'Include','right'));
z=splitapply(@(x){x}, a, G)
z = 1x4 cell array
{[1 3 5 8]} {[11 12 15 17 18 19 20]} {[21 24 29]} {[31 32 33 34 35 36 38 39]}

2 comentarios

splitapply() won't work if there is a gap in the data -
a = [1 3 5 8 11 12 15 17 18 19 20 21 24 29 31 32 33 34 35 36 38 39 69];
G=discretize(a,[0:10:max(a)+10],'Include','right');
z=splitapply(@(x){x}, a, G)
Error using splitapply
For N groups, every integer between 1 and N must occur at least once in the vector of group numbers.
Small modification,
a = [1 3 5 8 11 12 15 17 18 19 20 21 24 29 31 32 33 34 35 36 38 39 69];
G=findgroups(discretize(a,[0:10:max(a)+10],'Include','right'));
z=splitapply(@(x){x}, a, G)
z = 1x5 cell array
{[1 3 5 8]} {[11 12 15 17 18 19 20]} {[21 24 29]} {[31 32 33 34 35 36 38 39]} {[69]}

Iniciar sesión para comentar.

Categorías

Más información sobre Operators and Elementary Operations en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 30 de En. de 2024

Editada:

el 19 de Feb. de 2024

Community Treasure Hunt

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

Start Hunting!

Translated by