In MATLAB, data can easily be loaded from a data file. This has many advantages: It is quicker to load a data file than to type in all the numbers; loading data at the keyboard is likely to introduce typing errors; if there are errors in the data, it is easier to alter the file than to re-enter all the data again.
A data file called tester.txt in the data subdirectory of glmlab contains the following data:
1 2 -1 0 1 3 4 5 -1 -2 3 1Here is an example of how to load the file, play with it, and save another file:
>> %LOAD THE FILE tester.txt >> load tester.txtThe data is now loaded as a matrix called tester:
>> tester
tester =
1 2 -1 0
1 3 4 5
-1 -2 3 1
Let's play with this a little. First, call the first
column of data y:
>> %PLAY WITH THE DATA
>> y=tester(:,1)
y =
1
1
-1
Call the second column x1,
the third x2, the fourth x3:
>> x1=tester(:,2); x2=tester(:,3); x3=tester(:,4);
Many commands can be placed on one line, separated by a semicolon or a comma. Notice, also, how to access particular columns of a matrix using a colon. Rows can be accessed in a similar way; r=tester(1,:) would place the first row of tester into row vector r.
In MATLAB, it is standard to define variables as column vectors. This
standard is adopted by glmlab.We can now manipulate the vectors:
>> x=x1+x2-3*x3
x =
1
-8
-2
To save y and x in the file
prac.txt, proceed as follows:
>> save prac.txt y x -asciiThat is,
save <filename>.<extension> <variables> -asciiwhere the -ascii is so that humans can read it. However, the best way to save the file is to use save <filename> <variables>:
>> save prac2 y xThis creates a file called prac2.mat which MATLAB can use, but humans can't understand. To the load the file prac2.mat, simply type load prac2. This will automatically create two variables (called x and y) without you having to declare them explicitly.
A file called loadme.mat should be in the glmlab data folder. First, clear all the current variables (using clear), and then load this file:
>> clear all >> load loadmeBy typing who at the MATLAB prompt, the variables that have been loaded can be seen (try typing whos also):
>> who Your variables are: x y zHave a look at the variables (especially the variable called x) by typing variable names at the MATLAB prompt.
When saving data, the best method is to use the syntax:
save <filename> <variables>