MATH/CMSC 206 - Introduction to Matlab

Announcements Syllabus Tutorial Projects Submitting

Script M-files

Contents

What is a Script M-File?

Before we proceed further consider that when you're writing a Matlab project which involves typing a bunch of commands you probably don't want to type them over and over. In other words it would be helpful to create a "project" which contained all the commands you wished to execute. This would also be convenient for handing in homework assignments (hint hint!)

Script M-files allow us to do this. Simpler than the function M-files we'll look at later, script M-files are just text files with a .m extension which contain Matlab code that you want to run.

A Simple Script M-File

Suppose you want to write a series of commands to demonstrate your fantastic Matlab knowledge. You wish to put those in a file and then turn it in to your teacher. Simple! First create your first script. The following can be done either from within Matlab (which will open its own editor for you) or with any text editor you prefer.

edit firstscript.m

In this file type the following. This is simply a giant collection of a bunch of commands you've already learned.

3+5
sqrt(10)
gcd(120,90)
date
format long
1/7
format short
1/7
x=3.1
x^2
syms t
factor(t^3-5*t^2-6*t)
syms a b
[a b] = solve(2*a+4*b,a-b)
syms x
fzero(@(x) exp(x)+x,0)

Save this file. Now the file is available and as long as it is available you can run those lines of code simply by typing the following into Matlab.

firstscript
ans =

     8


ans =

    3.1623


ans =

    30


ans =

29-Jan-2011


ans =

   0.142857142857143


ans =

    0.1429


x =

    3.1000


ans =

    9.6100

 
ans =
 
t*(t + 1)*(t - 6)
 
 
a =
 
0
 
 
b =
 
0
 

ans =

   -0.5671

Note: When you run your script do not add the .m extension! If you do the script will run and then you'll get a peculiar error.

Just for the record, script M-files do not take parameters and do not return values. They simply contain lists of commands which are executed sequentially. For this reason they're perfect for doing a homework assignment which will be handed in. Moreover as we'll see in a subsequent lesson, M-files can be published to create html code which contain the commands and all the output (including graphs!) as well as comments. That's coming up shortly!

Self-Test

  1. Write a script M-file which does all of the following in order: Calculate 1457*2354, calculate 17!, assign the variable x to the value 7, calculate x^2-x, double the answer to the previous using ans, declare x and y symbolically, factor x^4-5x^2+4, solve y^2+2y-10=0 and numerically solve x=cos(x) near x=0.5.

Answers to Self-Test

Next Topic:   Plotting Curves