Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

Introduction to MATLAB for Engineers, Third Edition

William J. Palm III


MATLAB Programming for Engineers, Fourth Edition
Stephen J. Chapman

Advanced Methods, Input/Output


Structures

Copyright © 2010. The McGraw-Hill Companies, Inc.


Copyright © 2008. Thomson.

This lecture note includes some updates performed by Asst. Prof. Dr. Neyre Tekbıyık Ersoy for
ENGI316 course.
Advanced Methods in Displaying Output Data
The disp function
• This function is often combined with the functions num2str (convert a number to a
string) and int2str (convert an integer to a string) to create messages to be displayed in
the Command Window.
• For example, the following MATLAB statements will display “The value of pi = 3.1416” in
the Command Window.
• The first statement creates a string array containing the message, and the second
statement displays the message.

str = ['The value of pi = ' num2str(pi)];


disp (str);
Formatted Output with the fprintf Function
• An even more flexible way to display data is with the fprintf function.
• The fprintf function displays one or more values together with related text and lets the
programmer control the way that the displayed value appears.
• The general form of this function when it is used to print to the Command Window is

fprintf(format,data)

fprintf('The value of pi is %f \n',pi)


Advanced Methods in Displaying Output Data
Creating Two-Dimensional Character Arrays
It is possible to create two-dimensional character arrays, but each row of such an array
must have exactly the same length. If one of the rows is shorter than the other rows, the
character array is invalid and will produce an error. For example, the following statements
are illegal because the two rows have different lengths.

name = ['Stephen J. Chapman';'Senior Engineer'];

The easiest way to produce two-dimensional character arrays is with the char function.
This function will automatically pad all strings to the length of the largest input string.

name = char('Stephen J. Chapman','Senior Engineer')


» line2 = name(2,:)
line2 =
Senior Engineer
» line2_trim = deblank(name(2,:))
line2_trim =
Senior Engineer
» size(line2)
ans =
1 18
» size(line2_trim)
ans =
1 15
Concatenating Strings
Function strcat concatenates two or more strings horizontally, ignoring any
trailing blanks but preserving blanks within the strings. This function produces
the following result:

» result = strcat('String 1 ','String 2')


result =
String 1String 2

Function strvcat concatenates two or more strings vertically, automatically padding the
strings to make a valid two-dimensional array. This function produces the following result:

» result = strvcat('Long String 1 ','String 2')


result =
Long String 1
String 2
Comparing Strings for Equality
You can use four MATLAB functions to compare two strings as a whole for equality. They
are:
• strcmp determines whether two strings are identical.
• strcmpi determines whether two strings are identical ignoring case.
• strncmp determines whether the first n characters of two strings are identical.
• strncmpi determines whether the first n characters of two strings are identical
ignoring case.

» c = strcmp(str1,str2)
c =
0
» c = strcmpi(str1,str2)
c =
1
» c = strncmp(str1,str3,2)
c =
1
Categorizing Characters Within a String
There are three functions for categorizing characters on a character-by-character
basis inside a string:

• isletter determines whether a character is a letter.


• isspace determines if a character is whitespace (blank, tab, or new line).
• isstrprop ('str', 'category') is a more general function. It
• determines whether a character falls into a user-specified category, such as
• alphabetic, alphanumeric, uppercase, lowercase, numeric, control and so on.

To understand these functions, let’s create a string named mystring:


mystring = 'Room 23a';

a = isletter(mystring)

a = isspace(mystring)

a = isstrprop(mystring,'digit')

a = isstrprop(mystring,'lower')
PowerPoint to accompany

Introduction to MATLAB
for Engineers, Third Edition
William J. Palm III

Linear Algebraic Equations,


Numerical Methods,
Derivatives, Integrals,
Symbolics

Copyright © 2010. The McGraw-Hill Companies, Inc.


This lecture note includes some updates (compared to the original power point of the McGraw-Hill
Companies, Inc.) performed by Asst. Prof. Dr. Neyre Tekbıyık Ersoy for ENGI316 course.
Creating Symbolic Variables
 In order to use the symbolic toolbox, you
