0% found this document useful (0 votes)
4 views

MATLAB3

dsds
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

MATLAB3

dsds
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

if...

end Statement

An if ... end statement consists of an if statement and a boolean expression


followed by one or more statements. It is delimited by the end statement.

Syntax
The syntax of an if statement in MATLAB is −

if <expression>
% statement(s) will execute if the boolean expression is true
<statements>
end

If the expression evaluates to true, then the block of code inside the if
statement will be executed. If the expression evaluates to false, then the
first set of code after the end statement will be executed.

Example
Create a script file and type the following code −

a = 10;
% check the condition using if statement
if a < 20
% if condition is true then print the following
fprintf('a is less than 20\n' );
end
fprintf('value of a is : %d\n', a);

When you run the file, it displays the following result −

a is less than 20
value of a is : 10
if...else...end Statement
An if statement can be followed by an optional else statement, which
executes when the expression is false.

Syntax
The syntax of an if...else statement in MATLAB is −
if <expression>
% statement(s) will execute if the boolean expression is true
<statement(s)>
else
<statement(s)>
% statement(s) will execute if the boolean expression is false
end

If the boolean expression evaluates to true, then the if block of code will be
executed, otherwise else block of code will be executed.

Flow Diagram

Example
Create a script file and type the following code −

a = 100;
% check the boolean condition
if a < 20
% if condition is true then print the following
fprintf('a is less than 20\n' );
else
% if condition is false then print the following
fprintf('a is not less than 20\n' );
end
fprintf('value of a is : %d\n', a);

When the above code is compiled and executed, it produces the following
result −

a is not less than 20


value of a is : 100
if...elseif...elseif...else...end Statements
An if statement can be followed by one (or more) optional elseif... and
an else statement, which is very useful to test various conditions.

When using if... elseif...else statements, there are few points to keep in mind

 An if can have zero or one else's and it must come after any elseif's.
 An if can have zero to many elseif's and they must come before the
else.
 Once an else if succeeds, none of the remaining elseif's or else's will be
tested.

Syntax
if <expression 1>
% Executes when the expression 1 is true
<statement(s)>

elseif <expression 2>


% Executes when the boolean expression 2 is true
<statement(s)>

Elseif <expression 3>


% Executes when the boolean expression 3 is true
<statement(s)>

else
% executes when the none of the above condition is true
<statement(s)>
end

Example
Create a script file and type the following code in it −

a = 100;
%check the boolean condition
if a == 10
% if condition is true then print the following
fprintf('Value of a is 10\n' );
elseif( a == 20 )
% if else if condition is true
fprintf('Value of a is 20\n' );
elseif a == 30
% if else if condition is true
fprintf('Value of a is 30\n' );
else
% if none of the conditions is true '
fprintf('None of the values are matching\n');
fprintf('Exact value of a is: %d\n', a );
end

When the above code is compiled and executed, it produces the following
result −

None of the values are matching


Exact value of a is: 100
The Nested if Statements
It is always legal in MATLAB to nest if-else statements which means you can
use one if or elseif statement inside another if or elseif statement(s).

Syntax
The syntax for a nested if statement is as follows −

if <expression 1>
% Executes when the boolean expression 1 is true
if <expression 2>
% Executes when the boolean expression 2 is true
end
end

You can nest elseif...else in the similar way as you have nested if statement.

Advertisement

Example
Create a script file and type the following code in it −

a = 100;
b = 200;
% check the boolean condition
if( a == 100 )

% if condition is true then check the following


if( b == 200 )

% if condition is true then print the following


fprintf('Value of a is 100 and b is 200\n' );
end

end
fprintf('Exact value of a is : %d\n', a );
fprintf('Exact value of b is : %d\n', b );

When you run the file, it displays −

Value of a is 100 and b is 200


Exact value of a is : 100
Exact value of b is : 200
The switch Statement
A switch block conditionally executes one set of statements from several
choices. Each choice is covered by a case statement.

An evaluated switch_expression is a scalar or string.

An evaluated case_expression is a scalar, a string or a cell array of scalars or


strings.

The switch block tests each case until one of the cases is true. A case is true
when −
 For numbers, eq(case_expression,switch_expression).
 For strings, strcmp(case_expression,switch_expression).
 For objects that support
