How to Use MATLAB for Statistical Analysis

Learn how to use MATLAB for statistical analysis, from data cleaning and descriptive statistics to hypothesis testing, ANOVA, correlation, and regression.

When I first approach a statistical problem in MATLAB, I try not to start with a test or a formula. I start with a much simpler question: What am I actually trying to find out from this data?

That mindset makes MATLAB much easier to use. The software can calculate means, correlations, confidence intervals, hypothesis tests, ANOVA results, regression models, and much more. But knowing which function to run is only part of statistical analysis. You also need to understand your data, choose a method that fits the question, check its assumptions, and explain what the results mean.

In this guide, I'll show you a practical way to use MATLAB for statistical analysis, starting with a raw dataset and ending with an interpretable result.

What Can MATLAB Do for Statistical Analysis?

MATLAB is particularly useful when statistical analysis involves a mixture of numerical calculations, data preparation, visualisation, and modelling.

With the Statistics and Machine Learning Toolbox, you can work with descriptive statistics, probability distributions, hypothesis tests, ANOVA, regression, classification, clustering, and exploratory data analysis. MATLAB also provides interactive apps for several tasks, which can be helpful if you're still getting comfortable with statistical programming.

What I like about this setup is that the analysis can stay in one workflow. I can import a dataset, clean it, inspect it visually, perform calculations, fit a model, and save the code rather than manually moving results between several programs.

For most projects, I'd approach the analysis in this order:

  1. Import the data.
  2. Check and clean it.
  3. Explore the variables.
  4. Calculate descriptive statistics.
  5. Visualise important patterns.
  6. Choose the appropriate statistical method.
  7. Check the assumptions.
  8. Interpret and report the findings.
  9. Save the analysis so it can be reproduced.

The order matters. A statistical test applied to poorly understood data can give you a perfectly calculated answer to the wrong question.

1. Import Your Dataset into MATLAB

The first practical step is getting your data into a format MATLAB can work with.

For a CSV file, readtable is often a convenient option:

data = readtable("study_data.csv");

A table is particularly useful when your dataset contains several types of variables. For example, you might have age and income as numerical variables, department as a categorical variable, and a date column representing when an observation was recorded.

After importing the data, don't immediately run a statistical test. Take a look at it first:

head(data)summary(data)

This small check can uncover surprisingly large problems. You may find that a numerical column has been imported as text, category labels aren't consistent, or some observations are missing.

The official  provides details on importing and working with different data sources.

2. Clean the Data Before Analysing It

Data cleaning isn't the most exciting part of statistical work, but it can have a bigger effect on your final result than the statistical test itself.

Look for missing values, duplicated records, impossible measurements, inconsistent category names, and obvious data-entry errors.

For example, if your CSV file represents missing observations with NA, you can account for that during import:

data = readtable("study_data.csv", ... "TreatAsMissing", "NA");

MATLAB's Statistics and Machine Learning Toolbox accepts several data types, including numeric arrays, strings, logical values, and categorical variables. Choosing appropriate data types makes later analysis much less awkward.

One thing I would avoid is automatically deleting anything that looks unusual.

An outlier might be an error, but it might also be a genuine observation. Before removing one, I would check the original source and ask whether there is a sensible reason for the value.

The same caution applies to missing data. Removing incomplete observations may be appropriate in some analyses, but in others it can introduce bias. Your approach should depend on why the data is missing and what analysis you intend to perform.

3. Start With Descriptive Statistics

Once the dataset is in reasonable shape, describe it before trying to make statistical claims about it.

For a numerical variable, the mean, median, and standard deviation are useful starting points:

scores = data.Score;meanScore = mean(scores, "omitnan");medianScore = median(scores, "omitnan");stdScore = std(scores, "omitnan");

MATLAB includes functions for measures such as the mean, median, mode, standard deviation, skewness, kurtosis, percentiles, covariance, and correlation.

These numbers answer different questions.

The mean gives you the average. The median tells you where the middle observation sits. The standard deviation gives you an indication of how spread out the observations are.

Imagine two classes both have an average examination score of 70. That sounds similar until you discover that one class has scores tightly grouped around 70 while the other ranges from 35 to 98.

The average alone would hide that difference.

4. Use MATLAB to Visualise the Data

I would rarely rely on numerical summaries alone. A graph can reveal something that a table of statistics doesn't.

For example, a histogram lets you inspect the distribution of a variable:

histogram(data.Score)xlabel("Score")ylabel("Frequency")title("Distribution of Examination Scores")

