Why is my function giving me the wrong output?

조회 수: 8 (최근 30일)
Kristen O'Mara
Kristen O'Mara 2018년 2월 21일
댓글: Stephen23 2018년 2월 21일
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
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.

댓글을 달려면 로그인하십시오.

답변 (2개)

Steven Lord
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.

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by