Matlab Scripts

Matlab Scripts (or .m files) contain a set of instructions to accomplish a goal. Usually scripts will create variables, assign them values, do some computations, and report an answer. Small programs are often written as scripts (usually a page or less of code). Large programs are usually created using functions.

Matlab Scripts (of .m files)

Scripts are just lists of commands that we (usually) want to be used over and over again. (Note: scripts are similar to functions, but variables are stored in the Global Matlab Workspace.)

Scripts are stored in .m files (DOT M). Thus a the sin function would be stored in the file "sin.m", or our body_mass_index script would be stored in "body_mass_index.m".

Why Scripts?

  1. They keep us from retyping everything over and over again.
  2. We can modify just a few lines (or even only one line) and re-run our program.
  3. Variables introduced in scripts are introduced into the global namespace.
  4. Scripts are stored in ".m" files

Example Script.

Here is the body mass index script in a nicer form

%  File    :   body_mass_index.m
%  Author  :   Jim
%  Date    :   Fall 2007
%  Teammate:   None
%  Course  :   CS 1000
%  Description :  (in English, not Code)
%    This program determines a persons BMI (or body mass index)
%    by diving the weight of the person (in kilograms) by the
%    (height of the person squared).
% Used Variables and what they mean:
%    weight : a floating point number representing the weight in Kilograms
%    height : a floating point number representing the height in meters
%    bmi    : a floating point number representing body mass index

weight = input('Type your weight (kg): ');
height = input('Type your height (m): ');
bmi    = weight / height^2;

% Print the BMI 

fprintf('Your Body Mass Index is %f\n", bmi);

Back to Topics List