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

1 次查看(过去 30 天)
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 个评论
Vladimir
Vladimir 2023-9-7
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];

请先登录,再进行评论。

回答(1 个)

David Hill
David Hill 2023-9-5
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]}

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by