the eq(case_expression,switch_expression).
 For a cell array case_expression, at least one of the elements of the
cell array matches switch_expression, as defined above for numbers,
strings and objects.

When a case is true, MATLAB executes the corresponding statements and


then exits the switch block.

The otherwise block is optional and executes only when no case is true.

Syntax
The syntax of switch statement in MATLAB is −

switch <switch_expression>
case <case_expression>
<statements>
case <case_expression>
<statements>
...
...
otherwise
<statements>
end
Advertisement

Example
Create a script file and type the following code in it −

grade = 'B';
switch(grade)
case 'A'
fprintf('Excellent!\n' );
case 'B'
fprintf('Well done\n' );
case 'C'
fprintf('Well done\n' );
case 'D'
fprintf('You passed\n' );
case 'F'
fprintf('Better try again\n' );
otherwise
fprintf('Invalid grade\n' );
end

When you run the file, it displays −

Well done
The Nested switch Statements
It is possible to have a switch as part of the statement sequence of an outer
switch. Even if the case constants of the inner and outer switch contain
common values, no conflicts will arise.

Syntax
The syntax for a nested switch statement is as follows −

switch(ch1)
case 'A'
fprintf('This A is part of outer switch');
switch(ch2)
case 'A'
fprintf('This A is part of inner switch' );

case 'B'
fprintf('This B is part of inner switch' );
end
case 'B'
fprintf('This B is part of outer switch' );
end
Advertisement

Example
Create a script file and type the following code in it −

a = 100;
b = 200;
switch(a)
case 100
fprintf('This is part of outer switch %d\n', a );
switch(b)
case 200
fprintf('This is part of inner switch %d\n', a );
end
end

fprintf('Exact value of a is : %d\n', a );


fprintf('Exact value of b is : %d\n', b );

When you run the file, it displays −

This is part of outer switch 100


This is part of inner switch 100
Exact value of a is : 100
Exact value of b is : 200

While loop

The while loop repeatedly executes statements while condition is true.

Syntax
The syntax of a while loop in MATLAB is −

while <expression>
<statements>
end

The while loop repeatedly executes program statement(s) as long as the


expression remains true.

An expression is true when the result is nonempty and contains all nonzero
elements (logical or real numeric). Otherwise, the expression is false.

Example
Create a script file and type the following code −

a = 10;
% while loop execution
while( a < 20 )
fprintf('value of a: %d\n', a);
a = a + 1;
end

When you run the file, it displays the following result −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

A for loop is a repetition control structure that allows you to efficiently write
a loop that needs to execute a specific number of times.

Syntax
The syntax of a for loop in MATLAB is −

for index = values


<program statements>
...
end

values has one of the following forms −

Sr.N
Format & Description
o.

initval:endval
1 increments the index variable from initval to endval by 1, and repeats execution
of program statements until index is greater than endval.
initval:step:endval
2 increments index by the value step on each iteration, or decrements when step is
negative.

valArray
creates a column vector index from subsequent columns of array valArray on each
iteration. For example, on the first iteration, index = valArray(:,1). The loop executes for
3
a maximum of n times, where n is the number of columns of valArray, given by
numel(valArray, 1, :). The input valArray can be of any MATLAB data type, including a
string, cell array, or struct.

Example 1
Create a script file and type the following code −

for a = 10:20
fprintf('value of a: %d\n', a);
end

When you run the file, it displays the following result −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20

Example 2
Create a script file and type the following code −

for a = 1.0: -0.1: 0.0


disp(a)
end
When you run the file, it displays the following result −

1
0.90000
0.80000
0.70000
0.60000
0.50000
0.40000
0.30000
0.20000
0.10000
0

Example 3
Create a script file and type the following code −

for a = [24,18,17,23,28]
disp(a)
end

When you run the file, it displays the following result −

24

18

17

23

28

The Nested Loops


MATLAB allows to use one loop inside another loop. Following section shows
few examples to illustrate the concept.

Syntax
The syntax for a nested for loop statement in MATLAB is as follows −

for m = 1:j
for n = 1:k
<statements>;
end
end

