Can you help me create a function according to mathematical formula?

1 visualización (últimos 30 días)
Vladimir
Vladimir el 5 de Sept. de 2023
Editada: Vladimir el 7 de Sept. de 2023
Hello,
I am trying to create a function that will work as described below:
n = 4; %this is my input, describe how many number i will have in matrix A, but it can be any value up to 128.
A = [1, 2, 10, 16]; %input, which numbers I want to have in matrix, can be any number.
I want to divide input into 4 groups:
g1 = [];
g2 = [];
g3 = [];
g4 = [];
I want to divide it by following formula: B = sum(A) ./ n;
Which will do sum of A and divide it by n, then each value of A will be compared by B and in case " value of A < B", add this value to g1.
For example for group 1:
g1:
B = sum(A) ./ n
B = (1+2+10+16)/4
B = 7,25
Now I will compare each value of A: A(i) < B
1 < 7,25
2 < 7,25
so in this case
g1 = [1, 2];
Will do same steps for group 2 but n = 2 (because 2 numbers are already in group) and A = [10, 16]
g2:
B = sum(A) ./ n
B = (10+16)/2
B = 13
Now I will compare each value of A: A(i) < B
10 < 13
so in this case
g2 = [10];
Last step will be the same as for group 2 but if "A(i)<B" add value of A to group 3 and if "A(i) >= B" add value to group 4.
So in this case:
B = sum(A) ./ n
B = (16)/1
B = 16
16 = 16
g3 = [];
g4 = [16];
I want output to display value of each group:
In this case:
g1 = [1, 2];
g2 = [10];
g3 = [];
g4 = [16];
Thanks for any advices and tips.
  2 comentarios
Voss
Voss el 5 de Sept. de 2023
Do you always want to end up with 4 groups, regardless of the value of n?
Vladimir
Vladimir el 7 de Sept. de 2023
Yes, I always want to have 4 groups. For example:
If the input is 4 same numbers:
A = [10, 10, 10, 10]
I want to outcome to be:
g1 = [];
g2 = [];
g3 = [];
g4 = [10, 10, 10, 10];

Iniciar sesión para comentar.

Respuestas (1)

David Hill
David Hill el 5 de Sept. de 2023
A=randi(128,1,20)
A = 1×20
95 39 8 114 113 87 77 105 54 128 16 114 118 13 72 28 36 97 15 40
for k=1:3
B=sum(A)/numel(A);
idx=A<B;
g{k}=A(idx);
A(idx)=[];
end
g{4}=A;
g
g = 1×4 cell array
{[39 8 54 16 13 28 36 15 40]} {[95 87 77 72 97]} {[114 113 105 114]} {[128 118]}

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by