must create symbolic variables.
 To create one symbolic variable, type:
x = sym('x');

 You can also use the syms command:

syms x;
Creating Multiple Variables
 To create several symbolic variables use
the syms command as follows:

syms K T P0;

 This creates the symbolic variables K,


T, and P0
Creating a symbolic expression
with symbolic variables

 To create an expression using existing


symbolic variables, type:

P = P0*exp(K*T)

 This creates a symbolic expression that


includes the exponential function. It could
represent the exponential growth of a
population.
Creating an expression with
sym()

 You can also create symbolic expressions


with the sym() command:

E = sym('m*c^2')
Manipulating symbolic
expressions
 expand()
 factor()
 collect()
 simplify()
expand()
 expand() is used to expand an expression
by expanding the products of factors in an
expression.
 Expand the numerator of y:
numerator=
2*(x + 3)^2

expand(numerator)
expand(numerator

ans=
2*x^2 + 12*x + 18
factor()
 The factor() command is used to factor an
expression into a product of terms.

Example: Factor the expression for the


denominator.
denominator=
(x^2 + 6*x + 9)

factor(denominator)
ans=
[ x + 3, x + 3]
simplify()
 The simplify() command uses the Maple
simplification algorithm to simplify each
part of an expression.
 Enter the expression:

b=sym('3*a - (a + 3)*(a - 3)^2');


simplify(b)

ans=
- a^2 + 3*a + 9
solve()
 The solve() function sets an expression
equal to zero, then solves the equation
for its roots.

E1=x^2 - 9
solve(E1)

ans=
3
-3
Hands on

solve('a*x^2 + b*x + c')

ans =
1/2/a*( -b + (b^2 - 4*a*c)^(1/2))
1/2/a*( -b - (b^2 - 4*a*c)^(1/2))

Note: The expression is in single quotes; if


the symbolic variables in the expression
have not been defined previously, then the
single quotes are necessary.
Hands on

solve('a*x^2 + b*x + c', 'a')

ans =
-(b*x + c)/x^2

Note that this solves the expression for “a”.


Systems of equations
 You can use solve() to find the solution of
a system of equations.
one=sym('3*x + 2*y – z = 10');
two=sym('-x + 3*y + 2*z = 5');
three=sym('x – y – z = -1');
[x,y,z]=solve(one,two,three)

x= y= z=
-2 5 -6

Note that the solve function produces symbolic output. You can
change the output to numerical values with the double() command.
Systems of equations
Systems of equations
Systems of equations
Substitution with subs()
 The subs() command allows you to
substitute a symbol with another symbol or
assign a number to a variable.

syms a b c x y;
quadratic = a*x^2 + b*x + c;
yquadratic = subs(quadratic,x,y)

yquadratic =
a*y^2 + b*y + c
Multiple substitutions
 You can use the subs() command to do
multiple substitutions in one command.
This is done by grouping the variables and
their substitutes (other variables or
numerical values) in braces.
subs(symbolic_function, {substitutant}, {substitute})

subs(quadratic, {a,b,c,x}, {1,2,3,4})

ans =
27
Plotting symbolical functions
 Plotting symbolic functions in MATLAB is
done with the ezplot() set of commands.
 The syntax of ezplot() when y is a function
of x is:
ezplot(y)
x 2-2 x+3

y = sym('x^2 – 2*x + 3'); 50

ezplot(y) 40

30

20

10

0
-6 -4 -2 0 2 4 6
x
Plotting symbolical functions
Symbolic Plot Types
ezplot Function plotter if z is a function of x
ezplot(z)
ezmesh Mesh plotter if z is a function of x and y
ezmesh(z)
ezmeshc Combined mesh and contour if z is a function of x and y
plotter ezmeshc(z)
ezsurf Surface plotter if z is a function of x and y
ezsurf(z)
ezsurfc Combined surface and contour if z is a function of x and y
plotter ezsurfc(z)
ezcontour Contour plotter if z is a function of x and y
ezcontour(z)
ezplot3 3-D parametric curve plotter if x is a function of t
if y is a function of t
if z is a function of t
ezplot3(x,y,z)
Finding the Limits of a function-
f(x)
Mathematical Operation MATLAB Command

limit(f)

limit(f,x,a) or
limit(f,a)

limit(f,x,a,'right')

limit(f,x,a,'left')
Differentiation
Symbolic Differentiation

diff(f) Returns the derivative of the expression f y=sym('x^3+z^2')


with respect to the default independent diff(y)
variable ans =
3*x^2

diff(f,’t’) Returns the derivative of the expression f y=sym('x^3+z^2')


with respect to the variable t. diff(y,'z')
ans =
2*z

diff(f,n) Returns the nth derivative of the expression y=sym('x^3+z^2')


f with respect to the default independent diff(y,2)
variable ans =
6*x

diff(f,’t’,n) Returns the nth derivative of the expression y=sym('x^3+z^2')


f with respect to the variable t. diff(y,'z',2)
ans =
2
Integration
Symbolic Integration
int(f) Returns the integral of the expression f with y=sym('x^3+z^2')
respect to the default independent variable int(y)
ans =
1/4*x^4+z^2*x
int(f,’t’) Returns the integral of the expression f with y=sym('x^3+z^2')
respect to the variable t. int(y,'z')
ans =
x^3*z+1/3*z^3
int(f,a,b) Returns the integral with respect to the default y=sym('x^3+z^2')
variable, of the expression f between the int(y,2,3)
numeric bounds, a and b. ans =
65/4+z^2

int(f,’t’,a,b) Returns the integral with respect to the y=sym('x^3+z^2')


variable t, of the expression f between the int(y,'z',2,3)
numeric bounds, a and b. ans =
x^3+19/3

int(f,’t’,a,b) Returns the integral with respect to the y=sym('x^3+z^2')


variable t, of the expression f between the int(y,'z','a','b')
symbolic bounds, a and b. ans =
x^3*(b-a)+1/3*b^3-1/3*a^3
Double Integrals
Triple Integrals
The integral of f(x) interpreted as the area A under the
curve of f (x) from x = a to x = b.
Illustration of (a) rectangular and (b) trapezoidal
numerical integration. Figure 9.1–1, page 370.
Numerical integration functions. Table 9.1–1, page
371.
Command Description Example
Uses an adaptive
Simpson’s rule to
compute the integral of
the function whose
quad(fun,a,b) handle is fun, with a as
the lower integration limit
and b as the upper limit.
The function fun must
accept a vector
argument.

Uses Lobatto quadrature


to compute the integral of
quadl(fun,a,b)
the function fun. The rest
of the syntax is identical
to quad.
Numerical integration functions. Table 9.1–1, page 371
(Contd.)
Command Description Example

Uses trapezoidal
integration to compute
the integral of y with
respect to x, where the x = linspace(0,pi,10);
trapz(x,y) y = sin(x);
array y contains the trapz(x,y)

function values at the


points contained in the
array x.
Although the ‘quad’ and ‘quadl’ functions are more accurate than ‘trapz’, they
are restricted to computing the integrals of functions and cannot be used when
the integrand is specified by a set of points. For such cases, use the trapz
function.
Double Integrals
A = dblquad(fun, a, b, c, d) computes the integral of
f(x,y) from x = a to b, and y = c to d. Here is an example using an
anonymous function to represent f(x,y) = xy2.

>>fun = @(x,y)x.*y^2;
>>A = dblquad(fun,1,3,0,1)

The answer is A = 1.3333. For more, see pages 376 to 377.

9-10
Triple Integrals
A = triplequad(fun, a, b, c, d, e, f) computes the triple integral
of f(x,y, z) from x = a to b, y = c to d, and z = e to f. Here is an example using an
anonymous function to represent f(x,y,z) = (xy -y2)/z.

>>fun = @(x,y,z)(x*y –y^2)/z;


>>A = triplequad(fun,1,3,0,2,1,2)

The answer is A = 1.8484. Note that the function must accept a


vector x, but scalar y and z. See page 377.

clc;clear all
F = @(x,y,z) x.^2+y.^2+z.^2;
9-11 Mtotal = triplequad(F,0,2,-1,1,-4,4)

You might also like