How to Import Data from Files Programmatically
Learn how to import data programmatically in MATLAB® by creating a script using the Generate Code option in the Import Tool, or by writing code from scratch. This video shows how to use import functions such as readtable
, readmatrix
, and readcell
.
This tutorial focuses on spreadsheets, but MATLAB supports a wide variety of file types. The broad principles in this video can be applied to other supported file types as well.
Published: 18 Nov 2019
Hello and welcome to another MATLAB tutorial.
Let’s say we have a bunch of data sets and we want to import them the same way every time but using the import button over and over again is just an inefficient use of our time. How would we go about automating our import?
Well lucky for us, MATLAB lets us import data programmatically. Now there are two main ways to do this you can import using the import tool and then press generate code and a script will be generated.
Or, you can write the code from scratch. In the documentation you can find a list of supported file types, as you can see there’s a wide variety from videos to photos to music, this tutorial just focuses on spreadsheets, but the broad principles can also be applied to importing those as well.
The import and export functions for each file types we’re focusing on are listed here. Now an exciting development of 19a is that you no longer need to use functions such as CSVread, Dlmread, Xlsread. Instead spreadsheets with clear delimitators all use the same import functions.
The import function is read and then whatever you want to read the spreadsheet in as. So, if you wanted to import the spreadsheet as a matrix, it’s readmatrix, if you want a cell array it’s readcell, if you want a table it’s readtable etc. etc.
So, if I type in readtable(filename) and hit run, boom the program imports and spits out a table. Note that you have to be in the same directory for just writing the file name to work. Alternatively, you can write the file location for more ease of use.
MATLAB is really good at guessing the options you want for your file. But if you want to change them, you can see your options by typing detectImportOptions(filename). It returns a struct of values, for more information about what all of these different variables correspond to, consult the documentation. But let’s say we want to alter the number rows we’re reading in. Well that’s this variable here, DataLines. So we assign the options to a variable opts and then we can change the number of lines by typing opts.DataLines and assigning a new value.
When we call readtable now, we can just do comma opts and then boom only the rows you want.
You can also set variable options in a similar manner by calling setvaropts. You just write Opts = setvaropts(opts, variable name, element to change, new variable). You can access the setvaropts documentation by clicking right here on in the importoptions struct.
Thanks for watching and happy coding.