The syntax for a nested while loop statement in MATLAB is as follows −

while <expression1>
while <expression2>
<statements>
end
end

Example
Let us use a nested for loop to display all the prime numbers from 1 to 100.
Create a script file and type the following code −

for i = 2:100
for j = 2:100
if(~mod(i,j))
break; % if factor found, not prime
end
end
if(j > (i/j))
fprintf('%d is prime\n', i);
end
end

When you run the file, it displays the following result −

2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Plotting
To plot the graph of a function, you need to take the following steps −

 Define x, by specifying the range of values for the variable x, for


which the function is to be plotted
 Define the function, y = f(x)
 Call the plot command, as plot(x, y)
Following example would demonstrate the concept. Let us plot the simple
function y = x for the range of values for x from 0 to 100, with an increment
of 5.

Create a script file and type the following code −

x = [0:5:100];
y = x;
plot(x, y)

When you run the file, MATLAB displays the following plot −

Let us take one more example to plot the function y = x 2. In this example, we
will draw two graphs with the same function, but in second time, we will
reduce the value of increment. Please note that as we decrease the
increment, the graph becomes smoother.

Create a script file and type the following code −

x = [1 2 3 4 5 6 7 8 9 10];
x = [-100:20:100];
y = x.^2;
plot(x, y)

When you run the file, MATLAB displays the following plot −
Change the code file a little, reduce the increment to 5 −

x = [-100:5:100];
y = x.^2;
plot(x, y)

MATLAB draws a smoother graph −


Adding Title, Labels, Grid Lines and Scaling on the
Graph
MATLAB allows you to add title, labels along the x-axis and y-axis, grid lines
and also to adjust the axes to spruce up the graph.

 The xlabel and ylabel commands generate labels along x-axis and y-
axis.
 The title command allows you to put a title on the graph.
 The grid on command allows you to put the grid lines on the graph.
 The axis equal command allows generating the plot with the same
scale factors and the spaces on both axes.
 The axis square command generates a square plot.
Example

Create a script file and type the following code −

x = [0:0.01:10];
y = sin(x);
plot(x, y), xlabel('x'), ylabel('Sin(x)'), title('Sin(x) Graph'),
grid on, axis equal

MATLAB generates the following graph −

Drawing Multiple Functions on the Same Graph


You can draw multiple graphs on the same plot. The following example
demonstrates the concept −

Example

Create a script file and type the following code −

x = [0 : 0.01: 10];
y = sin(x);
g = cos(x);
plot(x, y, x, g, '.-'), legend('Sin(x)', 'Cos(x)')

MATLAB generates the following graph −

Setting Colors on Graph


MATLAB provides eight basic color options for drawing graphs. The following
table shows the colors and their codes −

Code Color

w White

k Black
b Blue

r Red

c Cyan

g Green

m Magenta

y Yellow

Example

Let us draw the graph of two polynomials

 f(x) = 3x4 + 2x3+ 7x2 + 2x + 9 and


 g(x) = 5x3 + 9x + 2

Create a script file and type the following code −

x = [-10 : 0.01: 10];


y = 3*x.^4 + 2 * x.^3 + 7 * x.^2 + 2 * x + 9;
g = 5 * x.^3 + 9 * x + 2;
plot(x, y, 'r', x, g, 'g')

When you run the file, MATLAB generates the following graph −
Setting Axis Scales
The axis command allows you to set the axis scales. You can provide
minimum and maximum values for x and y axes using the axis command in
the following way −
axis ( [xmin xmax ymin ymax] )

The following example shows this −

Example

Create a script file and type the following code −

x = [0 : 0.01: 10];
y = exp(-x).* sin(2*x + 3);
plot(x, y), axis([0 10 -1 1])

When you run the file, MATLAB generates the following graph −
Generating Sub-Plots
When you create an array of plots in the same figure, each of these plots is
called a subplot. The subplot command is used for creating subplots.

Syntax for the command is −

subplot(m, n, p)
where, m and n are the number of rows and columns of the plot array
and p specifies where to put a particular plot.

Each plot created with the subplot command can have its own
characteristics. Following example demonstrates the concept −

Example

Let us generate two plots −

