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