Split Number into digits adding up to it.

I need to split a number into smaller integers that add up to it.
So 4 -> [0,4],[1,3],[2,2],[3,1],[4,0]
6 -> [0,6],[1,5],[2,4],[3,3]...
I know this can be done with for loops but wanted to see if there is another way.

2 comentarios

Stephen23
Stephen23 el 10 de Sept. de 2020
Editada: Stephen23 el 10 de Sept. de 2020
"I need to split a number into smaller integers that add up to it. So 4 -> [0,4],[1,3],[2,2],[3,1],[4,0]"
What about [1,1,1,1],[1,1,2],[1,2,1],[2,1,1],etc., and [4]?
How many zeros are allowed? What about [0,0,0,4], [0,0,2,2], etc.?
Alberto Lorenzo
Alberto Lorenzo el 14 de Sept. de 2020
This is to simulate aircrafts in a collision paths so zeros and ones would not make sense. Also I have a maximum of 3 vehicles per encounters so I have some extra steps to only consider valid sets. So the only choice for 4 would be [2,2], 6 would have [2,2,2] or [3,3] where each values is the number of vehicles per encounter.

Iniciar sesión para comentar.

 Respuesta aceptada

Ameer Hamza
Ameer Hamza el 10 de Sept. de 2020
What about
f = @(n) [0:n; n:-1:0].';
Result
>> f(4)
ans =
0 4
1 3
2 2
3 1
4 0
>> f(6)
ans =
0 6
1 5
2 4
3 3
4 2
5 1
6 0

2 comentarios

Alberto Lorenzo
Alberto Lorenzo el 14 de Sept. de 2020
Vary clean and simple. Worked great!
Ameer Hamza
Ameer Hamza el 15 de Sept. de 2020
I am glad to be of help!

Iniciar sesión para comentar.

Más respuestas (1)

KSSV
KSSV el 10 de Sept. de 2020
n = 4 ;
[X,Y] = meshgrid(0:n,0:n) ;
thesum = X+Y ;
idx = thesum==n ;
iwant = [X(idx) Y(idx)]
n = 6 ;
[X,Y] = meshgrid(0:n,0:n) ;
thesum = X+Y ;
idx = thesum==n ;
iwant = [X(idx) Y(idx)]

Categorías

Más información sobre App Building en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 10 de Sept. de 2020

Comentada:

el 15 de Sept. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by