y = e−1.5xsin(10x)
y = e−2xsin(10x)

Create a script file and type the following code −

x = [0:0.01:5];
y = exp(-1.5*x).*sin(10*x);
subplot(1,2,1)
plot(x,y), xlabel('x'),ylabel('exp(–1.5x)*sin(10x)'),axis([0 5 -1
1])
y = exp(-2*x).*sin(10*x);
subplot(1,2,2)
plot(x,y),xlabel('x'),ylabel('exp(–2x)*sin(10x)'),axis([0 5 -1
1])

When you run the file, MATLAB generates the following graph −

Differential

MATLAB provides the diff command for computing symbolic derivatives. In


its simplest form, you pass the function you want to differentiate to diff
command as an argument.
For example, let us compute the derivative of the function f(t) = 3t 2 + 2t-2

Example
Create a script file and type the following code into it −

syms t
f = 3*t^2 + 2*t^(-2);
diff(f)
When the above code is compiled and executed, it produces the following
result −

ans =
6*t - 4/t^3

Following is Octave equivalent of the above calculation −

pkg load symbolic


symbols

t = sym("t");
f = 3*t^2 + 2*t^(-2);
differentiate(f,t)

Octave executes the code and returns the following result −

ans =
-(4.0)*t^(-3.0)+(6.0)*t

Verification of Elementary Rules of


Differentiation
Let us briefly state various equations or rules for differentiation of functions
and verify these rules. For this purpose, we will write f'(x) for a first order
derivative and f"(x) for a second order derivative.

Following are the rules for differentiation −

Rule 1

For any functions f and g and any real numbers a and b are the derivative of
the function −

h(x) = af(x) + bg(x) with respect to x is given by −


h'(x) = af'(x) + bg'(x)
Rule 2
The sum and subtraction rules state that if f and g are two functions, f' and
g' are their derivatives respectively, then,
(f + g)' = f' + g'
(f - g)' = f' - g'
Rule 3
The product rule states that if f and g are two functions, f' and g' are their
derivatives respectively, then,
(f.g)' = f'.g + g'.f
Rule 4
The quotient rule states that if f and g are two functions, f' and g' are their
derivatives respectively, then,
(f/g)' = (f'.g - g'.f)/g2
Rule 5
The polynomial or elementary power rule states that, if y = f(x) = xn,
then f' = n. x(n-1)
A direct outcome of this rule is that the derivative of any constant is zero,
i.e., if y = k, any constant, then
f' = 0
Rule 6
The chain rule states that, derivative of the function of a function h(x) =
f(g(x)) with respect to x is,
h'(x)= f'(g(x)).g'(x)
Example

Create a script file and type the following code into it −

syms x
syms t

f = (x + 2)*(x^2 + 3)
der1 = diff(f)

f = (t^2 + 3)*(sqrt(t) + t^3)


der2 = diff(f)

f = (x^2 - 2*x + 1)*(3*x^3 - 5*x^2 + 2)


der3 = diff(f)

f = (2*x^2 + 3*x)/(x^3 + 1)
der4 = diff(f)

f = (x^2 + 1)^17
der5 = diff(f)

f = (t^3 + 3* t^2 + 5*t -9)^(-6)


der6 = diff(f)
When you run the file, MATLAB displays the following result −

f=
(x^2 + 3)*(x + 2)

der1 =
2*x*(x + 2) + x^2 + 3

f=
(t^(1/2) + t^3)*(t^2 + 3)

der2 =
(t^2 + 3)*(3*t^2 + 1/(2*t^(1/2))) + 2*t*(t^(1/2) + t^3)

f=
(x^2 - 2*x + 1)*(3*x^3 - 5*x^2 + 2)

der3 =
(2*x - 2)*(3*x^3 - 5*x^2 + 2) - (- 9*x^2 + 10*x)*(x^2 - 2*x + 1)

f=
(2*x^2 + 3*x)/(x^3 + 1)

der4 =
(4*x + 3)/(x^3 + 1) - (3*x^2*(2*x^2 + 3*x))/(x^3 + 1)^2

f=
(x^2 + 1)^17

der5 =
34*x*(x^2 + 1)^16

