TASK 1 OBJECTIVE: Use array manipulation to compute useful information. You shou
ID: 3682499 • Letter: T
Question
TASK 1
OBJECTIVE: Use array manipulation to compute useful information.
You should work on this task individually, but you may discuss results with your teammates.
The median of a finite list of numbers can be found by arranging all the observations from lowest value to highest value and picking the middle one (e.g., the median of {3, 3, 5, 9, 11} is 5). If there is an even number of observations, then there is no single middle value; the median is then usually defined to be the mean of the two middle values (the median of {3, 5, 7, 9} is (5 + 7) / 2 = 6).[1]
Write a script (task1.m) that finds the median of the 1-dimensional array A. You may not use the built-in median function. Your script should assume that A has already been defined. Thus your script should not ask the user to input anything. It should simply output the value of the median.
Example:
>> A = [8 6 7 5 3 0 9]
>> task1
The median is 6.
[1] https://en.wikipedia.org/wiki/Median
Explanation / Answer
clc %clearing the screen
clear %clearing any variables
A = [8 6 7 5 3 0 9]; % the 1-dimensional array
n = length(A); % getting the length of array
A = sort(A); % sorting array in ascending order
% if remainder is 1 that means there are odd number of observations
% otherwise number of observation is even
if rem(n,2)==1
median = A((n+1)/2); %the middle value
else
median = (A(n/2)+A((n/2)+1))/2; %mean of the two middle value
end
string = sprintf('The median is %s',num2str(median)); %string to display
disp(string) %displaying the string
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.