Why is my function giving me the wrong output?
8 views (last 30 days)
Show older comments
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 Comments
Star Strider
on 21 Feb 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.
Stephen23
on 21 Feb 2018
See also the earlier question:
Answers (2)
Steven Lord
on 21 Feb 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.
0 Comments
See Also
Categories
Find more on Shifting and Sorting Matrices 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!