Unit#8  MATLAB 1 - Engineering Applications
Course Outline Return to Unit
Batch approach. The m-files

 

As you read this material we strongly recommend that you activate your MATLAB window and try the commands right there and then.

So far we worked with MATLAB in its fully interactive mode, this is to say we worked by entering commands at the command window and seeing their effect either at the command window, or on the figure window or on the output file created.

It is now time to put together all these elements and write a “program” which will be able to perform a certain task. This is achieved, by selecting a new m-file and writing our commands in it. The file can then be run from the command window by simply entering the name of the m-file at the prompt. Here is how you start an m-file: from the file menu you select new and then M-file. This will open the MATLAB editor window shown below:

We enter our commands, one per line and then we save the file in a folder using a name for the file, which will remind us its function, for example order2poly.

As an illustration of this, let us create a small program which will create a table of y = 2 x2 +3.2 x – 5.6 versus x as x varies between –2 and +2. The table should be outputted both to the screen and to the file polyreport.txt. The program in our editor window looks like this ( please note the brackets around [ x ; y ], in the output statements) :

notice that we saved the file with the name order2poly.m in our desktop folder MatlabDataFiles ( see the name of the file on the top bar). We can now go to the command window, ( make sure the current directory is MatlabDataFiles ) and simply type

order2poly

which makes the program run and produce:

It is very interesting to note that the editor can also be used to debug and run our program. Check and see that under the menu Tools we have the option Run . Also, if we move our cursor to a specific variable we get to see the contents in a bubble, which pops up as shown below:

 

 

Here we list the above example and some additional ones in simple text form:

order2poly.m

The above example on forming a table with the values of poly

unit8ex2.m

The sample problem of unit1 written in MATLAB

unit8ex3.m

Program which plots the function exp(alpha x) cos( omega x)

 
Jacob Y. Kazakia © 2001 All rights reserved