Finding the closest number to the average in an array

2 views (last 30 days)
The script should assume a vector A is assigned in the command window. The script should create a scalar x where x is the number in A that is closest to the average. Commands mean, median, mode, sum, max, or min are not allowed for this challenge.
This is the assignment I was given:
An example execution is as follows:
>> A = [-1 -0.5 0 1 4];
>> script24
x =
1
So far I figured out the calculation for the average but can you give me some hints on how to pick out the number closest? This is my script so far:
avg_value = 0
for ii = A
sum_value = avg_value + ii
end
avg_value_2 = sum_value / length(A)

Answers (1)

Image Analyst
Image Analyst on 29 May 2015
Do another loop where you find the min difference, and store where that's found.
for k = 1 : length(A)
difference = abs(A(k) - avg_value_2);
if difference < minDiffSoFar
minDiffSoFar = difference;
indexOfMin = k;
end
end
That's pretty close (it's just standard scanning of an array like any beginning computer programming course would have taught you), but I've left a little for you to do still.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!