필터 지우기
필터 지우기

Finding the closest number to the average in an array

조회 수: 3 (최근 30일)
LEP
LEP 2015년 6월 1일
답변: Image Analyst 2015년 6월 1일
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.

답변 (1개)

Image Analyst
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);

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by