Creating programs

All programs that have a certain goal to achieve. For example, the goal of a script file may be, to plot the function $ f(x)$ in the interval $ 0\leq x \leq 10$ .

Usually, some intermediate steps have to be taken to achieve the goal. In our example, the following steps are needed:

  1. Distinct points $ x$ should be determined.
  2. For each point $ x$ , the function values $ f(x)$ should be computed.
  3. The obtained function values should be plotted.
  4. The figure should be given appropriate title and axes labels.
In addition, it is wise to clear all variables at the beginning of your program. Hereto, the command clear all can be added.

Of course, the number of steps will increase when obtaining the goal is more difficult.

When you want to write a program achieving a certain goal, it is advisable first to determine all steps that are needed. This will be done in a list of steps, that are needed. When you know your sequence of steps will achieve the goal required, you can start writing your m-file according to your designed sequence of steps.

To make your Matlab files understandable to others, and to make it easier for yourself to use them later, you should add comments (with a % character in front of it) in your file, that clarify the step you are programming in a certain part of your code.

In our example, the program design given above will yield the following m-file to plot the function $ f(x)=arctan(2x^3)$ on 101 points. When a smoother plot is required, more points should be used.

%clear existing variables:
clear all;

% Determine distinct points x.
x=0:.1:10;

% For each point x, compute f(x) and store in an array F. Hereto,
% first create an array F:
F=zeros(length(x),1);
% compute f(x) for each x
for k=1:length(x)
    F(k)=atan(2*x(k)^3);
end

% plot F versus x
plot(x,F)
% labeling
title('function arctan(2x^3)');
xlabel('x')
ylabel('y')

Sometimes one has to figure out, what is the design of an existing program. In that case, from an existing m-file a sequence of steps should be derived. This may be a hard job when little or no comments are added.

Cell mode
The most important way to make an program understandable to others is the use of comments. In addition to these, one can subdivide a MATLAB program into cells. These are similar to sections in a normal texts. To start a cell, one should type %% cellheader in front of it, where cellheader can be replaced with a caption. For example, one can divide a program in a cell Initialisation, a cell Calculations and a cell Output Processing. When you are editing an m-file, you can run the active cell (i.e. the cell containing your cursor) by using Ctrl+Enter.



Previous      Next      Up      Contents


Esteur 2010-03-22