Introduction to Matlab Scripts

Envision It! Workshop, April 12, 1997

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.

Loops

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 (in other words, 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. To make the program more readable, there are a few rules you may wish to follow:

Condition Blocks

The other type of block is the if block allows conditional execution of a series of statements. For example, in the melting process, as snow melts, the melting rate can increase (this is because a completely snow covered surface will reflect most sunlight, but as some melts and exposes ground this will absorb sunlight and melt snow faster). A simple model might be that if the reservoir is less than 30, the melting rate is 30% per day, otherwise it is 20% per day. We could implement this by including the statements:
      if Reserve < 30
         LossRate = 0.3;
      else
         LossRate = 0.2;
      end   % if Reserve...
The placement of this block is very important - the value of LossRate is only changed when these commands are executed, thus if this block is placed immediately before the for statement, the value of LossRate will always be 0.2. To make this work correctly, this block of commands should be inserted after the for statement but before the OutFlow calculation, so it will always have the correct value for LossRate. Put these changes into your program.

It would also be nice to make a plot of the Reservoir and the Melting rate as a function of time. We can do this by appending the current values onto the end of a list of the previous values. A script file meltplot.m to do this would be

   Reserve = 100;    % Initial amount in the Reservoir
   AllReserve = [];  % Make an empty array to hold the Reservoir values
   AllOutFlow = [];
   for i=1:20;       % Perform the following statements 20 times
     if Reserve < 30
        LossRate = 0.3;
     else
        LossRate = 0.2;
     end   % if Reserve...
     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)]);
     AllReserve = [AllReserve Reserve];
     AllOutFlow = [AllOutFlow OutFlow];
   end  % for i ...
   hold off
   plot (AllReserve,'g-')
   hold on
   plot (AllOutFlow,'r-')

We could even extend the model further by saying that if the Reservoir is less than 10, it all melts immediately. We could do this using the if-elseif structure. Modify your program to do this.


Electronic Copy: http://physics.gac.edu/~huber/envision/tutor2/mtlscript.htm
Created: 4-APR-1997 by Tom Huber, Physics Department, Gustavus Adolphus College.