How to find the closest value to the average in an array?

조회 수: 5 (최근 30일)
Tawsif Mostafiz
Tawsif Mostafiz 2022년 4월 15일
답변: KSSV 2022년 4월 15일
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?

채택된 답변

KSSV
KSSV 2022년 4월 15일
a = [1,2,3,4,5,6,7] ;
[val,idx] = min(abs(a-mean(a)));
a(idx)
ans = 4

추가 답변 (2개)

KSSV
KSSV 2022년 4월 15일
a = [1,2,3,4,5,6,7] ;
idx = knnsearch(a',mean(a)) ;
a(idx)
ans = 4

Arif Hoq
Arif Hoq 2022년 4월 15일
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)
average = 3.6667
[~,~,idx]=unique(round(abs(a-average)));
nearest_value=a(idx==1)
nearest_value = 4

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by