f=
1/(t^3 + 3*t^2 + 5*t - 9)^6

der6 =
-(6*(3*t^2 + 6*t + 5))/(t^3 + 3*t^2 + 5*t - 9)^7

Following is Octave equivalent of the above calculation −

pkg load symbolic


symbols

x = sym("x");
t = sym("t");

f = (x + 2)*(x^2 + 3)
der1 = differentiate(f,x)

f = (t^2 + 3)*(t^(1/2) + t^3)


der2 = differentiate(f,t)

f = (x^2 - 2*x + 1)*(3*x^3 - 5*x^2 + 2)


der3 = differentiate(f,x)

f = (2*x^2 + 3*x)/(x^3 + 1)
der4 = differentiate(f,x)

f = (x^2 + 1)^17
der5 = differentiate(f,x)

f = (t^3 + 3* t^2 + 5*t -9)^(-6)


der6 = differentiate(f,t)

Octave executes the code and returns the following result −

f=

(2.0+x)*(3.0+x^(2.0))
der1 =

3.0+x^(2.0)+(2.0)*(2.0+x)*x
f=

(t^(3.0)+sqrt(t))*(3.0+t^(2.0))
der2 =

(2.0)*(t^(3.0)+sqrt(t))*t+((3.0)*t^(2.0)+(0.5)*t^(-0.5))*(3.0+t^(2.0))
f=

(1.0+x^(2.0)-(2.0)*x)*(2.0-(5.0)*x^(2.0)+(3.0)*x^(3.0))
der3 =

(-2.0+(2.0)*x)*(2.0-(5.0)*x^(2.0)+(3.0)*x^(3.0))+((9.0)*x^(2.0)-
(10.0)*x)*(1.0+x^(2.0)-(2.0)*x)
f=

(1.0+x^(3.0))^(-1)*((2.0)*x^(2.0)+(3.0)*x)
der4 =

(1.0+x^(3.0))^(-1)*(3.0+(4.0)*x)-(3.0)*(1.0+x^(3.0))^(-
2)*x^(2.0)*((2.0)*x^(2.0)+(3.0)*x)
f=

(1.0+x^(2.0))^(17.0)
der5 =

(34.0)*(1.0+x^(2.0))^(16.0)*x
f=

(-9.0+(3.0)*t^(2.0)+t^(3.0)+(5.0)*t)^(-6.0)
der6 =

-(6.0)*(-9.0+(3.0)*t^(2.0)+t^(3.0)+(5.0)*t)^(-7.0)*(5.0+(3.0)*t^(2.0)+(6.0)*t)

Derivatives of Exponential, Logarithmic and


Trigonometric Functions
The following table provides the derivatives of commonly used exponential,
logarithmic and trigonometric functions −

Function Derivative

ca.x ca.x.ln c.a (ln is natural logarithm)


ex ex

ln x 1/x

lncx 1/x.ln c

xx xx.(1 + ln x)

sin(x) cos(x)

cos(x) -sin(x)

tan(x) sec2(x), or 1/cos2(x), or 1 + tan2(x)

cot(x) -csc2(x), or -1/sin2(x), or -(1 + cot2(x))

sec(x) sec(x).tan(x)

csc(x) -csc(x).cot(x)

Example

Create a script file and type the following code into it −

syms x
y = exp(x)
diff(y)

y = x^9
diff(y)

y = sin(x)
diff(y)

y = tan(x)
diff(y)

y = cos(x)
diff(y)

y = log(x)
diff(y)

y = log10(x)
diff(y)

y = sin(x)^2
diff(y)

y = cos(3*x^2 + 2*x + 1)
diff(y)

y = exp(x)/sin(x)
diff(y)

When you run the file, MATLAB displays the following result −

y=
exp(x)
ans =
exp(x)

y=
x^9
ans =
9*x^8

y=
sin(x)
ans =
cos(x)

y=
tan(x)
ans =
tan(x)^2 + 1

y=
cos(x)
ans =
-sin(x)

y=
log(x)
ans =
1/x

y=
log(x)/log(10)
ans =
1/(x*log(10))

y=
sin(x)^2
ans =
2*cos(x)*sin(x)

