Sunteți pe pagina 1din 50

WIDENER UNIVERsITY School of Engineering

Third Edition
Tradition & Excellence since 1821 Mechanical Engineering

TOPIC

01
ENGR 680
Advanced Computational
Methods

Introduction to MATLAB

© Tulong Zhu, All rights reserved.


Introduction to MATLAB
• MATLAB is a powerful software tool developed by the
Mathworks for mathematical computations
– “Mat”rix “Lab”oratory --- started as matrix and linear algebra tool
– Widely used in academia and industry
– Many Mathworks & 3rd party application specific “toolboxes”
available
Start MATLAB (The Default View)
Start MATLAB: Summary of Windows and Button
Windows Purpose How to View
Main window, enters commands, View>Command
Command Window Window
variables, runs programs.
Output from graphic commands
Figure Window Automatically
(automatically appear).
Creates and debugs script and File>New>M-file
Editor Window File>Open
function files (.m files).
Provides information about
Workspace Window View>W orkspace
variables that are used.
Help Window Provides help information. View>Help
Provides access to tools, demos, &
Launch Pad Window View>Lunch Pad
documentation.
Command History Logs commands entered in the View>Command
Window Command Window. Histiry
Current Directory Shows the files in the current View>Current
Window directory. Directory
Allows a user to access matlab
Start Button Click to use
tools, desktop tools, help files, etc.
Working in the Command Window: The Main Window

Usage - Define variables - Execute commands


- Open other windows - Run program (Script files)
- Manage the Software - More…

Notes • To type a command the cursor must be next to the command


prompt (>>) (or ?? For the student version)
• Once the command is typed and the Enter key is pressed, the
command is executed.
• Several commands can be typed in the same line, using a “,”
between commands.
• It is impossible to go back to a previous line in the the
Command Window.
• A previous typed command can be recalled using the “” and
the “” keys.
• If a command is too long to fit in a line, it can be continued to
the next line by typing three periods, … (an ellipsis).
Working in the Command Window: Some Commands
The “ ; ” • If a semicolon (;) is added at the end of a command, the output of
the command is not displayed.

The “ % ” • Anything after the percent symbol (%) in a line is designated as a


comment.
• MATLAB will ignore all comments when the program is running.

The clc • The clc Command clears the Command Window. It will not
Command change anything that was done before.

The help • The help Command displays the description of the command
Command with instructions.
help command_name

For Example,
help sin

