Section 5.3 Import Data
There are several ways to import data: MATLAB’s Import Wizard, the
load()
command, or the fscanf()
command we just studied. Let’s take a closer look at the load()
command.Remember how difficult it was to use the fscanf() command to read tabular data into a variable and preserve the shape of the original table? The problem comes from the fact that MATLAB populates an array column-by-column (but data from the file is read row-by-row).
The
load()
command is less flexible than the fscanf() command but it makes it much easier to read from files whose data is a table. The load()
command will import such data into a single array variable (if you don’t specify a variable name then it will be the same as the filename). For example, if we want to load the data from our above file numbers.txt
, we can use the load()
command:>> load 'numbers.txt'
numbers =
23.5000 34.3000 33.1000
63.9000 234.0000 34.2000
54.3000 34.2000 67.9000
234.3000 22.5000 34.7000
78.5000 57.4000 44.0000
...
There is no need to open the file prior to loading its data, the
load()
command does it all. It is a very useful command for simple formats. You also do not need to close the file after loading the data.You can specify the name of the variable in which the file’s contents are stored:
>> fname='numbers.txt'; >> data = load(fname)
data = 23.5000 34.3000 33.1000 63.9000 234.0000 34.2000 54.3000 34.2000 67.9000 234.3000 22.5000 34.7000 78.5000 57.4000 44.0000 ...