y=
cos(3*x^2 + 2*x + 1)
ans =
-sin(3*x^2 + 2*x + 1)*(6*x + 2)

y=
exp(x)/sin(x)
ans =
exp(x)/sin(x) - (exp(x)*cos(x))/sin(x)^2

Following is Octave equivalent of the above calculation −

pkg load symbolic


symbols

x = sym("x");
y = Exp(x)
differentiate(y,x)
y = x^9
differentiate(y,x)

y = Sin(x)
differentiate(y,x)

y = Tan(x)
differentiate(y,x)

y = Cos(x)
differentiate(y,x)

y = Log(x)
differentiate(y,x)

% symbolic packages does not have this support


%y = Log10(x)
%differentiate(y,x)

y = Sin(x)^2
differentiate(y,x)

y = Cos(3*x^2 + 2*x + 1)
differentiate(y,x)

y = Exp(x)/Sin(x)
differentiate(y,x)

Octave executes the code and returns the following result −

y=

exp(x)
ans =

exp(x)
y=

x^(9.0)
ans =

(9.0)*x^(8.0)
y=

sin(x)
ans =

cos(x)
y=

tan(x)
ans =

1+tan(x)^2
y=

cos(x)
ans =

-sin(x)
y=

log(x)
ans =

x^(-1)
y=

sin(x)^(2.0)
ans =

(2.0)*sin(x)*cos(x)
y=

cos(1.0+(2.0)*x+(3.0)*x^(2.0))
ans =

-(2.0+(6.0)*x)*sin(1.0+(2.0)*x+(3.0)*x^(2.0))
y=

sin(x)^(-1)*exp(x)
ans =

sin(x)^(-1)*exp(x)-sin(x)^(-2)*cos(x)*exp(x)
Advertisement

Computing Higher Order Derivatives


To compute higher derivatives of a function f, we use the syntax diff(f,n).
Let us compute the second derivative of the function y = f(x) = x .e -3x
f = x*exp(-3*x);
diff(f, 2)

MATLAB executes the code and returns the following result −

ans =
9*x*exp(-3*x) - 6*exp(-3*x)

Following is Octave equivalent of the above calculation −

pkg load symbolic


symbols

x = sym("x");
f = x*Exp(-3*x);
differentiate(f, x, 2)

Octave executes the code and returns the following result −

ans =

(9.0)*exp(-(3.0)*x)*x-(6.0)*exp(-(3.0)*x)
Example
In this example, let us solve a problem. Given that a function y = f(x) = 3
sin(x) + 7 cos(5x). We will have to find out whether the equation f" + f = -
5cos(2x) holds true.

Create a script file and type the following code into it −


syms x
y = 3*sin(x)+7*cos(5*x); % defining the function
lhs = diff(y,2)+y; %evaluting the lhs of the equation
rhs = -5*cos(2*x); %rhs of the equation
if(isequal(lhs,rhs))
disp('Yes, the equation holds true');
else
disp('No, the equation does not hold true');
end
disp('Value of LHS is: '), disp(lhs);

When you run the file, it displays the following result −

No, the equation does not hold true


Value of LHS is:
-168*cos(5*x)

Following is Octave equivalent of the above calculation −

pkg load symbolic


symbols

x = sym("x");
y = 3*Sin(x)+7*Cos(5*x); % defining the function
lhs = differentiate(y, x, 2) + y; %evaluting the lhs of the
equation
rhs = -5*Cos(2*x); %rhs of the equation

if(lhs == rhs)
disp('Yes, the equation holds true');
else
disp('No, the equation does not hold true');
end
disp('Value of LHS is: '), disp(lhs);

Octave executes the code and returns the following result −

No, the equation does not hold true


Value of LHS is:
-(168.0)*cos((5.0)*x)

Finding the Maxima and Minima of a Curve


If we are searching for the local maxima and minima for a graph, we are
basically looking for the highest or lowest points on the graph of the function
at a particular locality, or for a particular range of values of the symbolic
variable.

For a function y = f(x) the points on the graph where the graph has zero
slope are called stationary points. In other words stationary points are
where f'(x) = 0.

To find the stationary points of a function we differentiate, we need to set


the derivative equal to zero and solve the equation.

