In the previous video, you learned how to write data to an external file. In this video, learn how to read values from an external file into a MATLAB variable.
- [Instructor] In the previous movie, I showed you how to write data to an external file. In this movie, I will show you how to read values from an external file into a MATLAB variable. I have just started MATLAB and I have a clean command window ready to go. So the first thing I need to do is create a file with some values. I'll start by defining a variable called mat1, and then an equal sign for the assignment, and I will create the first row with the values four through 16 going up in increments of four.
So I'll type four then a colon, my step value is four colon, and the top value is 16. Then a semicolon to indicate I have a new row, and then we'll do five through 20 going up by five for the second row. So five colon five colon 20. Right square bracket and Enter, and there I get my two by four matrix. If I want to save these values in a file, then I'd need to use the save function. A space, then I will call the file matrixdata.dat.
I don't need to add the extension. It can just be matrixdata. But when someone looks at it in the current folder, I want them to understand that it is a data file. Press space. The name of the variable I'm exporting is mat1. Then a space, and I want it to be text. So we're representing text using the ASCII qualifiers, so I'll type minus ascii. And Enter. And the file is created and the values are saved there.
If I want to bring the data in, I can do that using the load command. So I'll type load space and then the name of the file, matrixdata.dat, and Enter, and you see that I have the values in the workspace in a variable named matrixdata. So everything after the period was excluded for the name. And if I type matrixdata in the command window and press Enter, then you see that I get the values back.
Normally you will work with much larger data sets than this, but it's nice to know that the procedure works for small files, as well.
- Defining variables and contains
- Exploring operators
- Summarizing with built-in functions
- Generating random numbers
- Defining vectors and matrices
- Accepting input in scripts
- Writing and reading data from external files
- Creating custom functions
- Using conditional logic
- Repeating operations with loops
- Working with text strings
- Plotting data and function output
- Formatting, saving, and printing plots
- Using statistical and matrix functions