median of grouped frequency data

조회 수: 2 (최근 30일)
N/A
N/A 2024년 6월 10일
댓글: N/A 2024년 6월 13일
Given the data below
calculate the median of the data in MATLAB
I have the code below
class_intervals = [420 430; 430 440; 440 450; 450 460; 460 470; 470 480; 480 490; 490 500];
frequencies = [336, 2112, 2336, 1074, 1553, 1336, 736, 85];
% Calculate the cumulative frequencies
cum_frequencies = cumsum(frequencies)
% Calculate the total number of observations
N = sum(frequencies);
% Find the median class (where cumulative frequency exceeds N/2)
median_class_index = find(cum_frequencies >= N/2, 1)
% Extract the lower boundary, frequency, and cumulative frequency of the class before the median class
L = class_intervals(median_class_index, 1) % lower boundary of the median class
f = frequencies(median_class_index) % frequency of the median class
if median_class_index == 1
cf = 0; % cumulative frequency before the median class
else
cf = cum_frequencies(median_class_index - 1) % cumulative frequency before the median class
end
% Calculate the width of the median class interval
h = class_intervals(median_class_index, 2) - class_intervals(median_class_index, 1)
% Calculate the median using the formula
median = L + ((N/2 - cf) / f) * h
However I was wondering if instead of calculating it manually is there any inbuilt function in MATLAB to calculate median of grouped data.

답변 (1개)

Anurag Ojha
Anurag Ojha 2024년 6월 11일
Hi Nafisa
You can use 'grpstats' function in order to calculate median of a grouped data. Adding a pseudo code:
% Create a table with the class intervals and frequencies
data = table(class_intervals, frequencies, 'VariableNames', {'ClassIntervals', 'Frequencies'});
% Calculate the median using grpstats
median_data = grpstats(data, [], 'median', 'DataVars', 'ClassIntervals');
% Extract the median values
median_values = median_data.median_ClassIntervals;
% Display the median values
disp(median_values)
There is also a inbuilt 'Median' function that you can use to caluclate median.
data = [10, 20, 30, 40, 50];
median_value = median(data);
disp(median_value);
30
Adding documentation link for your reference:
  댓글 수: 5
Anurag Ojha
Anurag Ojha 2024년 6월 13일
편집: Anurag Ojha 2024년 6월 13일
Hi Nafisa
I am not getting this error at my end when I execute the provided code. Can you please provide the exact code that you are executing which results in this error.
N/A
N/A 2024년 6월 13일
Hello Anurag, it is working however when i try to use the same code in another example it gives me a wrong answer. So I tried using this example
I get the answer 27.5 using your code. However the real answer is 25.25

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

카테고리

Help CenterFile Exchange에서 Measurements and Spatial Audio에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by