SIN sine.
SIN(X) is the sine of the elements of X.
MATLAB Variables
Variable • A variable is a name made of a letter or combination of letters
(and digits), and is assigned a numerical value (for numerical
variable) or character string (for string variable) .
Define a • The assignment (replacement) operator, =, is used to assign a
Variable value to a variable:
variable_name = A value, or a computable expression
a = 1;
b = a^2 + 1 + sin(a);
name = 'John Doe';
d = input(‘Please input d'); (keyboard input)
• A variable must be defined (initialized) before it can be used.
some other programs may have a default initialization (e.g., 0),
but MATLAB does not.
• To assign an character string to a variable, the character string
should be enclosed in single quotes.
 If the character string already contains the single-quote
character, that quote can be specified by two single quotes:
answer = 'I don''t know'
MATLAB Variables: The Assignment Operator, =
The • The assignment operator, =, works differently than the equals
Assignment sign (=) we know from mathematics.
Operator, =  For a simple case like a=1, the usage is practically no
different than in mathematics. However, it really means to
assign a value 1 to the variable a to replace the original value
in a (if there is one).
 We cannot switch both sides of the expression a=1 to have
1=a in MATLAB, which is OK in mathematics.
 We can have something like a = a+1 in MATLAB, which
tells the computer to add 1 to the current value of a. However,
in mathematics, it is an invalid equation.

• In summary, the assignment operator, =, replaces the value of the


variable with the new value generated by the right-hand side
expression, hence the name of “replacement” operator.
• The left-hand side of = must be one and only one variable, and
the right-hand side must be a number or computable expression.
MATLAB Variables: Rules
Rules • Can be up to 63 (V6.5) characters long (31 characters in v6.0).

• Can contains letters, digits, and underscore character.

• Must begin with a letter.


• Case sensitive. For example, AA, Aa and aA are different variables.

• Avoid using built-in functions, e.g., cos, sin, exp, sqrt, abs, …

• Avoid using the Predefined Variables:


 ans A variable that has the value of the last expression that
was not assigned to a specific variable.
 pi The number .
 eps Smallest distance between two numbers = 2^(-52).
 inf Used for infinity.
 i, j 1
 NaN Stands for Not-a-number. For example, 0/0.
Mathematical Operation with Scalar Variable
+, – , • MATLAB uses “+”, “–”, “*”, “/”,”\”, and “^” for addition,
* , /, \, ^ subtraction, “multiplication”, “division”, and “exponentiation
(power)”.

Symbol Description MATLAB form


+ Addition: a + b a + b
– subtraction: a – b a - b
* Multiplication: ab a * b
a
/ Right division: a / b
b
b
\ Left division: a \ b
a
^ Exponentiation: ab a ^ b

Precedence • MATLAB evaluates an expression in an order similar to what we


have used in mathematics: from left to right, from “^” to “*, / and
\” and finally to “+ and –” .
• Parentheses can be used to alter the above order. To avoid
mistakes and to improve readability of your codes, feel free to use
parentheses.
Useful Commands for Managing Variables
The clear • clear removes all variables from the memory.
Command • clear x y z removes x, y and z from the memory.

The who • The who Command displays a list of variables currently in the
Command memory.

The whos • The whos Command displays a list of variables currently in the
Command memory and their size together with information about their bytes
and class.
The save save fname stores all variables in MATLAB Binary
Command format in the MAT-file fname.mat in
the current directory.
save fname x stores the variables x in MATLAB Binary
format the file fname.mat in the current
directory.
The load load fname loads all variables in the file
Command fname.mat into the workspace.
load fname x loads the variables x in the file
fname.mat into the workspace.
More on the save and load Commands
The MAT- • The save and load commands save and load data in a special
file compact format that preserves many details, such as the name and
type of the variable, etc.
• The MAT-file created by the save command on any platform can
be read on any other platform which runs MATLAB.
• However, the MAT-file is in a format that cannot be read by other
programs.
• If data must be shared with other programs, then the data must be
saved in ASCII format by adding -ascii option.
save fname.dat x -ascii
saves the variable x in the file fname.dat in ASCII format.
 The extension of the file name must be specified.
Notes • If the data is saved in ASCII format, the special information, such
as the variable names and types, is lost.
• If data must be exchanged between MATLAB and other
programs, save the data in ASCII format. If the data will only be
used in MATLAB, save the data in MAT-file format.
Displaying Output Data
Default • MATLAB automatically displays the result of an expression
Format without a “;” in the Command Window using a default format as
follows:

 Integer values are always displayed as integers.

 Character values are always displayed as characters.

 Other values (real values and complex values) are displayed


with four digits after the decimal point, in a decimal notation
or scientific notation.

Change • We may need more digits after the decimal point, or we may want
Format see the data in a different format.
• The default format can be changed using the format command.
A summary of the command is displayed on the next Slide
Display Output Data: Change Formats
Command Description Example (>>290/7)
format short Fixed-point with 4 decimal digits for 41.4286
0.001<=number<=1000
Otherwise display format short e
format Long Fixed-point with 14 decimal digits for 41.4285714285714
0.001<=number<=100
Otherwise display format long e
format short e scientific notation with 4 decimal digits 4.1429+e001
format long e scientific notation with 15 decimal digits 4.142857142857143+e001
format short g Best of 5-digit fixed or floating point 41.429
format long g Best of 15-digit fixed or floating point 41.4285714285714
format bank Two decimal digits 41.43
format compact Eliminates empty lines to allow more lines displayed on the screen
format loose Adds empty lines (opposite of compact)

Note: The displaying format does not affect how MATLAB computes and stores numbers
Displaying Output Data: Other Commands
The disp • disp(x) displays the array (matrix or vector), without printing
Command the array name.
 The disp Command accepts only one argument, i.e., it can
only display one array (vector, matrix) at a time.
 The disp Command only displays data on the screen.
The • fprintf can display one or more values with related text,
fprintf according to the user-defined format.
Command
 The fprintf Command can display data on the screen or
write the data to a file.
 The general form of the fprintf Command is
fprintf(fid,format,data,…)
 fid: file identifier if the data is written to a file.
If fid is missing, the data will be displayed on
the screen.
 format: format describing how the data is to be printed.
 data: the data to be printed (displayed).
More on the fprintf Command: the format
Example • >> fprintf('The value of pi is %f\n',pi)

Text String Format New line


• It prints the text “The value of pi is”, and the variable pi at
the location of the format %f, according to the format %f:
>> The value of pi is 3.141593
Format Format Results
%d Display value as an integer
%e Display value in exponential format
%f Display value in floating point format # decimal places
%g Display value in either floating or
exponential format, whichever is shorter Width
\n Skip to a new line
Notes • We can specify the width of the field in which the number will
display, and the number of decimal places to display, by inserting
the width and precision between % and f:
fprintf('The value of pi is %8.2f\n',pi)
The value of pi is 3.14
fprintf Command: Example
Example • Display the following result using the fprintf command
ID xx yy xy
1 0.8415 0.5403 1.5574
2 0.9093 -0.4161 -2.1850
3 0.1411 -0.9900 -0.1425
4 -0.7568 -0.6536 1.1578
5 -0.9589 0.2837 -3.3805

Matlab ID=[1 2 3 4 5]';


stress=[0.8415 0.9093 0.1411 -0.7568 -0.9589;...
0.5403 -0.4161 -0.9900 -0.6536 0.2837;...
1.5574 -2.1850 -0.1425 1.1578 -3.3805]';
fprintf('\nID s_xx s_yy t_xy\n')
for i = 1:5
fprintf('%2d %8.4f %8.4f %8.4f\n',ID(i),stress(i,:))
end

Display ID s_xx s_yy t_xy


1 0.8415 0.5403 1.5574
2 0.9093 -0.4161 -2.1850
3 0.1411 -0.9900 -0.1425
4 -0.7568 -0.6536 1.1578
5 -0.9589 0.2837 -3.3805
Create One-Dimensional Arrays (Vector Variables)
1D Array • A 1D array is a list of numbers placed in a row or column – A
Vector variable, e.g., [1 2 3].
How to 1. variable_name=[ type vector elements], e.g.,
Create 1 D x = [2 4 6 8 10];
Arrays
2. variable_name=[x1:d:x2] or
variable_name=x1:d:x2
x1 = first term, d = spacing, and x2 = last term, e.g.,
x=1:2:13
x=
1 3 5 7 9 11 13

3. variable_name=linspace(x1,x2,n)
x1= first term, x2= last term, and n= number of elements, e.g.,
x=linspace(0,8,6)
x=
0 1.6000 3.2000 4.8000 6.4000 8.0000
4. Programming. (see Vector.m)
Create Two-Dimensional Arrays (Matrix Variables)
2D Arrays • A 2D has numbers placed in rows and columns – A Matrix
variable, e.g., 1 2 3
3 4 5
How to variable_name=[1st row;2nd row;…;last row] :
Create 2D
• x=[1 2 3;3 4 5]
Arrays
x=
1 2 3
3 4 5
• x=[1:2:7;linspace(10,40,4);67 2 45 8]
x =
1 3 5 7
10 20 30 40
67 2 45 8

Notes • Unlike in most programming languages, there is no need to define


the size of the array before the elements are assigned.
• An array can be changed to be any size or type, by adding or
deleting elements.
Mathematical Operation with Array
+, – , * , ^ • The operations of + (addition), – (subtraction), * (multiplication),
and ^ (exponentiation) are executed by MATLAB according to
the rules of matrix operations in linear algebra.
inv, det • inv(A) and det(A) gives the inverse matrix and determinant of A.
.*, .^ , ./, .\ • Element-by-element multiplication, division, and exponentiation
of two vectors or matrices are executed by MATLAB using the
.*, ./, .\ and .^ operators, e.g.,
 If a=[a1 a2 a3], then a^2 is not operable,
but a.^2=[a1^2 a2^2 a3^2] .
 If a=[a1 a2 a3], and b=[b1 b2 b3], then a*b is not
operable, but a.*b=[a1*b1 a2*b2 a3*b3] .
 If a=a11 a12 a13, and b= b11 b12 b13
a21 a22 a23, b21 b22 b23,
then a*b and a/b are not possible, but
a.*b=a11*b11 a12*b12 a13*b13
a21*b21 a22*b22 a23*b23
a./b=a11/b11 a12/b12 a13/b13
a21/b21 a22/b22 a23/b23
script Files (.m files)
Why m files • The commands typed in the Command Window can NOT be
saved, edited, and reused. A script file can!
m files: • A script (m) file is a sequence of MATLAB command, also called
a program or an m file as the extension .m is used
• When a script file runs, MATLAB executes the commands in the
order they are written just as if they were typed in the Command
Window.
• When a script file has a command that generates an output, the
output is displayed in the Command Window or Picture Window.
• Script files can be created using File > New > M file
Run an m • In the Command Window: Type the filename to run (The file
file must be in the Current Directory or in the search path).
 The current directory can be changed from the Current
Directory Window, or by typing CD directory_name in
the Command Window.
 The search path can be added or deleted in the set Path
Window that can be opened from File > Set Path
• Click the Run icon ( ) from the Editor Window.
Two-Dimensional Plots: The plot Command
plot • The plot(x,y) command is used to create two-dimensional plots
using two vectors x and y. Additional options can be used to specify
the color, and style of lines and type of markers:
plot(x,y,'linespecifiers','PropertyName',PropertyValue)

Example x = -10:1:10;
y = x.^2;
plot(x,y,'--ro','linewidth',2,'markersize',12)
Two-Dimensional Plots: The fplot Command
fplot • The fplot command is used to create a given function:
fplot('function',[limits],'line specifiers')
Example fplot('x^2+4*sin(2*x)-1',[-3,3],'-b+')

Note • The fplot command automatically determine the vectors x and


y and use plot to create the graphics.
• Properties such as the line width, marker size, etc. can not be
changed using the fplot command.
Plot Multiple Graphs in the Same Plot
plot plot(x,y,u,v,t,h) plots three graphics (x,y), (u,v) & (t,h) in
one single plot.

Hold on hold on starts the process to add graphics to the previous plot.
Hold off hold off stops the above process.

line line(x,y) adds graphics to the previous plot.

Note • For the first approach plot(x,y,u,v,t,h), we can't specify


different properties, such as the line width, marker size, etc.

• For line(x,y), no line specifier (color, marker type, etc.) nor


line property (line thickness, marker size, etc.) can be used.

• We can always combine the hold on command and the plot


command (to plot only one curve a time) to plot multiple graphs
in the same plot. This way, we can change the color, type of the
line and marker, the line width, marker size, etc.
Plot Multiple Graphs: plot
Example Plots y = sin(x) and z = cos(x) in the same plot.
x=0:0.1:2*pi;
y=sin(x);
z=cos(x);
plot(x,y,'-ro',x,z,'--b+')

Note • Can not change line


width, marker size,
etc., using
'linewidth',
'markersize',
etc.
Plot Multiple Graphs: line
Example Plots y = sin(x) and z = cos(x) in the same plot.
x=0:0.1:2*pi;
y=sin(x);
z=cos(x);
plot(x,y,'-ro','linewidth',2,'markersize',6)
line(x,z)
Note • Can not add line
specifiers such as
'-bo' and line
properties, such as
'linewidth',
'markersize',
etc. in the line
command.
Plot Multiple Graphs: hold on with plot
Example Plots y = sin(x) and z = cos(x) in the same plot.
Use hold on x=0:0.1:2*pi;
& plot y=sin(x);
z=cos(x);
plot(x,y,'-ro','linewidth',2,'markersize',6)
hold on
plot(x,z,'--b+','linewidth',2,'markersize',6)
hold off

Note • Best approach .


Formatting a Plot: Using Command
xlabel xlabel('text as string') places a label under the x axis.
ylabel ylabel('text as string') places a label besides the y axis.
title title('text as string') adds a title to the top of the plot.
text text(x,y,'text as string') adds a text label in the plot at
the point with the coordinates x, y.
legend legend('string1','string2',…,pos) places legends in the
plot, at a location determined by the option pos.
axis axis([xmin,xmax,ymin,ymax])
sets the limits of the x and
y axes.

Example see Plots.m


Formatting a Plot: Using the Plot Editor
A plot can be formatted interactively in the Figure Window by clicking on the plot
and /or using the menus.
Click here to start Use these buttons to
the plot edit mode add text, arrows & lines

Use the Edit and Insert


menus to add formatting
objects, or to edit
existing objects

Change position of
labels, legends and
other objects by
clicking on the object
and dragging.
An Example
Try Matlab_Command.m to test some basic MATLAB commands.
Simple if Clauses
General if expression
Form Statements
end
Analysis • If the logical expression is TRUE, the statements between the
if statement and the end statement are executed.
• If the logical expression is FALSE, program control jumps
immediately to the statement following the end statement.
count = 0, n = input('Please input n = ');
if n < 50
count = count + 1
end
Notes • The logical expression is generated from relational operators
(>, >=, <, <=, ==, ~=) and logical operators [~ (not), & (and), |
(or), xor (logical exclusive or)]
• It is a good programming practice to indent the statements within
an if structure, for readability.
• An if statement can have a nested if statement inside it.
if Clauses: The Relational and Logical Operators
Operators • Complicated tests can be performed using the logical operators in
conjunction with the relational operators.

Relational > : Greater than >=: Greater than or equal to


Operators < : Smaller than <=: Smaller than or equal to
==: Equal to ~=: Not equal to

Logical Operator Description Example


Operators
& Logical AND. True if both (x>5)&(y>=5)
conditions are true
| Logical OR. True if at least (x>5)|(y>=5)
one condition is true
~ Logical NOT. (x~=5)
xor Exclusive OR. True if xor(x>2,y>5)
ONLY one of the two
conditions is true.
if Clauses: An Example
Example • The computer generates a random number between 0 and 10 and then
asks a user to guess what the number is. The computer then notifies
the user the result of the guess, and if incorrect, tells the user what
the number is.
Guess1. real_number=10*rand(1);
m number=ceil(real_number); % Round to the next highest
integer
fprintf('\nThe number is between 1 and 10.\n\n')
guess= input('Guess a number: ');
if guess == number
fprintf('Congratulations, your guess is right.\n')
end
if guess ~= number
fprintf('Oops, your guess is wrong.\n');
fprintf('The number is %d\n',number);
end

Results The number is between 1 and 10.


?
Guess a number: 7
Congratulations, your guess is right.
if-else Clauses
if-else • The if-else clause allows us to execute one set of statements
Clause if a logical expression is true and a different set of statements if
the logical expression is false.

General if expression
Form statement t1
statement t2

else
statement f1
statement f2

end

Results • If the logical expression is TRUE, the statements t1,


t2,… are executed.

• If the logical expression is FALSE, the statements f1,


f2,… are executed.
if-else Clauses: An Example
Example • The same guess number problem: The computer generates a random
number between 1 and 10 and then asks a user to guess what the
number is. The computer then notifies the user the result of the
guess, and if incorrect, tells the user what the number is.
Guess2. real_number=10*rand(1);
m number=ceil(real_number); % Round to the next highest
integer
fprintf('\nThe number is between 1 and 10.\n\n')
guess= input('Guess a number: ');
if guess == number
fprintf('Congratulations - your guess is right.\n')
else
fprintf('Oops, your guess is wrong.\n');
fprintf('The number is %d\n',number);
end

Results The number is between 1 and 10.


?
Guess a number: 3
Oops, your guess is wrong.
The number is 10
elseif Clauses
elseif • The elseif clause allows us to deal with more than 2 cases.
General if expression 1
Form statements group 1
elseif expression 2
statements group 2
elseif expression 3
statements group 3

else
statements group n
end
Analysis • If the logical expression1 is TRUE, the statements
group1 are executed, and the program jumps to the statement
following the end statement.
• If the logical expression 2 is True, the statements
group 2 are executed, and the program jumps to the statement
following the end statement. …
• If none of the logical expressions is True, the
statements group n are executed.
elseif Clauses: An example
Example  b  b 2  4ac
• Solve a quadratic equation: ax2 + bx + c = 0. x 
2a
Quad_eq.m a=input('Please input a:');
b=input('Please input b:');
c=input('Please input c:');
if a == 0
disp('One Solution, a=0')
x1 = -c/b;
x2 = x1;
elseif b^2-4*a*c == 0
disp(‘Two repeated roots, b^2-4ac = 0')
x1 = -b/2/a;
x2 = x1;
else
disp('Two distinct Solutions')
x1 = (-b + sqrt(b^2 - 4*a*c))/2/a;
x2 = (-b - sqrt(b^2 - 4*a*c))/2/a;
end
disp([x1 x2])
Loops
Loops • A loop is a structure that allows us to repeat a set of statements.
There are two basic forms of loop constructs: for loops and
while loops.

 A for loop can be used when the number of repetitions is


known before the loop starts.
 A while loop can be used when the looping process must
be terminated when a specific condition is satisfied, and
thus the number of repetition is unknown in advance.

Notes • Loops are very popular in other languages. They should be


avoided if possible in MATLAB as they can significantly
increase the execution time.
for Loops
Typical for loop_variable = m:s:n
Form statements
end
• The statements between the for statement and the end
statement are called the body of the loop.
• m:s:n = initial value : step (incremental value) : final value
Analysis • When the loop starts, the program assigns the initial value (m) to
the loop_variable, and executes the statements within
the loop body.
• After the statements have been executed, the program
increases the loop_variable by s, and executes the
statements within the loop body AGAIN.
• The previous step is repeated over and over until the
loop_variable exceeds the final (terminating) value n.
• After the loop is finished, the program will execute the statements
following the loop construct.
Notes • If s = 1, then s can be omitted.
for Loops: Example 1
Example 1 Calculate the sum s = 1 + 2 + 3 +…+ n
Analysis i Program Results
S = 0 S = 0
1 S = S + i S = 1
2 S = S + i S = 1+2
3 S = S + i S = 1+2+3 for i = 1:n
… … … S = S+i;
i S = S + i S = 1+2+3+…+i end
… … …
n S = S + i S =1+2+3+…+n

Code n = input('Please input n:');


s = 0;
for i = 1:n
s = s + i;
end
fprintf('1+2+...+ %d = %d\n',n,s)
for Loops: Example 2
Example 2 Calculate the factorial P = n! = 1*2*3*…*n
Analysis i Program Results
P = 1 P = 1
1 P = P * i P = 1
2 P = P * i P = 1*2
3 P = P * i P = 1*2*3 for i = 1:n
… … … P = P*i;
i P = P * i P =1*2*3*…*i end
… … …
n P = P * i P=1*2*3*…*n

Code n = input('Please input n:');


P = 1;
for i = 1:n
P = P*i;
end
fprintf('%d! = %d\n',n,P)
for Loops: An Example Using Nested for Loops
Example Calculate the sum S = 1! + 2! + 3! +…+ n!
Sum_fact.m % Sum_fact1.m
% Dr. T Zhu
% Calculate 1!+2!+...+n!
% Use nested for loops

n = input('Please input n:');


sum = 0;
for i = 1:n
fact = 1;
for j = 1:i Inner loop Outer loop sums
fact = fact*j; calculating from 1 to n
end i! for each i
sum = sum + fact;
end
fprintf('1!+2!+...+ %d! = %d\n',n,sum)
Result Please input n:10
1!+2!+...+ 10! = 4037913
while Loops
Typical while condition
Form statements
end

Analysis • When the program encounters the while statement for the first time,
the condition is tested:
 If the condition is false (=0), MATLAB jumps to the statement
following the end statement and continues with the rest of the
program, if any.
 If the condition is true (=1), the statements are executed,
and the program jumps back to the while statement and test the
condition again.
 The loops repeats indefinitely until the condition becomes false.
Notes • If the condition never becomes false, an infinite loop results.
i = 10;
while i<=10
i = i – 1;
a=i^2;
end
While Loops: An Example
Example Calculate the sum s = 1 + 2 + 3 +…+ n
for loop n = input('Please input n:');
s = 0;
for i = 1:n
s = s + i;
end
fprintf('1+2+...+ %d = %d\n',n,s)

while loop n = input('Please input n:');


s = 0;
i = 1;
while i <= n
s = s + i;
i = i + 1;
end
fprintf('1+2+...+ %d = %d\n',n,s)

Result Please input n:100


1+2+...+ 100 = 5050
Loops: Comparison
Comparison • Which one is better, the for loop or the while loop? In most
cases, the programming can be done using either of these two
loops. There are many cases where it is only a question of feeling.
• The while loop is the more general one. Almost all for loops
can be converted into while loops.
• If the number of repetitions is unknown, only the while loop
can be used.
• An infinite loop may occur if a while loop is used. However, a
for loop will not cause an infinite loop.
Functions: Introduction
Preliminary • MATLAB has lots of functions available, such as sin, cos,
sqrt, etc.
• Sometimes, we need to write our own functions to perform
certain kind of calculation.
• Like functions in C, Subroutines in FORTRAN and BASIC.

Importance • Can be used to create user-defined functions.


• Can break a large program into several smaller sub-programs
(modules). Each sub-program (i.e., function) can be written as an
independent unit, and can be tested separately to ensure it
performs properly before combining it into the large program.
• Perform a task that is used frequently. Instead of repeating the
same code in several places, the function is simply called.
• Functions can be used in other programs needing the same
functions
• The program is easy to maintain and read.
• …
Functions: Definition
General function [output variables] = function_name(input variables)
Form
• The input and output variables are also called arguments.
• Unlike in other languages, each function in MATLAB has to
be saved separately into a file, with the function_name
being the same as the file name.
• Variables declared within the function are local to the
function by default –accessible only within the function. The
only information returned from the function is contained in
the output arguments.
 Even if the input variables are changed in the function,
they will not be changed in the program – data shield.
• The same variable names used in the function and the
program are different.
• A function can not run independently. It can only be called
within the main program.
Functions: An Example
Problem 2
 b  b  4ac
• Solve a quadratic equation: ax2 + bx + c = 0. x 
2a
• Check for Quad_eq_repeat.m for solving 3 quadratic equations.
Quad_eq_fu % Quad_eq_func.m
nc.m % Dr. T Zhu
% A function file to solve a*x^2 + b*x + c = 0
Quad_eq_m % function[x1,x2] = Quad_eq_fun(a,b,c)
ain.m
function[x1,x2]=Quad_eq_func(a,b,c)
if a == 0
disp('One solution, a=0')
x1 = -c/b;
x2 = x1;
elseif b^2-4*a*c == 0
disp('One solution, b^2-4ac = 0')
x1 = -b/2/a;
x2 = x1;
else disp('Two solutions')
x1 = (-b + sqrt(b^2 - 4*a*c))/2/a;
x2 = (-b - sqrt(b^2 - 4*a*c))/2/a;
end
Functions: Calling
General function [output variables] = function_name(input variables)
Form
• The input and output variables are also called arguments.
…More… (self-study) 

• Formatting plots
• More programming
• 3D plots
• Images, Movies, and sound
• Printing and Exporting Graphics
• Handle Graphics
• Graphical user Interface (GUI)
• …

S-ar putea să vă placă și