How can I save MATLAB variables to a text file?
To save your matlab variables/arrays as ascii text, there are a number of things you can do. Here are some options in order of increasing difficultly:
- For small matrices, you can use the "diary" command to create a diary file, and then list the variables on this file. You can then use your text editor to manipulate the diary file at a later time. The output of the diary includes the matlab commands used during the session. To turn the diary on, you simply enter a command of the form:
diary filename
To turn the diary off, just enter the command:
diary off
When using this method, you have some control the output format with the "format" command. See "help format" for more details.
- You can save variables using the "save" command, with the /ascii option.
For example:A = rand(4,3); save temp.dat A /ascii
creates an ASCII file called temp.dat which contains something like:
0.2113 0.8096 0.4832 0.2115 0.7496 0.4483 0.4813 0.5896 0.4383 0.2373 0.5654 0.1934
The format options are limited to either short or long floating point format with the "save" command.
- Use the "fopen" and "fprintf" commands in Matlab to create your own custom format. These commands are similar to the ANSI C functions of the same name, with some extensions. Here is a simple example from "help fprintf". These statements
>> x = 0:.1:1; y = [x; exp(x)]; >> fid = fopen('exp.txt','w'); >> fprintf(fid,'%6.2f %12.8f\n',y);
create a text file containing a short table of the exponential function:
0.00 1.00000000 0.10 1.10517092 ... 1.00 2.71828183