Example
Let us find the stationary points of the function f(x) = 2x 3 + 3x2 − 12x + 17

Take the following steps −

First let us enter the function and plot its graph.


syms x
y = 2*x^3 + 3*x^2 - 12*x + 17; % defining the function
ezplot(y)

MATLAB executes the code and returns the following plot −

Here is Octave equivalent code for the above example −


pkg load symbolic
symbols

x = sym('x');
y = inline("2*x^3 + 3*x^2 - 12*x + 17");

ezplot(y)
print -deps graph.eps
Our aim is to find some local maxima and minima on the graph, so
let us find the local maxima and minima for the interval [-2, 2] on
the graph.
syms x
y = 2*x^3 + 3*x^2 - 12*x + 17; % defining the function
ezplot(y, [-2, 2])

MATLAB executes the code and returns the following plot −

Here is Octave equivalent code for the above example −

pkg load symbolic


symbols

x = sym('x');
y = inline("2*x^3 + 3*x^2 - 12*x + 17");

ezplot(y, [-2, 2])


print -deps graph.eps
Next, let us compute the derivative.
g = diff(y)

MATLAB executes the code and returns the following result −

g=
6*x^2 + 6*x - 12

Here is Octave equivalent of the above calculation −

pkg load symbolic


symbols

x = sym("x");
y = 2*x^3 + 3*x^2 - 12*x + 17;
g = differentiate(y,x)

Octave executes the code and returns the following result −

g=
-12.0+(6.0)*x+(6.0)*x^(2.0)
Let us solve the derivative function, g, to get the values where it
becomes zero.
s = solve(g)

MATLAB executes the code and returns the following result −

s=
1
-2

Following is Octave equivalent of the above calculation −

pkg load symbolic


symbols

x = sym("x");
y = 2*x^3 + 3*x^2 - 12*x + 17;
g = differentiate(y,x)
roots([6, 6, -12])

Octave executes the code and returns the following result −


g=

-12.0+(6.0)*x^(2.0)+(6.0)*x
ans =

-2
1
This agrees with our plot. So let us evaluate the function f at the
critical points x = 1, -2. We can substitute a value in a symbolic function
by using the subs command.
subs(y, 1), subs(y, -2)

MATLAB executes the code and returns the following result −

ans =
10
ans =
37

Following is Octave equivalent of the above calculation −

pkg load symbolic


symbols

x = sym("x");
y = 2*x^3 + 3*x^2 - 12*x + 17;
g = differentiate(y,x)

roots([6, 6, -12])
subs(y, x, 1), subs(y, x, -2)
ans =
10.0
ans =
37.0-4.6734207789940138748E-18*I
Therefore, The minimum and maximum values on the function f(x) = 2x 3 +
3x2 − 12x + 17, in the interval [-2,2] are 10 and 37.

Solving Differential Equations


MATLAB provides the dsolve command for solving differential equations
symbolically.
The most basic form of the dsolve command for finding the solution to a
single equation is
dsolve('eqn')
where eqn is a text string used to enter the equation.

It returns a symbolic solution with a set of arbitrary constants that MATLAB


labels C1, C2, and so on.

You can also specify initial and boundary conditions for the problem, as
comma-delimited list following the equation as −

dsolve('eqn','cond1', 'cond2',…)
For the purpose of using dsolve command, derivatives are indicated with
a D. For example, an equation like f'(t) = -2*f + cost(t) is entered as −
'Df = -2*f + cos(t)'

Higher derivatives are indicated by following D by the order of the derivative.

For example the equation f"(x) + 2f'(x) = 5sin3x should be entered as −

'D2y + 2Dy = 5*sin(3*x)'

Let us take up a simple example of a first order differential equation: y' = 5y.

s = dsolve('Dy = 5*y')

MATLAB executes the code and returns the following result −

s=
C2*exp(5*t)

Let us take up another example of a second order differential equation as: y"
- y = 0, y(0) = -1, y'(0) = 2.

dsolve('D2y - y = 0','y(0) = -1','Dy(0) = 2')

MATLAB executes the code and returns the following result −

ans =
exp(t)/2 - (3*exp(-t))/2

You might also like