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.
An example execution is as follows:
>> A = [-1 -0.5 0 1 4];
>> script24_drew_Murray
x =
1
I tried doing the problem using the following script...
total = 0;
for jj = length(A);
for ii = A;
total = (total + ii);
end
A_avg = total/jj;
end
for kk = 1:length(A);
diffr = abs(A(kk) - A_avg);
sortedA = sort(A);
mindiff = abs(sortedA(2)-sortedA(1));
if diffr < mindiff;
x = A(kk)
end
end
This worked for the example given. But I tried running the script with a different array A = [-4 -0.5 1 200] and no result was produced from the script. I am not sure why it works for some arrays and not for others.

Answers (1)

Image Analyst
Image Analyst on 1 Jun 2015
Pretty close, but try it this way:
A = [-4 -0.5 1 200]
% First find the total
total = 0;
for ii = A;
total = total + ii;
end
% Now find the mean.
A_avg = total/length(A);
% Now find out the delta to the mean.
diffr = abs(A - A_avg)
% Now scan to find which delta is smallest.
minDiff = inf;
for kk = 1:length(diffr);
if diffr(kk) < minDiff;
x = A(kk);
minDiff = diffr(kk);
end
end
fprintf('%.1f is closest to the mean of %.4f\n', ...
x, A_avg);

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!