A box plot can help you compare groups and identify observations that deserve further investigation:

boxchart(data.Group, data.Score)xlabel("Group")ylabel("Score")

For two numerical variables, a scatter plot is a useful first check:

scatter(data.Hours, data.Score)xlabel("Study Hours")ylabel("Score")title("Study Hours and Examination Score")

This is more than making your report look better. Visualisation can change how you approach the analysis.

A scatter plot, for instance, might show that two variables have a curved relationship rather than a straight-line relationship. It might also reveal clusters or a handful of observations that have an unusually large influence on the apparent relationship.

MATLAB's statistical tools are designed to combine descriptive statistics and visual exploration as part of the wider analysis process.

5. Calculate Correlation

If you want to measure the strength of an association between two variables, correlation is one option.

Suppose I want to investigate whether study time is associated with examination scores:

[rho, pValue] = corr(data.Hours, data.Score, ... "Rows", "complete");

MATLAB's corr function supports both linear and rank-based correlation methods, including Pearson, Spearman, and Kendall approaches.

For data that doesn't fit the assumptions of a standard Pearson correlation, you might consider Spearman correlation:

[rho, pValue] = corr(data.Hours, data.Score, ... "Type", "Spearman", ... "Rows", "complete");

But there's an important distinction here: correlation does not prove causation.

If students who study longer tend to receive higher marks, the data shows an association. It doesn't automatically demonstrate that additional study time caused the higher scores. Other factors could be involved.

That distinction is easy to overlook when you're concentrating on getting MATLAB to produce the correct number.

6. Perform a Hypothesis Test

Hypothesis testing becomes useful when you have a specific claim that you want to investigate.

For example, suppose I have two independent groups and want to compare their average measurements. A two-sample t-test can be performed with:

[h, pValue] = ttest2(groupA, groupB);

MATLAB provides several hypothesis-testing procedures, including t-tests for one and two samples, paired observations, distribution tests, and nonparametric tests.

The important part is choosing the test based on the research design rather than simply choosing the test that produces the result you want.

I also wouldn't report only the p-value.

A useful statistical interpretation should consider the size of the observed effect, uncertainty around the estimate, sample size, assumptions, and the practical meaning of the finding.

A result can be statistically significant without being particularly important in the real world. Conversely, a potentially meaningful effect may not reach conventional statistical significance when the sample is small.

7. Compare Several Groups With ANOVA

If you're comparing more than two groups, ANOVA can be more appropriate than performing multiple separate t-tests.

For a simple one-way ANOVA, MATLAB provides anova1:

[pValue, tbl, stats] = anova1(data.Score, data.Group);

If the overall analysis indicates that group means are not all equal, you can investigate the differences further with multiple comparisons:

multcompare(stats);

MATLAB supports several forms of ANOVA, including one-way, two-way, multivariate, repeated-measures, and nonparametric approaches.

ANOVA isn't simply a more complicated t-test. The underlying design and assumptions matter. For example, independence, the distribution of residuals, and variance characteristics need to be considered when deciding whether a particular ANOVA model is suitable.

This is one of those situations where understanding statistics is more important than knowing the MATLAB syntax.

8. Use Regression to Examine Relationships

Correlation tells you about association between variables, but regression gives you a way to model a response variable using one or more predictors.

For example, suppose examination score is related to both study hours and attendance:

model = fitlm(data, "Score ~ Hours + Attendance");

You can inspect the fitted model with:

disp(model)

MATLAB's regression functionality covers linear, generalized linear, nonlinear, mixed-effects, and other regression approaches. You can also examine residuals and diagnostic plots after fitting a model.

I would strongly recommend looking at those diagnostics.

It is tempting to focus on coefficients and p-values because they're easy to copy into a report. But a regression model is not automatically trustworthy just because MATLAB has fitted it successfully.

Residual patterns, influential observations, nonlinearity, and other problems can indicate that the model isn't representing the data appropriately.

9. Standardise Variables When It Makes Sense

Sometimes variables need to be put on a comparable scale.

MATLAB's zscore function converts observations into standardised scores:

Z = zscore(data{:, ["Age", "Income", "Score"]});

This can be useful when variables are measured using very different units or when a particular modelling technique benefits from standardised predictors.

However, I wouldn't standardise variables automatically. Whether it makes sense depends on the purpose of the analysis. Keeping variables in their original units can actually make a model much easier to interpret.

10. Fit Probability Distributions

Another useful MATLAB capability is fitting probability distributions to observed data.

For example:

pd = fitdist(data.Measurement, "Normal");

