Matlab m-files


MatLab has a rich set of built-in functions which can easily be supplemented by user created functions, programs, even toolboxes (analogous to Maple's packages).
First, we start with Matlab script files . These are collections of executable commands, which are saved in a file (with an extension of .m) which is in the MatLab executable path. These easiest way to ensure that MatLab can find the commands is to place them into a file, e.g., demo1.m

t = 0:0.01:5;           % 500 values, spaced 0.01 apart, on [0,5]
y = sin(4*t);           % function to be plotted
plot(t,y);              % 2D plot command (t,y are both vectors)!
print -deps plot1.eps;  % print current graphic to postscript file
several things to note:
  1. The percent sign "%" is the matlab comment character
  2. This file can be executed as a batch file by
    matlab < demo1.m
    
  3. When you are in terminal mode, not in X-Windows, you can only save plots to a postscript file. If you are running under X-Windows, you can execute
    print -djpeg plot1.jpeg;  % print to JPEG file
    print -dpng plot1.png;    % print to PNG file
    print -dtiff plot1.tiff;  % print to TIFF file
    
    Note: GIF format not supported (Copyright/Patent problems)

    Also, watch out for unintended side effects in script files. For example, if you include a "clear" command in the script files, all global variables are cleared!


Next, we consider Matlab function m-files.

We can define inline functions via the inline command

f = inline('sin(x)','x');
The same command in an m-file would look like
function y = f(x)
y = sin(x)
m-files are are similar to script files, but they begin with the keyword "function" and the file name and the function name must agree. That is, if a function "f" is defined by a m-file, it must reside in file "f.m" in the path. Suppose we want to evaluate 3 functions simultaneously.

We can define inline vector functions also, via,

f2 = inline('[sin(x),cos(x)]','x')
x = linspace(0,1,10)';
y = f2(x);
y1=y(:,1)   % first column vector
y2=y(:,2)   % second column vector
plot(x,y1,x,y2) % plot both curves
plot(y1,y2) % plot both curves parametrically
We could define a function "f2" in a file "f2.m" by
function [out1,out2] = f2(x)
  out1 = sin(x);
  out2 = cos(x);
We can calculate specific values by, e.g.
x = linspace(0,10,100)';
[y1,y2] = f3(x);
plot(x,y1,x,y2)
Notes:
  1. You must be careful to distinguish between column vectors (separated by a ";") and row vectors (separated by a ",")
  2. function m-files are very strongly typed. They expect to see a left hand side that precisely matches the template give in the m-file.
  3. Matlab's 2D plot function is very "smart".