Develop Good Problem-Solving Strategies.: Program Development
Develop Good Problem-Solving Strategies.: Program Development
Program Development
One very big advantage of Matlab over other programming language is the
possibility of designing your own toolbox to be added to existing ones like
SIMULINK, the Symbolics toolbox, and the Controls toolbox. Matlab is a useful
environment to develop software tools to solve relatively complicated
mathematical problems.
The logical steps (blocks or modules) that are finally transcribed into the
MATLAB codes and saved as M-files in your work directory are the primary
and most useful goals of users of tools like MATLAB. More so, there are
numerous toolboxes available that can be purchased from MathWorks
(www.mathworks.com) or other sources to use with Matlab to solve a variety
of engineering and scientific problems.
The important goals of software tools design are that it works, and can easily
be read and understood. That way, it can be systematically modified when
required. For programs to work well they must satisfy the requirements
associated with the problem or class of problems it is intended to solve. The
detailed description of the problem to be solved, inputs, method of
1
processing, outputs and any other special requirements, must be known by
the designer. The program must work completely and correctly, i.e. all
options should be usable without error within the limitations of the
specifications. It must be readable and, hence, clearly understandable. Thus,
it is useful to decompose major tasks (or the main program) into subtasks (or
subprograms) that do specific parts of the main task. It is much easier to
read subprograms that have fewer lines, than one large main program that
doesnt segregate the subtasks effectively, particularly if the problem to be
solved is relatively complicated. Each subtask should be designed so that it
can be evaluated independently before it is incorporated into the larger main
program. A well-written code, when it works, is much more easily evaluated
in the testing phase of the design process. If changes are necessary to
correct sign mistakes and the like, they can be implemented easily. One
thing to keep in mind is adding information about the program. This is done
by comments. Ensure to add enough comments and references so that a
year the program is written, you will know exactly what was done and for
what purpose. Also note that the first few comment lines in a script are
displayed in the command window when you type help followed by the name
of your file, thus naming your files well, is also an art.
3
The time txmax from launch for the projectile to reach xmax is given by
at
For this problem the horizontal distance traveled when the object reaches
the maximum altitude is xymax=xmax/2.
The trajectory (or flight path) is described by the following pair of coordinates
at any given instant of time is given by
We need to solve these equations over the range of time 0 <t <=tmax for
prescribed launch conditions V>0 and 0 <<=/2. Then the maximum value
of the altitude and the range are computed along with their respective
arrival times. Finally, we want to plot V versus , where
Step 3: The required inputs are g, Vo, , and a finite number of time steps
between t =0 and the time the object returns to the ground. The outputs are
the range and time of flight, the maximum altitude and the time it is
reached, and the shape of the trajectory in graphical form.
Steps 4&5: The structural plan developed to solve this problem is given as a
MATLAB program. This is because it is a realitively straightforward problem
and the translation to MATLAB codes is easily. The steps of the structure plan
4
are enumerated. This plan and the M-file, of course, is the final result
developed after trying a number of approaches during the design phase.
%
% The proctile problem with zero air resistance
% in a gravitational field with constant g.
%
% Written by D. T. Valentine ........ september 2006
% An eight-step structure plan applied in MATLAB:
%
% 1. Definition of the input variables.
%
g = 9.81; % Gravity in m/s/s.
vo = input(What is the launch speed in m/s?)
tho = input(What is the launch angle in degrees?)
tho = pi*tho/180; % Conversion of degrees to radians.
%
% 2. Calculate the range and duration of the flight.
%
txmax = (2*vo/g) * sin(tho);
xmax = txmax * vo * cos(tho);
%
% 3. Calculate the sequence of time steps to compute trajectory.
%
dt = txmax/100;
t = 0:dt:txmax;
%
% 4. Compute the trajectory.
%
x = (vo * cos(tho)) .* t;
y = (vo * sin(tho)) .* t - (g/2) .* t.2;
%
% 5. Compute the speed and angular direction of the
projectile.
% Note that vx = dx/dt, vy = dy/dt.
%
vx = vo * cos(tho);
vy = vo * sin(tho)-g.*t;
v = sqrt(vx.*vx + vy.*vy);
th = (180/pi) .* atan2(vy,vx);
%
% 6. Compute the time, horizontal distance at maximum altitude.
%
tymax = (vo/g) * sin(tho);
xymax = xmax/2;
ymax = (vo/2) * tymax * sin(tho);
%
5
% 7. Display ouput.
%
disp([Range in m = ,num2str(xmax), Duration ins=,
num2str(txmax)])
disp( )
disp([Maximum altitude in m = ,num2str(ymax), Arrival
ins=,num2str(tymax)])
plot(x,y,k,xmax,y(size(t)),o,xmax/2,ymax,o)
title([Projectile flight path, vo =,num2str(vo),
th =, num2str(180*th/pi)])
xlabel(x), ylabel(y) % Plot of Figure 1.
figure % Creates a new figure.
plot(v,th,r)
title(Projectile speed vs. angle)
xlabel(V), ylabel(\theta) % Plot of Figure 2.
%
% 8. Stop.
%
6
The example just seen is a Matlab program which receives input data from a
user, performs simple arithmetic operations on the data, and displays the
results of the computation in a comprehensible form. However, more
interesting problems in science and engineering are likely to involve special
mathematical functions like sines, cosines, logarithms, etc. These will be
seen later
7
Chapter 4
Functions
>> cumsum(1:4)
ans=
[1 3 6 10].
9
Considering examples with the arc-cosine, the arc-sine and the arctangent
functions, i.e. acos(x), asin(x) and atan(x), respectively. If we specify x
between -1 and 1, what quadrant of the circle are the output angles
selected? The following M-file is proposed.
%
% Script to compare the acos(x), asin(x), and atan(x)
% functions over the range -1<x<1.Thevalues are
% converted to angles in degrees. The results are
% compared graphically.
% Script prepared by D. T. Valentine - September 2006.
% The question raised is: What range of angles, i.e.
% which of the four quadrants of the circle from 0 to
% 2*pi are the angular outputs of each of the functions?
%
% Determine the values of x to be examined:
%
x = -1:0.001:1;
% Compute the arc-functions:
%
y1 = acos(x);
y2 = asin(x);
y3 = atan(x);
%
% Convert the angles from radians to degrees:
%
y1 = 180*y1/pi;
y2 = 180*y2/pi;
y3 = 180*y3/pi;
%
% Plot the results:
%
plot(y1,x,y2,x,y3,x),grid,legend(asin(x), acos(x),
atan(x))
xlabel(\theta in degrees),ylabel(x, the argument of
the function)
% REMARKS: Note the following:
% (1) The acos(x) varies from 0 to 90 to 180 degrees.
% (2) The asin(x) varies from -90 to 0 to 90 degrees.
% (3) The atan(x) varies from -45 to 0 to 45 degrees.
%
% Stop
10
4.2 Importing and Exporting Data
Text formats are very useful, because they very portable and can be read
and written by many different applications. They will be introduces here.
The save and load commands are probably the best commands to use in
saving data between MATLAB sessions.
in delimited ASCII format in the file myData.txt (creating it) use the
command
11
>> save ascii myData.txt A
If you view myData.txt in a text editor (or type it in the Command Window) it
looks like this:
Delimiters are the characters used to separate the data values in the file .i.e.
spaces by default. You can use tabs instead of spaces by specifying the tabs
qualifier instead of -ascii. If you save character arrays (strings) in this way,
the ASCII codes of the characters are written to the file.
B=
4 5 6
7 8 9
>> save -tabs mytext.txt B
__________IM____,___xc``_b6
3_13_3___R____
(Quite incomprehensible huh!)
The load command is the reverse of save, but has a curious twist in the
syntax. If the array A has been saved in myData.txt as in the above
command, then
load myData.txt
creates a variable in the workspace with the same name as the file, minus
the extension, i.e. myData. If you dont want the filename as the variable
name use the functional form of the command, e.g.
>> A = load(myData.txt)
A=
1 2 3
4 5 6
Data imported in this way doesnt have to be created by MATLAB. You can
create it in a text editor, or it could be created by any other program that
exports data in ASCII format.
save x y z
ekepata will be seen in a Matlab folder as a matlab file with extension .mat
Note:
If no variables are listed the entire workspace is saved.
The extension .mat is the default extension but you can specify a
different extension.
The command
load filename
The MATLAB Import Wizard is the easiest way of importing data into the
workspace during an interactive session.
Start the Import Wizard by selecting Import Data on the MATLAB File
menu. You can also use uiimport on the command line to start it. A list
of files appears in a dialogue box. Open the file you want to import.
Select the delimiter used in the text file (if necessary). Click Next.
Select the variables you want to import. By default the Import Wizard
puts all the numeric data in one variable and all the text data in other
variables, but you can choose other options.
Click Finish to import the data into the selected variables.
13
To import binary data with the Import Wizard, start it in the same way as
when importing text data. When the file opens the Import Wizard attempts to
process its contents and creates variables depending on the type of data in
the file. Check the variables you want to import and click Finish to create the
selected variables. You can, for example, import data from an Excel
spreadsheet in this way. If the data are numeric with row and column
headers, the Import Wizard imports the numeric data into a numeric array
and the headers into a cell array.
MATLAB has a set of low-level file I/O (input/output) functions based on the
I/O functions of the ANSI Standard C Library. Low-level file I/O functions allow
the most direct control over reading or writing data to a file. However, these
functions require that you specify more detailed information about your file.
You would typically use these functions to access binary data written by C or
Java programs, for example, or to access a database which is too large to be
loaded into the workspace in its entirety.
Files can be accessed with these functions in text or binary mode. In binary
mode you can think of the file as a long continuous stream of bytes, which
are your responsibility to interpret correctly. Files opened in binary mode can
be accessed randomly, i.e. you can specify at which particular byte you
want to start reading or writing.
fscanf: reads formatted data in a text or ASCII file; that is, a file you can view
in a text editor.
fgetl and fgets: reads one line of a file at a time, where a newline character
separates each line.
fread : reads a stream of data at the byte or bit level
fopen: opens a file
fclose:closes a file
Finally, the diary command can also be used to export small arrays as text
data, although you will need to edit out extraneous text.
14