You can then use the fitted distribution for further calculations or visualisation.

MATLAB also provides the Distribution Fitter app, which lets you explore distribution fits interactively. The Statistics and Machine Learning Toolbox supports a range of continuous and discrete probability distributions.

Again, I wouldn't choose a distribution simply because its curve looks good on a graph. You need to consider whether the distribution is sensible for the process that produced the data and whether the fit is adequate for the purpose of your analysis.

A Simple End-to-End MATLAB Example

Let's put the workflow together.

Imagine I have a dataset containing study hours, attendance, and examination scores for 150 students. I might start with:

data = readtable("student_data.csv");summary(data)mean(data.Score, "omitnan")median(data.Score, "omitnan")std(data.Score, "omitnan")histogram(data.Score)figurescatter(data.Hours, data.Score)[rho, pValue] = corr(data.Hours, data.Score, ... "Rows", "complete");model = fitlm(data, "Score ~ Hours + Attendance");

At this point, I have several pieces of information, but they don't all mean the same thing.

The descriptive statistics tell me what the examination scores look like numerically. The histogram shows the distribution. The scatter plot gives me a visual indication of the relationship between study time and scores. Correlation quantifies an association, while the regression model lets me examine a response using multiple predictors.

That's why I prefer to think of MATLAB as an analysis environment rather than simply a collection of statistical commands.

MathWorks' own statistical methods training follows a similar progression, covering data management, summary statistics, visualisation, distribution fitting, significance tests, ANOVA, regression, data reduction, and simulation.

How to Make Your MATLAB Analysis More Reliable

Getting a numerical answer is not the same as producing a good statistical analysis.

When I'm working through a dataset, I keep a few practical habits in mind.

Don't choose the statistical test first

Start with the research question and the structure of the data. Then decide which method answers that question appropriately.

Don't ignore assumptions

A statistical method can be mathematically correct while still being inappropriate for your particular dataset.

Check the assumptions relevant to the method you're using rather than treating MATLAB's output as automatically valid.

Don't remove inconvenient observations

Investigate outliers and missing values before deciding what to do with them. Keep a record of any exclusions and explain the reasoning.

Don't report only p-values

Where appropriate, report estimates, confidence intervals, effect sizes, and other information that helps readers understand the size and uncertainty of the result.

Keep your code

One of the biggest advantages of MATLAB is reproducibility. Save the script that imports the data, performs transformations, runs the analysis, and creates the figures.

If you later discover an error in the dataset or receive additional observations, you can rerun the analysis rather than starting from scratch.

Where MATLAB Fits Compared With Other Statistical Tools

MATLAB isn't the only option for statistical analysis, and it isn't automatically the best choice for every project.

R has a huge ecosystem for statistics and research, while Python is widely used for data science, machine learning, and general-purpose programming. MATLAB's strength is the way numerical computing, visualisation, statistics, simulation, and engineering workflows fit together.

That can be especially useful if you're already working with MATLAB for another part of a project.

The Statistics and Machine Learning Toolbox also offers interactive applications alongside programmable workflows. For example, the Regression Learner and Classification Learner apps can help users compare models interactively and then generate MATLAB code for further work.

The trade-off is cost: MATLAB and some of its specialised toolboxes require appropriate licences. Students should check whether their university already provides access.

When Data Preparation Becomes the Difficult Part

In many student projects, the statistical test isn't actually the biggest obstacle.

The difficult part can be getting a messy dataset into the right structure first—filtering observations, combining tables, converting variables, handling missing values, reshaping data, and making sure the variables going into the statistical test are actually what you think they are.

If that is the part you're struggling with in an academic project, getting specialist guidance on a data manipulation assignment service can be useful. The important thing is to understand the transformations being performed rather than treating data preparation as a black box.

Final Thoughts

Learning how to use MATLAB for statistical analysis is less about memorising commands and more about developing a sensible analytical workflow.

I would begin with the question you want your data to answer. Then import the dataset, inspect it carefully, deal with missing or problematic observations, calculate descriptive statistics, and create a few useful plots. Only after that would I choose a hypothesis test, ANOVA, correlation, regression model, or another statistical method.

MATLAB gives you a substantial set of tools for doing this. Its official documentation covers descriptive statistics, hypothesis testing, probability distributions, regression, ANOVA, clustering, and machine learning in considerable depth.

But the software cannot decide whether your research question makes sense, whether your data was collected properly, or whether a statistically significant result is practically meaningful.


Taylor Harris

9 Blog posts

Comments