Borrar filtros
Borrar filtros

Why is my function giving me the wrong output?

9 visualizaciones (últimos 30 días)
Kristen O'Mara
Kristen O'Mara el 21 de Feb. de 2018
Comentada: Stephen23 el 21 de Feb. de 2018
I was asked to write a function finding median and mean of an array without using the built in functions or the sum function. I think my code is very close to being correct, however I am confused as to why it is giving me the output zero when it should be giving me a 3. The array I tested it with was [5 8 9 1 0 2 3 1 9]. I then tried to sort it in ascending order and index it to find the median value. When I hover the cursor over the line
medianValue = sortedArray(medianIndex);
it shows the array as sorted. So basically, I don't know why my medianValue = 0 when it should equal 3. I think that part of my function is correct because it should be indexing the sorted array at the value for medianIndex, which is 5. So it should be returning the value 3.
function [meanValue, medianValue] = statsFunction(array)
%function to calculate median and mode values of an array
sortedArray = sort(array, 'ascend');
numElements = numel(sortedArray);
if mod(numElements, 2) ~= 0
medianIndex = (numElements+1)/2;
medianValue = sortedArray(medianIndex);
else
medianIndex1 = numElements/2;
medianIndex2 = (numElements+1)/2;
medianValue = (medianIndex1 + medianIndex2) / numElements;
end
sumx = 0;
k = 1;
while k <= length(array)
sumx = sumx + array(k);
k = k+1;
end
meanValue = sumx/(length(array));
  2 comentarios
Star Strider
Star Strider el 21 de Feb. de 2018
When I run the if block in your code, it gives the correct result for the median. I cannot reproduce the error you report.

Iniciar sesión para comentar.

Respuestas (2)

Steven Lord
Steven Lord el 21 de Feb. de 2018
Are you sure that this is failing for an odd length input array and not an even length input array? The else branch of your if statement doesn't index into sortedArray at all, while the if branch does.

Kristen O'Mara
Kristen O'Mara el 21 de Feb. de 2018
Thanks everyone, I fixed the issue. I needed to change the line medianValue to
medianValue = (array(medianIndex1) + array(medianIndex2))/2;

Categorías

Más información sobre Data Types en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by