e-Mathematics > Matrix Algebra

Creating M Files

Matlab/Octave is built around the M-code, and the simplest way to execute M-code is to type it in at the prompt. In this way, it can be used as an interactive mathematical shell. Sequences of commands can be saved in a text file as a script or encapsulated into a function. Such an external Matlab/Octave file with extension “.m” is called an M files. A simple script
% It plots the sine curve on the xy-plane
x = 0:0.1:2*pi;
plot(x,sin(x));
plots the sine curve on the xy-plane. Here the semicolon (;) is not only used to terminate commands, but also serves to suppress the output of the command line. The script should be saved as M file, say “sinecurve.m,” under the current directory. Having been saved, it is executed by typing its name “sinecurve” at the prompt
> sinecurve

When you run Octave, at the screen with prompt “ยป” type

> cd [the directory where M files are saved]
If you are using Octave in Windows, you may save M files under the directory “C:\Program Files\GNU Octave\” where you install Octave. You can always go back to this directory by typing
> cd
To make sure whether the M file is under this directory, check the current place by typing “pwd” and use “ls” to see all the files under the directory. If you see it, say “yourscript.m,” you are ready to execute the script “yourscript”.

When a script needs arguments to pass, M file must be defined as a function. Here are M files defining a function we might need in this course:

idemo.m idemo('[script file]') executes a Matlab/Octave script line by line. In Matlab, you can call it by
> idemo(uigetfile('*.m','Load M file'))
In Octave you have to set
default_eval_print_flag = 1
to display the output properly.
arrow.m arrow([x0,y0],[v1,v2]) drows a vector $ \begin{bmatrix}v_1  v_2 \end{bmatrix}$ starting from the point $ (x_0,y_0)$ in xy-coordinate.
pmatrix.m pmatrix(n) generates an n-by-n probability transition matrix consisting of random entries.

You can find many more M files and custom scripts, and extensions for GNU Octave at GNU Octave Repository.


© TTU Mathematics