0% found this document useful (0 votes)
26 views33 pages

CH 03

Uploaded by

wjdalscks0204
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views33 pages

CH 03

Uploaded by

wjdalscks0204
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Chapter 3.

Programming with
MATLAB

Prof. Kiho Park

Numerical Methods 1
M-Files
• MATLAB allows you to put commands in text files
called M-files.
– The files are stored with a .m extension
• There are two main kinds of M-file
– Script files
– Function files

Numerical Methods 2
M-Files: Script Files
• A script file is merely a set of MATLAB commands
that are saved on a file.
• Scripts can be executed either
– by typing their name in the command window, or
– by invoking the Debug, Run command in the edit
window.

Numerical Methods 3
M-Files: Script Files – Ex. 3.1
Edit g=9.81; m=68.1; cd=0.25; t=12;
scriptdemo.m
Window v=sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t)

>> scriptdemo
v=
50.6175

M-files should be run (or


called)
at the directory (current folder)
where M-files are saved.
Numerical Methods 4
M-Files: Function Files
• Function files can accept input arguments from and
return outputs to the command window
• Variables are created and manipulated within the
function.
function outvar = funcname(arglist)
% helpcomments
statements
outvar = value;

Numerical Methods 5
M-Files: Function Files – Ex 3.2

Edit function v = freefallvel(t, m, cd)


Window %freefallvel: bungee velocity with second-order drag
%v=freefallvel(t,m,cd) computes the free-fall velocity
% of an object with second-order drag
%input:
%t=time(s)
%m=mass(kg)
%cd=second order drag coefficient (kg/m)
%output:
%v=downward velocity (m/s)
g=9.81; %acceleration of gravity
v=sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t);

freefallvel.m

Numerical Methods 6
M-Files: Function Files – Ex 3.2

>> freefallvel(12, 68.1, 0.25)


ans =
50.6175

>> freefallvel(8, 100, 0.25)


ans =
53.1878

Numerical Methods 7
M-Files: Returning more than one results

Edit function [mean, stdev] = stats(x)


stats.m
Window n=length(x);
mean=sum(x)/n;
stdev=sqrt(sum((x-mean).^2/(n-1)));

>> y=[8 5 10 12 6 7.5 4];


>> [m,s] =stats (y)
m=
7.5000
S=
2.8137

Numerical Methods 8
M-Files: Subfunctions
• Functions can call other functions.
– Main or primary function: It is the only function that is
accessible to the command window and other functions
and scripts.
– A subfunction is only accessible to the main function and
subfunctions within the same M-file.

Numerical Methods 9
M-Files: Subfunctions
• example

function v= freefallsubfunc(t, m, cd)


v=vel(t, m, cd); Main function
end

function v=vel(t, m, cd)


g=9.81;
subfunction
v=sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t);
end

