Finding the closest number to the average in an array
1 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(1 个)
Image Analyst
2015-6-1
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);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!