1
ENGR 1140
2019
Unit 2
Whitmoyer
M-files and the MATLAB Editor
1. Script Files (M-files).
Typing commands in the command window is tedious, and it’s not very convenient to execute a
long sequence of calculations. A much better way to execute commands is to create a file where
they can be edited and saved.
We call this list or sequence of commands a program. The file is called a Script file, and it’s
also called an M-file because the filename extension .m is always appended to the name you
give the file. After completing this section, you should be able to:
• Create an M-File (a MATLAB program) and
execute the M-File from the Command
Prompt.
Here are some other important aspects of Script files:
• When the Script file is executed (run) MATLAB executes the commands in the order in which
they are listed.
• A command in the Script file that produces an output causes the output to be displayed in the
Command Window.
• It is very easy to edit, modify, and save the Script file.
2. Creating and saving a Script file.
A. Look at the smaller Current Folder window within the MATLAB main window. You will
need to change the Current Folder to your folder on the Z: network drive, so you can save your
programs there.
Click on the
Browse for folder
icon
In the next window that opens, click on
2
ENGR 1140
2019
Whitmoyer
Then click on your roaming Z: connection
Then press the Select Folder button at the bottom of that window
Next, you might see a MATLAB folder in the Current Folder Window.
(You will not see testprogram.m )
You will then need to
double left-click on the
MATLAB folder.
Now, files like “testprogram.m” can be saved in the MATLAB folder, on your Roaming
Z:drive.
B. If you want to save files to a USB drive, insert your USB drive into a USB port.
Click the Browse for folder icon, then in the next window click where your USB drive is
connected. This might be E: , F: , or G: on your computer.
3
ENGR 1140
2019
Whitmoyer
Switching your Current Folder tells MATLAB that you want to run programs (Script files)
stored in that location. When MATLAB is looking for programs, it searches in your Current
Folder, then searches in MATLAB’s default directories.
C. You can open the MATLAB Editor 2 different ways: (see screen shots below and on
next page)
1. Type edit at the command prompt, and then press ENTER.
2. Click on the New Script icon at the top left of the main MATLAB window.
In this view, the Current Folder was changed to a USB drive, E:
R2016a
The MATLAB Editor is a very convenient and powerful application that helps you create, edit,
and “debug” (remove errors from) programs that you write.
Note: Any text editor can be used to create MATLAB programs, but the MATLAB Editor is
your best option.
4
ENGR 1140
2019
Whitmoyer
D. You will now create your first MATLAB program.
It’s very simple !
After you have opened the MATLAB Editor, type what is shown in the screen shot below,
EXACTLY AS SHOWN, except type in Your Name, instead of M. Yoder, and use the
current date
This name will be Untitled before you save the program.
E. Save this program to your Roaming Z:drive as “ColorBars” by clicking on
Save, and then Save As … in the top menu of the Editor (see picture below).
The filename extension .m is automatically added to the name.
Assuming that you changed your Current Folder in part A., and have named your file
ColorBars, the file ColorBars.m should now appear in the Current Folder.
F. There are 2 different ways to run (execute) your program.
1. The first way is to click on the green Run button in the toolbar at the top of the Editor
(see picture above). If needed, this will change the Current Folder to be the Folder where
this program resides, and it will then run (execute) the program. Do this now.
Another window should open, labelled Figure 1, showing a series of colored bars (pretty!).
5
ENGR 1140
2019
Whitmoyer
If you don’t see Figure 1, it may be hidden behind the main MATLAB window, or you can
check the Command Window for errors. Errors in MATLAB can often be difficult to interpret,
even when the supposed line number is given.
You can’t run a program unless it appears in the Current Folder.
2. Another way to run your program is to run it from the Command Window. Close the
Editor by clicking on the X at the top right of the window. At the command prompt in the
Command Window, type
>> ColorBars
ENTER
Note: You do not type ColorBars.m which includes the .m filename extension.
Congratulations, some of you have just created your first program!
% Comment Lines
In the preceding program (ColorBars.m), the first line at the top started with the percent
symbol, % . Anything typed after the percent symbol is regarded as a _______________ ,
and is _______________ by MATLAB, but it’s ______________ information for the
programmer !
For anything typed to the right of the %, you don’t have to worry about ______________ or
syntax. Also, MATLAB will not execute anything in a comment.
3. Writing programs to solve math problems.
Here’s an example using the quadratic formula.
Let’s say your quadratic equation is 3x2 + 2x – 15 = 0
You want to find the values of x that satisfy the equation.
Open a new Script file, and type in the following program, and save it as
Quad_ratic.m
8-22-2016
6
ENGR 1140
2019
Whitmoyer
>> x1 =
>> x2 =
4. Writing programs to solve physics equations.
A. From physics, an equation of motion with constant acceleration is:
V2 = Vi2 + 2ad
, where V = velocity of some object (m/sec) , at some distance, d.
(equation 1)
Vi = the initial velocity (m/sec) of the object.
a = the constant acceleration (m/sec2)
d = the distance travelled (m) by the object over some time
interval.
If you throw some object downward, from the top of a cliff, and
assume there is no air friction on the object, then the nearly
constant acceleration is g = 9.81 m/sec2.
Starting with equation 1, rewrite the equation to calculate V,
V =
Next, write down, in the lines below, the commands for a MATLAB program that calculates
the velocity (v), given the values for the other variables as shown in line 3 below,
1 –
% fall_velocity.m
2 –
% Your name and date
7
ENGR 1140
2019
Whitmoyer
3 –
vi = 2 ; a = 9.81 ; d = 7 ;
4 –
v =
5 –
How should you end each line, if the only output that you want to see in the Command
Window is the calculated value for V ?
Open a new Script file, type in your program shown above, and save it as
“fall_velocity.m”
Run your program, and write down the calculated value of the velocity
_____________ m/sec
( This is the velocity when it reaches 7 m. The initial velocity was 2 m/sec )
B. Another equation of motion, with constant acceleration is the following,
d = Vi t + at2
2
where d = the distance travelled (ft) by the object,
during time, t.
t = time (sec.)
a = acceleration due to gravity (ft/sec2)
Vi = initial velocity of object (ft/sec)
For the application, consider you are trying to determine the
depth of a well. You drop a rock down the well (so initial
velocity is zero), and measure the time it takes to hear the
splash.
We will neglect drag due to air friction on the rock, and we
will ignore the very short time it takes for the splash sound to travel back up the well. ( The
speed of sound in dry air at room temperature is about 1137 ft/sec).
Write another MATLAB program below, that will calculate the depth (d) of the well (in feet)
with the variable assignments shown below (in line 3 of program),
The only output (in the Command window) should be for the variable, d.
1 –
% well_depth.m
2 –
% Your name and date
3 –
vi = 0 ; a = 32.174 ; t = 2.5 ;
8
ENGR 1140
4 –
2019
Whitmoyer
d =
5 –
Open a new Script file, type in your program shown above, and
Save your program as “well_depth.m”
Run your program
Write down the calculated depth __________ ft
( The initial velocity was 0 m/sec. The time it took to hear the splash was 2.5 sec. )
5. Fun Matlab programs
% Heart3.m
8-30-2016 M.Y.
x= -2:0.001:2 ;
for w = 0.3:0.03:2
y=(sqrt(cos(x)).*cos(200*x)+sqrt(abs(x))-w).*(4-x.*x).^0.01;
plot(x,y,'r','linewidth',1.3)
pause(0.1)
end
% Warning: Imaginary parts of complex X and/or Y arguments
ignored
% Test_pattern.m
[x,y] = meshgrid(-200:200);
r = hypot(x,y);
km = 0.8*pi;
rm = 200;
w = rm/10;
term1 = sin( (km * r.^2) / (2 * rm) );
term2 = 0.5*tanh((rm - r)/w) + 0.5;
g = (term1 .* term2 + 1) / 2;
imshow(g, 'XData', [-.8 .8], 'YData', [-.8 .8])
axis on
xlabel('Normalized frequency'), ylabel('Normalized frequency')
title('Test pattern')
9
ENGR 1140
2019
Whitmoyer
% polar_plot_1.m
% example of a polar plot
M. Yoder
theta = 0:(0.01*pi):(2*pi);
r = 5*cos(4*theta);
rr = 3*cos(8*theta);
h1 = polar(theta,r);
set(h1,'color','b','linewidth',4)
hold on
h2 = polar(theta,rr);
set(h2, 'color','r','linewidth',4)
6. Creating programs with animation.
This line is automatically added by MATLAB. We’ll describe these new commands later!
Once you get a program like this to work, you can then change various things, to learn what it’s
doing. However, each time you run the program, it will automatically save your changes, and
you will no longer have the original version! So, resave the program with a different name
before you start making changes. That way you still have the “original recipe”.
Below are two more programs with animation. We’ll learn more about these commands in the
next several weeks. But, you can also experiment, and change different parts of the program
10
ENGR 1140
2019
Whitmoyer
and observe how that affects the animation.