Often you’ll have a need for recording the data your programs generate. MATLAB and Octave have a few ways to do this. We can best show this with a quick example.
The following code will generate a matrix 10,000 by 6. On my current hardware this takes about 2 seconds to execute.
% Sample code to generate a large matrix
clear
for i = 1:10000
a = sin(i*pi/180);
b = cos(i*pi/180);
c = tan(i*pi/180);
temparray(i, 1:6) = [a, b, c, a^2, b^2, c^2];
end
In MATLAB and Octave, the process of outputting data to files is called “exporting.” Reading data in is likewise called “importing.”
The easiest way to save the above output to a file is to use the save function and add it directly to the code. Adding the following line just below the for loop would do the trick.
save test.txt temparray -ascii
The format is: save filename variable -format. The above will result in a text file called test.txt which will contain the variable “temparray.” You can open or view this in any text editor. The default delimiter is a space but if you’d like to save it as tab-delimited data, you would simply change the line to the following:
save test.txt temparray -ascii -tabs
If you do not specify the variable, all variables in the current workspace will be saved to the file. The above could also be executed from the command line, as long as you had recently run the code and the variable “temparray” was still assigned the value you need. Worth noting is that within Octave or MATLAB, if you save without using the -ascii tag, the default will be to save the data in a proprietary binary format and you will have something like the below text at the top of your document:
# Created by Octave 3.2.4, Thu Mar 10 00:24:15 2011 EST
# name: temparray
# type: matrix
# rows: 10 000
# columns: 6
1.7452e-02 9.9985e-01 1.7455e-02 3.0459e-04 9.9970e-01 3.0468e-04
3.4899e-02 9.9939e-01 3.4921e-02 1.2180e-03 9.9878e-01 1.2195e-03
5.2336e-02 9.9863e-01 5.2408e-02 2.7391e-03 9.9726e-01 2.7466e-03
...
This may be inconvenient for your purposes (for example, if you are using the data with an external program), but if you are going to use the “load” command (described later) to import this file, it doesn’t matter that this header information is present. If it is a hindrance, you can always save the data using the -ascii tag.
Other ways to export data to a file is with the fwrite, csvwrite and dlmwrite commands. Both programs have detailed help files on these commands but in short, they are for appending to files (fwrite), saving as comma-separated-values (csvwrite) and using specific delimiters (dlmwrite).