Why is my function giving me the wrong output?
8 次查看(过去 30 天)
显示 更早的评论
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 个评论
Star Strider
2018-2-21
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
2018-2-21
See also the earlier question:
回答(2 个)
Steven Lord
2018-2-21
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!