Please include an example function call and the resulting output values from you
ID: 3593098 • Letter: P
Question
Please include an example function call and the resulting output values from your function in your comments. Write a function that has one input, array1, and two outputs output, medianValue and meanValue. These outputs are as follows:
- medianValue is the median of the numbers in your array. The median is the number in the array that has exactly the same number of values that are greater than or equal to it as it has values that are less than or equal to it. In an array with an odd number of indices, this is a value from the array itself. In an array with an even number of indices, this is the average of the two middle values in the array. For example, for the array [5 8 9 1 0 2 3 1 9], the median is [0 1 1 2 3 5 8 9 9] 3. For the array [10 2 11 3 12 4], the median is [2 3 4 10 11 12] (4+10)/2 = 7. Note that the numbers before and after the median can be the same as the median. The median of [1 2 2 2 2 2 2 2 2 2 3] is [1 2 2 2 2 2 2 2 2 2 3] 2.
- meanValue is the average of all of the numbers in the array.
You should use a loop or multiple loops to find both of these, and you should NOT call either of the following built-in MATLAB functions:
- mean
- median
- sum .
Other functions, like sort and length are allowed, and may be useful to you.
Explanation / Answer
PLEASE CREATE FILE mean_median.m AND PASTE BELOW CODE
function [Mean,Median] = mean_median(array1)
sum = 0;
%calculating sum of the array
for i=1:length(array1)
sum = sum + array1(i);
end
%mean = sum / length of an array
Mean = sum / length(array1);
%sorting array1
x = sort(array1);
%checking array length is even or odd
array_length = mod(length(x), 2);
%if array lenght is odd then median is element of array @array_length + 1
%otherwise sum of array elements @array_length/2 and array_length/2 + 1
%divide by 2
if array_length ~= 0
Median = x(ceil(length(x) / 2));
else
Median = x((length(x) / 2)) + x((length(x) / 2) + 1);
Median = Median / 2;
end
PLEASE CREATE test.m AND PASTE BELOW CODE
close all
clear all
clc
[Mean,Median] = mean_median([5 8 9 1 0 2 3 1 9])
[Mean,Median] = mean_median([2 3 4 10 11 12])
[Mean,Median] = mean_median([1 2 2 2 2 2 2 2 2 2 3])
PLEASE REFER BELOW OUTPUT
Mean =
4.2222
Median =
3
Mean =
7
Median =
7
Mean =
2
Median =
2
>>