MATLAB3
MATLAB3
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);
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 −
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)>
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 −
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 )
end
fprintf('Exact value of a is : %d\n', a );
fprintf('Exact value of b is : %d\n', b );
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.
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
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
While loop
Syntax
The syntax of a while loop in MATLAB is −
while <expression>
<statements>
end
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
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 −
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
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 −
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
24
18
17
23
28
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
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
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 −
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.
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)
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
x = [0:0.01:10];
y = sin(x);
plot(x, y), xlabel('x'), ylabel('Sin(x)'), title('Sin(x) Graph'),
grid on, axis equal
Example
x = [0 : 0.01: 10];
y = sin(x);
g = cos(x);
plot(x, y, x, g, '.-'), legend('Sin(x)', 'Cos(x)')
Code Color
w White
k Black
b Blue
r Red
c Cyan
g Green
m Magenta
y Yellow
Example
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] )
Example
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.
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
y = e−1.5xsin(10x)
y = e−2xsin(10x)
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
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
t = sym("t");
f = 3*t^2 + 2*t^(-2);
differentiate(f,t)
ans =
-(4.0)*t^(-3.0)+(6.0)*t
Rule 1
For any functions f and g and any real numbers a and b are the derivative of
the function −
syms x
syms t
f = (x + 2)*(x^2 + 3)
der1 = diff(f)
f = (2*x^2 + 3*x)/(x^3 + 1)
der4 = diff(f)
f = (x^2 + 1)^17
der5 = diff(f)
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
x = sym("x");
t = sym("t");
f = (x + 2)*(x^2 + 3)
der1 = 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=
(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)
Function Derivative
ln x 1/x
lncx 1/x.ln c
xx xx.(1 + ln x)
sin(x) cos(x)
cos(x) -sin(x)
sec(x) sec(x).tan(x)
csc(x) -csc(x).cot(x)
Example
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
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)
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)
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
ans =
9*x*exp(-3*x) - 6*exp(-3*x)
x = sym("x");
f = x*Exp(-3*x);
differentiate(f, x, 2)
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.
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);
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.
Example
Let us find the stationary points of the function f(x) = 2x 3 + 3x2 − 12x + 17
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])
x = sym('x');
y = inline("2*x^3 + 3*x^2 - 12*x + 17");
g=
6*x^2 + 6*x - 12
x = sym("x");
y = 2*x^3 + 3*x^2 - 12*x + 17;
g = differentiate(y,x)
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)
s=
1
-2
x = sym("x");
y = 2*x^3 + 3*x^2 - 12*x + 17;
g = differentiate(y,x)
roots([6, 6, -12])
-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)
ans =
10
ans =
37
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.
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)'
Let us take up a simple example of a first order differential equation: y' = 5y.
s = dsolve('Dy = 5*y')
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.
ans =
exp(t)/2 - (3*exp(-t))/2