clear
echo on

%This is a demonstration of matlab read and write
%file handling procedures.  First we demonstrate
%the write command, which is 'save'

%We construct a matrix a:

a=[1.2, 2.3, 3.4; 4.5, 5.6, 2*pi]

pause

%Now we save this to a file a.m in the current
%directory:

save 'a.m' a;

%Try opening the file a.m using the text editor.
pause

%It looks like garbage because it is stored in
%a binary format.  We can change this by using
%some switches:

save 'a.m' a -ascii -double -tabs;

%which should save the file in ascii format, using
%double precision, and tab delimited columns.  Try
%looking at the file now with the text editor.
pause

%The file now makes more sense, but you will also
%notice the roundoff error in the last digit!

%We can load this file back in too.  First we clear
%the variable 'a', and then load it in:

clear a
load 'a.m'

%and then display the result:

a

pause

%In this case the load 'a.m' command loads the contents
%of the file 'a.m' into the variable name a.  If we had
%set the name to 'b.m' for example, it would have set
%the contents into the variable b.  Let's do this.  First
%we set up the file 'b.m' using the Unix command cp:

!cp a.m b.m
load 'b.m'

b

pause

%As you can see, this makes it easy to get files in
%and out of matlab.  The last example is printing.  The
%easiest way of doing this is to use the diary command:

diary 'out.txt'
disp('This is the matrix A')
disp(a)
diary off

%Now open the file 'out.txt' using the text editor.  It
%should give you the desired output.  The extra junk
%is there because we have used the 'echo' command.  The
%txt suffix on the file denotes it as a text file, although
%it will work ok with other suffixes.
pause

%You can do the same thing with figures using the print
%command.  First we set up the figure:

x=[0:.1:6*pi];
plot(x,sin(x))
xlabel('x')
ylabel('sin(x)')
print 'graphout.ps'

%You should now have a file graphout.ps which contains
%the postscript file of the graph.  This can be printed
%to the postscript printers in the engineering lab.  The
%ps suffix denotes it as a postscript file, although again
%it will work with other suffixes.  Putting on the right
%suffix helps to keep things straight in your directory,
%and is important when loading files back in to matlab,
%for example

%If you don't want to save the graph, but just want to
%print it directly, you can just type in:

print

%which will direct the graph to the printer rather than
%to a file.  It is probably not too good an idea to do
%this if you are in the middle of debugging your program!
%It will send the file to the printer every time it hits
%the command, and graphs really tie up the printer!  You
%can just type it in from the command line in matlab, 
%though, after the program has finished running.

echo off