Numerical Methods 10
Input-Output
• input function
n = input('promptstring')
n = input('promptstring‘, ‘s’)

• disp function
disp (value)

Numerical Methods 11
Input-Output
• fprintf function
fprintf('format', x, …)

e.g.
>> fprintf(‘The velocity is %8.4f m/s \n’, velocity)

%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
\n - start a new line
\t – tab
Numerical Methods 12
Input-Output: Ex 3.3
Edit Window

function freefalli
>> freefalli
g=9.81; Mass (kg): 68.1
m=input('Mass(kg):'); Drag coefficient (kg/m): 0.25
cd=input('Drag Coefficient(kg/m):’);
Time (s): 12
t=input('Time(s):');
disp(' ')
disp('Velocity (m/s):') Velocity (m/s):
disp(sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t)) 50.6175
The velocity is -50.6175 m/s
v1= -sqrt(g*m/cd)* tanh(sqrt(g*cd/m)*t);
fprintf('The velocity is %8.4f m/s\n’, v1)

Numerical Methods 13
Structured Programming
• MATLAB includes statements allowing programs to
take non-sequential paths.
– Decisions (or Selection): The branching of flow based on a
decision
– Loops (or Repetition): The looping of flow to allow
statements to be repeated.

• The if structure
if condition
statements
end

Numerical Methods 14
Structured Programming: Decisions
function
Edit grader(grade)
Window if grade >= 60
disp('passing
grade:')
disp(grade)
end

>> grader(95.6)
passing grade:
95.6000

Numerical Methods 15
Structured Programming: Decisions
• Error function
Error (msg)

• Relational operators
Example Operator Relationship
x == 0 == Equal
unit ~= ~= Not equal
‘m’
a < 0 < Less than
s > t > Greater than
3.9 <= a/3 <= Less than or equal to
r >= 0 >= Greater than or equal to
Numerical Methods 16
Structured Programming: Decisions
• Logical conditions
~ (Not)
& (And)
| (Or)
• The order of priority
– Parentheses > mathematical expressions > relational
operators > logical operators (Not > And > Or)
– When all things are equal,
expressions are performed from left to right.

Numerical Methods 17
Structured Programming: Decisions

Numerical Methods 18
Structured Programming: Decisions
• The if…else structure
if condition
statements1
else
statements2
end

• The if…elseif structure


if condition1
statements1
elseif condition2
statements2
:
else
statementsN
end Numerical Methods 19
Structured Programming: Decisions
• Example 3.4. For a scalar, the built-in MATLAB sign function
returns the sign of its argument (−1, 0, 1). Develop an M-file
to perform the same function.

Edit Window

function sgn = mysign(x) >> mysign(25.6)


ans =
1
if x > 0
sgn = 1; >> mysign(-0.776)
elseif x < 0 ans =
sgn = -1; -1
else
sgn = 0; >> mysign(0)
ans =
end
0
Numerical Methods 20
Structured Programming: Decisions
• The switch structure
switch testexpression
case value1
statements1
case value2
statements2
:
otherwise
statementsN
end

Numerical Methods 21
Structured Programming: Loops
• The for…end structure
for index = start:step:finish
statements
end
• Example 3.5
function fout = factor(n)
>> factor(5)
x = 1; ans =
for i=1:n 120
x = x * i;
end
fout = x;
end

Numerical Methods 22
Structured Programming: Loops
• Vectorization

for structure Vectorization


i = 0; t = 0:0.02:50;
for t = 0:0.02:50 y = cos(t);
i = i + 1;
y(i) = cos(t);
end

Numerical Methods 23
Structured Programming: Loops
• The while structure
while condition
statements
end

• The while … break structure


while (1)
statements
if condition, break, end
statements
end
• The pause command

Numerical Methods 24
Structured Programming: Loops
• The while structure

>> x = 8
x=
>> 8 x=8
x>>= while x > 0
8 x = x - 3;
>> while disp(x)
x>0
end x = x - 3;
5disp(x)
2 end
-1

Numerical Methods 25
Structured Programming: Loops
• The while … break structure

>> x= 0.24
x=
0.2400
>> while(1)
x = x - 0.05
if x<0, break, end
end
x=
0.1900
x=
0.1400
x=
0.0900
x=
0.0400
x=
-0.0100
Numerical Methods 26
Nesting and Indentation
• Structures can be nested within other structures.

• Example 3.7 Nesting structures

2
f ( x) ax  bx  c
2
 b  b  4ac
x
2a
– Develop a function to implement this formula given values
of the coefficients.
Numerical Methods 27
Nesting & function quadroots(a, b, c)

Indentation
• Ex 3.7

end
Numerical Methods 28
Passing Functions to M-files
• Anonymous functions: simple functions without
creating an M-file.
fhandle = @(arg1, arg2, …) expression

>> outvar =feval('cos',pi/6)


>> fl = @(x,y) x^2 + y^2;
>> fl (3,4)
ans =
25

Numerical Methods 29
Passing Functions to M-files
• inline functions
f1 = inline('expression', 'arg1', 'arg2',…)

>> f1 =inline('x^2 + y^2', 'x', 'y')


f1 =
inline function:
f1(x,y) = x^2 + y^2
>> f1(3,4)
ans =
25

Numerical Methods 30
Passing Functions to M-files
• Function functions are functions that operate on
other functions which are passed to it as input
arguments.
– e.g. built-in function fplot fplot(func, lims)

>> vel= @(t)…


sqrt(9.81*68.1/0.25)*tanh(sqrt(9.81*0.25/68.1)*t);
>> fplot(vel, [0 12])

Numerical Methods 31
Passing Functions to M-files
• Ex 3.7 Building and implementing a Function Function:
– Develop an M-file function function to determine the average value of
a function over a range. Illustrate its use for the bungee jumper
velocity over the range from t = 0 to 12 s:
gm  gm 
v(t )  tanh  t 
Cd  C d 
>> vel= @(t)…
sqrt(9.81*68.1/0.25)*tanh(sqrt(9.81*0.25/68.1)*t);
function favg = funcavg(f, a, b, n)
x = linspace(a,b,n); >> funcavg(vel, 0, 12, 60)
y=f(x); ans =
favg=mean(y);
36.0127
>> funcavg(@sin, 0, 2*pi, 180)
ans =
-6.3001e-017

Numerical Methods 32
Summary
• What we have learned…
– Creation of M-files in the edit window and its use from the
command window.
– Script and function files
– Sub-functions
– Structured programming
– if…elseif and switch structures
– for…end and while structures
– Passing function to M-files

Numerical Methods 33

You might also like