フィルターのクリア

Why is my function giving me the wrong output?

6 ビュー (過去 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.
Stephen23
Stephen23 2018 年 2 月 21 日

サインインしてコメントする。

回答 (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 Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by