Finding the closest number to the average in an array
    4 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
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)
0 comentarios
Respuestas (1)
  Image Analyst
      
      
 el 29 de Mayo de 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.
0 comentarios
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

