Introduction to Matlab Scripts

In the Previous Tutorials, we have been introduced to the basic methods of performing calculations and plotting graphs in Matlab. We have used these to create some interesting models. In this tutorial, we will extend our ability to create models by learning the fundamentals of creating Matlab Script files (or M-Files)

A Matlab script file (also known as an M-File because Matlab script files always have the file extension .m) is a method for executing a series of Matlab instructions without typing all of the commands from the keyboard. This allows one to automate tasks, and will allow you to write script files that a student could run without knowing the details of Matlab programming. Begin by creating the following script file by selecting File-New-MFile from the Matlab menu. Give it a name such as test1.m
      disp('Howdy Folks')
      a = input('Enter a Number to Square ');
      b = a*a;
      disp(['The Result is ' num2str(b)])
Now type test1 in the Matlab window and it will ask for a number, square it and then display the result. An important technique in programming is the concept of a loop - this allows us to perform some series of instructions many times without typing them in each time. Consider the following situation - there is a reservoir of some material (for the problem we are considering today this would be unmelted snow - after melting this will flow into a river). A very simple model of this would be that we have 100 units in the reservoir and remove 20% each time step (for example, 20% of the snow melts each day). We can make a script file to calculate the amount of melting and the amount remaining after each day by making the script file melting.m
   Reserve = 100;    % Initial amount in the Reservoir
   LossRate = 0.2;   % Rate at which material flows from reservoir
   for i=1:20;       % Perform the following statements 20 times
     OutFlow = LossRate*Reserve;  % Calculate the amount of snow that melts
     Reserve = Reserve - OutFlow; % Subtract this from the reserve
     disp(['After Day ' num2str(i) ' Outflow=' num2str(OutFlow) ' Reserve=' num2str(Reserve)]);
   end  % for i ...
Note that this program will run the loop a total of 20 times with the variable i increasing by one each time. The other

Electronic Copy:
Created: 4-APR-1997 by Tom Huber, Physics Department, Gustavus Adolphus College.