Matlab

Median in MATLAB

In data analysis and statistics, the median is a fundamental measure that provides insights into the central tendency of a dataset. MATLAB, a powerful programming language, and environment, offers a comprehensive set of functions to perform statistical calculations efficiently. In this article, we will explore the median function in MATLAB, examining its syntax and presenting multiple examples to demonstrate its practical usage.

Median in MATLAB

The median in MATLAB is a statistical measure that depicts a dataset’s middle value. It is significant because it provides a robust measure of central tendency, making it less sensitive to outliers compared to the mean, and is particularly useful for summarizing skewed or non-normal distributions. The median function in MATLAB calculates the median of a dataset. Its syntax is as follows:

M = median(X)

Here, X represents the input data, and M stores the calculated median value, and for a deeper understanding of this function in MATLAB below are some examples have been given:

Example 1: Computing the Median of a Numeric Vector

data = [8, 4, 12, 6, 10];

result = median(data);

disp(result);

In this example, we have numeric vector data representing a dataset. By applying the median function, we compute the median of the vector and store it in the variable result.

Example 2: Computing the Median of a Matrix Column

matrix = [1, 4, 7; 2, 5, 8; 3, 6, 9];

result = median(matrix(:, 2));

disp(result);

In this example, we have a matrix with three columns. To compute the median of a specific column, we use the (:) operator to select all rows and specify the desired column index.

A picture containing text, line, screenshot Description automatically generated

Example 3: Handling Missing or NaN Values

data = [7, 2, NaN, 9, 5];

result = median(data, 'omitnan');

disp(result);

In this example, we have vector data that contains a missing value represented by NaN (Not-a-Number). By providing the omitnan option to the median function, MATLAB handles the missing value appropriately and computes the median without considering the NaN value.

A picture containing screenshot, text, line Description automatically generated

Conclusion

The median function in MATLAB provides a valuable tool for calculating the central tendency of datasets. By applying the appropriate syntax, you can easily compute the median of numeric vectors, and matrix columns, or handle missing values using the omitnan option.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.