Software tutorial/Scripts and functions

From Process Model Formulation and Solution: 3E4
< Software tutorial
Revision as of 14:17, 19 September 2010 by Kevindunn (talk | contribs) (Created page with "== Scripts == * Scripts are a series of commands, saved in a <tt>.m</tt> or <tt>.py</tt> file. * When you run a script, it is as if you typed each line, in sequence, into MATLAB...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Scripts

  • Scripts are a series of commands, saved in a .m or .py file.
  • When you run a script, it is as if you typed each line, in sequence, into MATLAB or Python.
  • It is good programming practice, and is required for this course, that all all your programs should run from a script.
    • It prevents you retyping in the commands if you need to change a variable's value
    • You must use scripts if you need to debug your program
    • Is helpful when you come back weeks or months later to figure out what you did (like revising for exams)
    • Can be shared with your colleagues for collaborative development.
  • All variables resulting from calculations performed in the script are available to you in the command window after the script is finished


A simple example of a script:

MATLAB: example.m Python: example.py
rho = 1200;   % [kg/m^3]
Cp = 4180;    % [J/(kg.K)]
f = 0.1;      % [m^3/s]
T = 341;      % [K]
energy_in = rho * Cp * f * T; % [J]
disp(['The energy in = ', num2str(energy_in/1E6), ' MJ/s'])

Now at the MATLAB command prompt you can type:

>> example
The energy in = 171.0456 MJ/s
rho = 1200    # [kg/m^3]
Cp = 4180     # [J/(kg.K)]
f = 0.1       # [m^3/s]
T = 341       # [K]
energy_in = rho * Cp * f * T # [J]
print('The energy in = %f MJ/s' % energy_in/1E6)

From the Python command prompt:

>> execfile('example.py')
The energy in = 171.0456 MJ/s


Functions

  • Functions are more versatile than scripts because they can accept input arguments and return output values
  • An example of a simple function:
function d = distance(x,y)
% calculates distance between the point (x,y) and the origin
z = x2 + y2;
d = sqrt(z);
end
  • The output variable here is d and the input variables are x and y
  • The name of the function is distance
  • The function .m file MUST HAVE THE SAME NAME AS THE FUNCTION
  • The % sign signifies the start of a comment (text that is ignored by MATLAB)
  • The above function may be called (both at the command line and in a script) by the following command:
D = distance(2.0,3.5)
  • The function will calculate the distance between (2.0,3.5) and the origin and put the result in the variable D
  • Note that the function allows us to perform the distance calculation without previously assigning values to the variables x and y in the workspace
  • A function can assign multiple output variables (consult MATLAB help to find out how)
  • Functions can call other functions