How to find the closest value to the average in an array?
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Tawsif Mostafiz
el 15 de Abr. de 2022
Respondida: KSSV
el 15 de Abr. de 2022
I get a different one dimentional array for different inputs. Now, I want to take the average value of the array, and find the value that is closest to it.
For example if the array output is like this:
a = [1,2,3,4,5,6,7]
Then average will be 4.14, which is closest to 4.
So, the answer should be 4.
How can I do it?
0 comentarios
Respuesta aceptada
KSSV
el 15 de Abr. de 2022
a = [1,2,3,4,5,6,7] ;
[val,idx] = min(abs(a-mean(a)));
a(idx)
0 comentarios
Más respuestas (2)
Arif Hoq
el 15 de Abr. de 2022
Then average will be 4.14, which is closest to 4.
actually average is 4. you can try this:
a=[1,2,3,4,6,6];
average=mean(a)
[~,~,idx]=unique(round(abs(a-average)));
nearest_value=a(idx==1)
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements 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!