S02 Numerical Methods 2024 Fall
S02 Numerical Methods 2024 Fall
2
Plotting Example
• t = [0:2:20]’;
g = 9.81; m = 68.1; cd = 0.25;
v = sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t);
plot(t, v)
3
Plotting Annotation Example
• title('Plot of v versus t')
xlabel('Values of t')
ylabel('Values of v')
grid
4
Plotting Options
• When plotting data, MATLAB can use several different
colors, point styles, and line styles. These are specified at
the end of the plot command using plot specifiers as found
in Table 2.2.
• The default case for a single data set is to create a blue line
with no points. If a line style is specified with no point style,
no point will be drawn at the individual points; similarly, if a
point style is specified with no line style, no line will be
drawn.
• Examples of plot specifiers:
– ‘ro:’ - red dotted line with circles at the points
– ‘gd’ - green diamonds at the points with no line
– ‘m--’ - magenta dashed line with no point symbols
5
Plotting Options
• plot(t, v, ‘o’)
• plot(t, v, ‘s--g’)
• plot(t,v,'--dc','LineWidth',2,...
'MarkerSize',10,...
'MarkerEdgeColor','k',...
'MarkerFaceColor','m')
• plot(t, v, t, v, 'o')
• >> plot(t, v)
>> hold on
>> plot(t, v, 'o')
>> hold off
6
Other Plotting Commands
• hold on and hold off
– hold on tells MATLAB to keep the current data plotted
and add the results of any further plot commands to the
graph. This continues until the hold off command,
which tells MATLAB to clear the graph and start over if
another plotting command is given. hold on should be
used after the first plot in a series is made.
• subplot(m, n, p)
– subplot splits the figure window into an mxn array of
small axes and makes the pth one active. Note - the first
subplot is at the top left, then the numbering continues
across the row. This is different from how elements are
numbered within a matrix!
See S02_P2_ex1.m 7
Plotting Options
back
8
Part 1
Chapter 3
Programming with
MATLAB
12
Script Files
• A script file is merely a set of MATLAB commands that are
saved on a file - when MATLAB runs a script file, it is as if
you typed the characters stored in the file on the command
window.
• Scripts can be executed either by typing their name (without
the .m) in the command window, by selecting the Debug,
Run (or Save and Run) command in the editing window,
or by hitting the F5 key while in the editing window. Note
that the latter two options will save any edits you have made,
while the former will run the file as it exists on the drive.
See scriptdemo.m
13
Function Files
• Function files serve an entirely different purpose from script
files. Function files can accept input arguments from and
return outputs to the command window, but variables
created and manipulated within the function do not impact
the command window.
14
Function File Syntax
• The general syntax for a function is:
function outvar = funcname(arglist)
% helpcomments
statements
outvar = value;
where
– outvar: output variable name
– funcname: function’s name
– arglist: input argument list - comma-delimited values that are
passed into the function
– helpcomments: text to show with help funcname
– statements: MATLAB commands for the function
15
Function File Syntax
See freefall.m
16
Variable Scope
function c = adder(a,b)
• a and b are called local
x=88 variables.
a
c = a + b
>> x = 1; y = 4; c = 8
>> d = adder(x, y)
>> c, x, a 17
Global Variables
global X Y Z
Example 3.3
J an 0.97 Tair 273.15 0.6 0.031 eair
4
[W/(m 2 s )]
17.27 Td
237.3Td
eair 4.596 e [mmHg]
J br 0.97 Tw 273.15
4
[W/(m 2 s )]
See GV_scrpt.m
18
Subfunctions
• A function file can contain a single function, but it can also
contain a primary function and one or more subfunctions
• The primary function is whatever function is listed first in the
M-file - its function name should be the same as the file
name.
• Subfunctions are listed below the primary function. Note
that they are only accessible by the main function and
subfunctions within the same M-file and not by the
command window or any other functions or scripts.
• >> freefallsubfunction(12,68.1,0.25)
• >> vel(12,68.1,.25)
19
Input
• The easiest way to get a value from the user is the input
command:
– n = input('promptstring')
MATLAB will display the characters in promptstring,
and whatever value is typed is stored in n. For example,
if you type pi, n will store 3.1416…
– n = input('promptstring', 's')
MATLAB will display the characters in promptstring,
and whatever characters are typed will be stored as a
string in n. For example, if you type pi, n will store the
letters p and i in a 1x2 char array.
20
Input
• >> m = input('Mass (kg): ')
• >> name = input('Enter your name: ','s')
21
Output
• The easiest way to display the value of a matrix is to type its
name, but that will not work in function or script files.
Instead, use the disp command
disp(value)
will show the value on the screen, and if it is a string, will
enclose it in single quotes.
• >> freefalli
Mass (kg): 68.1
Drag coefficient (kg/m): 0.25
Time (s): 12
Velocity (m/s):
22
50.6175
Formatted Output
• For formatted output, or for output generated by combining
variable values with literal text, use the fprintf command:
fprintf('format', x, y, ...)
where format is a string specifying how you want the value
of the variables x, y, and more to be displayed - including
literal text to be printed along with the values.
• The values in the variables are formatted based on format
codes.
23
Format and Control Codes
• Within the format string, the following format codes define
how a numerical value is displayed
%d - integer format
%e - scientific format with lowercase e
%E - scientific format with uppercase E
%f - decimal format
%g - the more compact of %e or %f
• The following control codes produce special results within
the format string:
\n - start a new line
\t – tab
\\ - print the \ character
• To print a ' put a pair of ' in the format string 24
Format and Control Codes
See fprintfdemo.m
25
Creating and Accessing Files
• MATLAB has a built-in file format that may be used to save
and load the values in variables.
• save filename var1 var2 ... varn
saves the listed variables into a file named filename.mat.
If no variable is listed, all variables are saved.
• load filename var1 var2 ... varn
loads the listed variables from a file named filename.mat.
If no variable is listed, all variables in the file are loaded.
• Note - these are not text files!
26
Creating and Accessing Files
• >> g=9.81;m=80;t=5;
• >> cd=[.25 .267 .245 .28 .273]';
• >> v=sqrt(g*m ./cd).*tanh(sqrt(g*cd/m)*t);
• >> clear
27
ASCII Files
28
ASCII Files
• >> A = [ 5 7 9 2; 3 6 3 9];
• >> save simpmatrix.txt -ascii
• >> B = load(‘simpmatrix.txt’)
See fprintfdemo2.m
29
Structured Programming
• Structured programming allows MATLAB to make decisions
or selections based on conditions of the program.
• Decisions in MATLAB are based on the result of logical and
relational operations and are implemented with if,
if...else, and if...elseif structures.
• Selections in MATLAB are based on comparisons with a
test expression and are implemented with switch
structures.
See grader.m
30
Relational Operators
• From Table 3.2: Summary of relational operators in
MATLAB:
31
Logical Operators
~x (Not): true if x is false (or zero); false otherwise
x & y (And): true if both x and y are true (or non-zero)
x | y (Or): true if either x or y are true (or non-zero)
32
Order of Operations
• Priority can be set using parentheses. After that,
Mathematical expressions are highest priority, followed by
relational operators, followed by logical operators. All things
being equal, expressions are performed from left to right.
• Not is the highest priority logical operator, followed by And
and finally Or
• Generally, do not combine two relational operators!
If x=5, 3<x<4 should be false (mathematically), but it is
calculated as an expression in MATLAB as:
3<5<4, which leads to true<4 at which point true is
converted to 1, and 1<4 is true!
• Use (3<x)&(x<4) to properly evaluate.
33
• a * b > 0 & b == 2 & x > 7 | ~(y > 'd')
• If a = -1, b = 2, x = 1, and y = 'b',
-1 * 2 > 0 & 2 == 2 & 1 > 7 | ~('b' > 'd')
34
Decisions
• Decisions are made in MATLAB using if structures, which
may also include several elseif branches and possibly a
catch-all else branch.
• Deciding which branch runs is based on the result of
conditions which are either true or false.
– If an if tree hits a true condition, that branch (and that
branch only) runs, then the tree terminates.
– If an if tree gets to an else statement without running
any prior branch, that branch will run.
• Note - if the condition is a matrix, it is considered true if and
only if all entries are true (or non-zero).
35
See mysign.m
36
Selections
• Selections are made in MATLAB using switch structures,
which may also include a catch-all otherwise choice.
• Deciding which branch runs is based on comparing the
value in some test expression with values attached to
different cases.
– If the test expression matches the value attached to a
case, that case’s branch will run.
– If no cases match and there is an otherwise statement,
that branch will run.
37
See freefall2.m
38
• >> nargin('freefall2')
39
Loops
• Another programming structure involves loops, where the
same lines of code are run several times. There are two
types of loop:
– A for loop ends after a specified number of repetitions
established by the number of columns given to an index
variable.
– A while loop ends on the basis of a logical condition.
40
for Loops
See factor.m
41
Vectorization
• Sometimes, it is more efficient to have MATLAB perform
calculations on an entire array rather than processing an
array element by element. This can be done through
vectorization.
42
Preallocation of Memory
• MATLAB automatically increases the size of arrays every
time you add a new element. This can become time
consuming when you perform actions such as adding new
values one at a time within a loop.
for loop Vectorization
t = 0:.01:5; t = 0:.01:5;
for i = 1:length(t) y = ones(1, size(t));
if t(i)>1 for i = 1:length(t)
y(i) = 1/t(i); if t(i)>1
else y(i) = 1/t(i);
y(i) = 1; end
end end
43
end
while Loops
• A while loop is fundamentally different from a for loop
since while loops can run an indeterminate number of
times. The general syntax is
while condition
statements
end
where the condition is a logical expression. If the
condition is true, the statements will run and when that
is finished, the loop will again check on the condition.
• Note - though the condition may become false as the
statements are running, the only time it matters is after all
the statements have run.
44
Early Termination
• Sometimes it will be useful to break out of a for or while
loop early - this can be done using a break statement,
generally in conjunction with an if structure.
• Example:
x = 24
while (1)
x = x - 5
if x < 0, break, end
end
will produce x values of 24, 19, 14, 9, 4, and -1, then stop.
45
• Crtl+C or Crtl+Break
• for n = 3:10
mesh(magic(n))
pause
end
46
Animation
• There are two simple ways to animate a plot in MATLAB.
First:
– Important to use the axis command so that the plots scales are
fixed.
47
Animation
• The general syntax for movie is:
movie(m, n, fps)
where
– m: the vector or matrix holding the sequence of frames constituting
the movie
– n: an optional variable specifying how many times the movie is to
be repeated (if it is omitted, the movie plays once)
– fps: an optional variable that specifies the movie’s frame rate (if it is
omitted, the default is 12 frames per second).
48
Example 3.6
See example3_6.m
49