Many students ask me how do I do this or that in MATLAB. So I thought why not have a small series of my next few blogs do that. In this blog, I show you how to read data from an external data file. We will use the simplest command to read from a text file, that is, the fgets command.
So let us look at an example. Let’s suppose someone asks you to find the dot product of two vectors: A=[7 11 13 23] and B=[3 5 17 29]. The program for that simply is
A=[7 11 13 23]
B=[3 5 17 29]
What if now the data for the vectors are given in an external text file? How does MATLAB read the data and assign it properly to A and B.
The first thing is to make the text file. Let’s save this data in the file called /blog/vectordata.txt. The text file is here.
7 11 13 23
3 5 17 29
Now how is this data read from the data file.
First you tell MATLAB what the name of the file is
Now the file needs to be opened by using the fopen command. This also assigns an integer to the file called the filehandler. This integer is automatically assigned by MATLAB and is a unique integer for any open file. The ‘r’ stands for the file being opened for reading. The other choices are ‘w’ for writing and ‘a’ for appending.
Now we need to get the data from the file which is identified through the file identifier variable. The fgets command does this and every time fgets is used, it reads the next line.
However, this reads the whole line of data as a single string. How do we now get it to be a vector A with the 4 entries. We do this by using the sscanf command that parses the string variable into the format used by sscanf. The format used here is %f which is a floating point format. The other formats for reading numbers include %e for scientific format and %d for integers.
Similarly, one can now read the B vector via fgets command and parse it using the sscanf command.
This post is brought to you by Holistic Numerical Methods: Numerical Methods for the STEM undergraduate at http://nm.mathforcollege.com, the textbook on Numerical Methods with Applications available from the lulu storefront, and the YouTube video lectures available at http://nm.mathforcollege.com/videos and http://www.youtube.com/numericalmethodsguy