Files
Last updated on 2025-10-30 | Edit this page
Overview
Questions
- How do I read data from files in MATLAB?
- How do I save my results to files?
- What file formats does MATLAB support?
Objectives
- Learn to navigate the file system using MATLAB commands
- Understand how to load data from common file formats
- Practice saving variables and results to files
Introduction
Working with files is essential for any data analysis workflow. In this episode, we’ll learn how to access files in MATLAB, load data from various file formats, and save our results for future use.
Understanding the Working Directory
MATLAB operates from a specific location on your computer called the working directory or current folder. This is the default location where MATLAB looks for files and saves new ones.
To see where you currently are, use:
This command prints the working directory (hence the name: print working directory).
To change to a different directory, use:
Path File Separators
Linux, Mac and MATLAB Online use forward slashes / to
separate files where Windows use backslashes \.
MATLAB has a handy way of allowing you to create paths that can work
on both file systems, using the filesep
This will allow you to share code with colleagues no matter what operating system they are on.
Listing Files
To see what files are in your current directory, use:
This will display all files and folders in your working directory. You can also list files matching a specific pattern:
Loading Files
Text and CSV Files
MATLAB can easily read CSV (comma separated value), other text files
and spreadsheets using readmatrix:
MATLAB Data Files
MATLAB has its own file format with the .mat extension.
These files can store multiple variables efficiently:
Download the rain_data.mat for the next examples
You can also load specific variables:
Saving Files
Saving to MATLAB Format
The save command stores variables to .mat
files.
By default the save command will save all variables in
your workspace:
To save specific variables:
When and why use .mat files?
MATLAB’s .mat format is compressed and optimised for
MATLAB data types, so is often a good choice if your data is being saved
for working in MATLAB. The format also preserves the information about
data types and dimensions for your variables.
If you want to save your data to share with colleagues not using
MATLAB or to load into other programs like Excel, saving to a more open
format like .csv may be more appropriate.