M-files
Home Up Quick Reference M-files Laser Printing 1. Matlab Basics 2. Sequences & Series 3. Taylor Series 4. Fields & Flows 5. ODE Models 6. Symbolic ODE 7. Systems & 2nd order 8. Numerical ODE 9. Laplace Transform

[What are M-files | How to make them | A Function M-file  A Command M-file ]

What are M-files

M-files are files that contain a collection of  MATLAB commands or are used to define new MATLAB functions. (Read about 'Simple Function M-Files' on page 41 of ODE using MATLAB to learn more about M-files.)  

For the purposes of this class, we will only need very simple M-files used to define new functions.  However, you may find them useful for other parts of your homework as well. For example you may put a bunch of MATLAB commands into an M-file and then run all of those commands at the MATLAB prompt simply by typing the name of the M-file. 

How to make M-files in General

Make sure that the MATLAB command window is active.

Choose 'NEW M-file' from the 'File' menu.  (This will bring up MATLAB's M-file editor.)

Edit your file.

Choose 'Save' from the 'File' menu and then click on the 'DESKTOP' button, and then click on the Workspace icon. 

In the 'SAVE document as:' box, type in the name you want to call the file. (There maybe a name in the box already, if it is ok leave it alone, otherwise change it.) Important: the name of your file should end in '.m', for example 'whatever.m' (without the quotes) is a fine name.

Finally click on the SAVE button to save the M-File. 


In order to use this file please be sure to type 'start' in the MATLAB command window at the beginning of your session. This ensures that MATLAB will be able to find your M-files.

An Example Function M-file

Here is an example of a function M-file for use in Example 1 of the assignment on numerical ODE. 

function xpr=firstode(t,x);
%
% A line with starting with % is only a comment, unseen by MATLAB. 
%This M-file is used with ode45 to solve the differential equation
% x'(t)=sin(tx(t))
%
xpr=sin(t*x);

Assuming this file is saved as    firstode.m    then when you type at the MATLAB command prompt

>> firstode(1.7,2.3)

you will get          

    ans =-0.6950

which is approximately   sin(1.7*2.3).

An Example Command M-file

Here is an example of an M-file containing a few commands. 

 

1+2
sin(3*exp(4))
syms x
diff(cos(x))

Assuming this file is saved as    tryme.m    then when you type at the MATLAB command prompt

>> tryme

you will get:

ans =
3
ans =
0.4184
ans =
-sin(x)

[What are M-files | How to make them | A Function M-file  A Command M-file ]

 

Jump to Bruce Driver's Homepage.                       Jump to Current Courses Page.

Last modified on November 19, 1999 at 10:51 AM.