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

Matlab Basics

The document provides an overview of MATLAB basics, focusing on logical operators, control statements, loops, and functions. It includes examples of using if statements, for loops, while loops, and nested loops to perform various tasks such as calculating net bills, checking even/odd numbers, and generating Fibonacci numbers. Additionally, it covers built-in control statements like break, continue, and return for managing loop execution and program flow.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Matlab Basics

The document provides an overview of MATLAB basics, focusing on logical operators, control statements, loops, and functions. It includes examples of using if statements, for loops, while loops, and nested loops to perform various tasks such as calculating net bills, checking even/odd numbers, and generating Fibonacci numbers. Additionally, it covers built-in control statements like break, continue, and return for managing loop execution and program flow.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Differential Equations and Numerical Methods

MATLAB BASICS
(I) logical operators:
Logical operators are used to compare the expressions or values.

Logical Operator Description

a < b True if a is less than b and output is 1. Otherwise output is 0

a <= b True if a is less than or equal b and output is 1. Otherwise output is 0

a > b True if a is greater than b and output is 1. Otherwise output is 0

a >= b True if a is greater than or equal b and output is 1. Otherwise output is 0

a == b True if a is equal to b and output is 1. Otherwise output is 0

a ~= b True if a is not equal to b and output is 1. Otherwise output is 0

a && b (and True if both a and b are true and output is 1. Otherwise output is 0
operator)

a || b (or True if either a or b is true and output is 1. Otherwise output is 0


operator)

a & b Element wise and operator

a | b Element wise or operator

x = 4;
y = 3;

Ex.1: Write code to check whether x greater than 7 and y less than 4?

x > 7 && y < 4

ans = logical
0

Ex.2: Write code to check whether x greater than 2 and y less than or equal 4?

(x > 2) && (y <= 4)

ans = logical
1

Ex.3: Write code to check whether either x greater than or equal 4 or y less than 4?

(x >= 4) || (y < 4)

ans = logical
1

Ex.4: Write code to check whether either x is negative or y equals to x?

(x < 0) || (y == x)

ans = logical

Dr J Siva Ram Prasad; Dept. of Mathematics


1
Differential Equations and Numerical Methods
0

We can extract elements of a vector satisfying some condition

Ex.5: Let k = (2, -4, 6, 8, 0, -3, 10, 9, 1) be a vector. Write code to extract elements of k which are
(i) less than 5. (ii) less than 5 and greater than or equal zero.

k = [2, -4, 6, 8, 0, -3, 10, 9, 1];


k(k < 5)

ans = 1×5
2 -4 0 -3 1

k(k < 5 & k >= 0)

ans = 1×3
2 0 1

(II) Control Statements:


Controlling the flow of a program is an important task in the programming. There are one-way controlling,
two-way controlling and many-way controlling statements. All control statements ends with the line end after the
commands.

(1) if statement:
It is one-way controlling statement. The syntax is as follows.

if logical expression
commands
end

If the logical expression is True then the commands execute and the prompt comes to beyond the end
statement. If the logical expression is False, then the prompt directly comes to beyond the end statement. The
flow chart is as follows.

Ex.6: Create a function with name Netbill to print net bill amount subject to the condition. If the
total bill amount is more than Rs.1000, then a discount of 10% applied on total bill. The output is in
this format. "The total bill = 2000, Net bill = 1800."

function nb = Netbill(tb)
if tb > 1000
nb = tb * 0.9;
fprintf('The total bill = %f, Net bill = %f\n',tb, nb)
end
if tb <= 1000
fprintf('The total bill = %f, Net bill = %f\n',tb, nb)
end
end
% Check for the total bill Rs.2000

Dr J Siva Ram Prasad; Dept. of Mathematics


2
Differential Equations and Numerical Methods

Netbill(2000)

The total bill = 2000.000000, Net bill = 1800.000000


ans = 1800

% Check for the total bill Rs.900


Netbill(900)

The total bill = 900.000000, Net bill = 900.000000

(2) if else statement:


It is two-way controlling statement. The syntax is as follows.

if logical expression
commands1
else
commands2
end

If the logical expression is True then the commands1 execute and the prompt comes to beyond the end
statement. If the logical expression is False, then the commands2 execute and the prompt comes to beyond the
end statement. The flow chart is as follows.

Ex.7: Create a function with name Netbill1 to print net bill amount subject to the condition. If the
total bill amount is more than Rs.1000, then a discount of 10% applied on total bill. The output is in
this format. "The total bill = 900, Net bill = 900."

function nb = Netbill1(tb)
if tb > 1000
nb = tb * 0.9;
fprintf('The total bill = %f, Net bill = %f\n',tb, nb)
else
fprintf('The total bill = %f, Net bill = %f\n',tb, tb)
end
end
% Check for the total bill Rs.900
Netbill1(900)

The total bill = 900.000000, Net bill = 900.000000

Ex.8: Create a function with name Even_Odd to check a number is an even or odd. The output is in
this format. "The number 5 is an Odd number."

function Eo = Even_Odd(x)
if rem(x,2) == 0
fprintf('The number %d is an Even number\n',x)
else

Dr J Siva Ram Prasad; Dept. of Mathematics


3
Differential Equations and Numerical Methods

fprintf('The number %d is an Odd number\n',x)


end
end
% Check the number 5
Even_Odd(5)

The number 5 is an Odd number

% Check the number 20


Even_Odd(20)

The number 20 is an Even number

(3) if elseif else statement:


It is many-way controlling statement. The syntax is as follows.

if logical expression1
commands1
elseif logical expression2
commands2
else
commands3
end

If the logical expression1 is True then the commands1 execute and the prompt comes to beyond the end
statement. If the logical expression1 is False & logical expression2 is True then the commands2 execute and the
prompt comes to beyond the end statement. If the logical expression1 and logical expression2 are False then the
commands3 execute and the prompt comes to beyond the end statement. The flow chart is as follows.

We can insert more elseif controls in between if else block.

Ex.9: Create a function with name Grade to declare the grade to a student as follows. The output is
like “Marks = 95, Grade = Ex”.

Marks (x) x > 90 70 < x 90 50 < x 70 35 x 50 x < 35

Grade Ex A B C Fail

Check the grades for the marks 92, 70, 61, 52 36, 34

function g = Grade(x)
if x > 90
fprintf('Marks = %f, Grade = Ex.\n', x)
elseif x > 70
fprintf('Marks = %f, Grade = A.\n', x)

Dr J Siva Ram Prasad; Dept. of Mathematics


4
Differential Equations and Numerical Methods

elseif x > 50
fprintf('Marks = %f, Grade = B.\n', x)
elseif x >= 35
fprintf('Marks = %f, Grade = C.\n', x)
else
fprintf('Marks = %f, Grade = Fail.\n', x)
end
end

% Check for the marks 92, 70, 61, 42, 36, 34


Grade(92)

Marks = 92.000000, Grade = Ex.

Grade(70)

Marks = 70.000000, Grade = B.

Grade(61)

Marks = 61.000000, Grade = B.

Grade(42)

Marks = 42.000000, Grade = C.

Grade(36)

Marks = 36.000000, Grade = C.

Grade(34)

Marks = 34.000000, Grade = Fail.

(III) Loops:
Loops are used to perform the operations repeatedly (iteratively) to a specified or unspecified number of
times in a program. There are two types of loops in Matlab depending on how the repetitions are terminated. Both
loops ends with the line end after the commands.

(1) for loop:


When the number of repetitions (iterations) is known in advance, for loop is used. The syntax
is as follows.

for index = a:h:b


commands
end

Here index is variable name, a is starting value and b is final value of the index, h is step length of
indices. index starts with a and the commands are executed. Then index variable is increased by h and if it is
less than or equal b, again the commands are executed. The process continues until the index value becomes
greater than b. Flow of the for loop is as follows.

Dr J Siva Ram Prasad; Dept. of Mathematics


5
Differential Equations and Numerical Methods

Ex.10: Create a function with name Math_Table to print mathematical table of a number. Here input
is the number p and the table contains first n multiples of the number.

function t = Math_Table(p,n)
for i = 1:n
fprintf('%d x %d = %d\n', p, i, p*i)
end
end

% Print the table of 9 up to 10 multiples


Math_Table(9, 10)

9 x 1 = 9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
9 x 10 = 90

% Print the table of 7 up to 5 multiples


Math_Table(7, 5)

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

Ex-11: Write function with name Fibonacci to generate the nth (n > 2) Fibonacci number and
Fibonacci series. The output is in the form "8th Fibonacci number is ‘

function f = Fibonacci(n)
if n <= 0
fprintf('Enter positive integer\n')
elseif n == 1
fprintf('%dst Fibonacci number is 1\n', n)
elseif n == 2
fprintf('%dnd Fibonacci number is 1\n', n)
fprintf('1 1\n')
else
f(1) = 1;
f(2) = 1;
for i = 3:n
f(i) = f(i-1) + f(i-2);
end
fprintf('%dth Fibonacci number is %d\n', n, f(n))
Dr J Siva Ram Prasad; Dept. of Mathematics
6
Differential Equations and Numerical Methods

end
end

% print 8th Fibonacci number


Fibonacci(8)

8th Fibonacci number is 21


ans = 1×8
1 1 2 3 5 8 13 21

% Observe if n = -5
Fibonacci(-5)

Enter positive integer

% Observe if n = 1
Fibonacci(1)

1st Fibonacci number is 1

% Observe if n = 2
Fibonacci(2)

2nd Fibonacci number is 1


1 1

(2) nested loop:


Nesting means placing one structure within other structure. We can insert for loop within the
for loop or control statement.

Ex-12: Write function with name TriDiaMatrix to generate m x n tridiagonal matrix A given by

A(i, j) =

function A = TriDiaMatrix(m,n)
for i = 1:m
for j = 1:n
if i == j
A(i,j) = 2;
elseif abs(i-j) == 1;
A(i,j) = -1;
else
A(i,j) = 0;
end
end
end
end

% Print 2x3 Tridiagonal matrix


TriDiaMatrix(2,3)

ans = 2×3
2 -1 0
-1 2 -1

% Print 5x5 Tridiagonal matrix

Dr J Siva Ram Prasad; Dept. of Mathematics


7
Differential Equations and Numerical Methods

TriDiaMatrix(5,5)

ans = 5×5
2 -1 0 0 0
-1 2 -1 0 0
0 -1 2 -1 0
0 0 -1 2 -1
0 0 0 -1 2

(3) while loop:


When the number of repetitions is unknown, while loop is used. while loop is based on a
logical condition. The operations repeat until the logical condition is true. Once the logical condition become false,
the prompt comes out from the loop. The syntax is as follows.

while logicalcondition
Commands
end

Flow of the while loop is as follows.

Ex-13: Write function with name Factorial to find the first integer x whose factorial is a n-digit
number. The output is like this “The first integer is 5 whose factorial is 3 digit number”.

function x = Factorial(n)
x = 1;
fact = 1;
while fact < 10^(n-1)
x = x + 1;
fact = fact*x;
end
fprintf('The first integer is %d whose factorial is %d digit number\n', x, n)
end

% test for n = 3
Factorial(3)

The first integer is 5 whose factorial is 3 digit number


ans = 5

% test for n = 5
Factorial(5)

The first integer is 8 whose factorial is 5 digit number


ans = 8

Dr J Siva Ram Prasad; Dept. of Mathematics


8
Differential Equations and Numerical Methods

(IV) Other Control Statements:


Sometimes we require pre-termination of for loop or while loop, or to continue the iteration without
executing the commands, or to terminate the whole programme. To handle these situations, Matlab has built-in
control statements.

(1) break:
break statement is used to terminate the execution of for loop or while loop
prematurely. In nested loops break terminates the inner loop only in which it appears.

(2) continue:
continue statement is used to skip the current iteration and to pass to next iteration in
for loop or while loop.

(3) return:
return statement is used to terminate the entire program before it reaches to end.

Ex-14: Create a function with name Prime to check a number greater than 2 is prime number or not.
The output is in the form. 'Enter a number greater than 2' or '5 is prime number' or '10 is not a prime
number'.

function p = Prime(n)
if n <= 2
fprintf('Enter a number greater than 2\n')
return
else
for i = 2:ceil(n/2)
if rem(n,i) == 0
fprintf('%d is not a prime number\n',n)
return
end
end
fprintf('%d is a prime number\n',n)
end
end

% test for n = 5
Prime(5)

5 is a prime number

% test for n = 10
Prime(10)

10 is not a prime number

% test for n = 1
Prime(1)

Enter a number greater than 2

(V) Creating Simple Plots:


The plot function has different forms depending on the input arguments. If y is a vector plot(y)
produces a piecewise linear graph of the elements of y versus the index of the elements of y. If we specify two
vectors ‘x’ and ‘y’, then plot(x, y, ’s’) produces a graph of y versus x.
Dr J Siva Ram Prasad; Dept. of Mathematics
9
Differential Equations and Numerical Methods
Here ‘s’ is the character string which is combination of one element from any or all the following columns.

Color Marker Line Style

b - blue (default) . point - solid line (default)

g - green * star : dotted line

r - red o circlr -. dash dot line

k - black x x-mark -- dashed line

y - yellow + plus

c - cyan s square

We can add names to x-axis and y-axis by using the functions xlabel(‘text’) and
ylabel(‘text1’)respectively. Here text and text1 are the names of x-axis and y-axis respectively.

We can add title to the graph using the function title(‘text’).

We can add labels to the different curves drawn on the same graph using the function legend(‘text1’,
‘text2’), here text1, text2 are the labels of the two curves drawn in the graph.

We can insert grid lines in the graph using grid on command.

Ex-15: Plot the graphs of f(x) = 2 Cosx; g(x) = Cosx; h(x) = 0.5 Cosx in the range [0, 2π] by splitting it
in to 20 equal points. Insert x label as “x”, y label as “cos” and title of the graph as “Cosine curves”.
The line of f(x) is red solid line, g(x) is black dotted line and h(x) is blue solid line. Insert legend also.

x = linspace(0, 2*pi, 20);


f = 2*cos(x);
g = cos(x);
h = 0.5*cos(x);
plot(x,f,'-r', x,g,':k', x,h,'-b')
legend('2 Cosx', 'Cosx', '0.5 Cosx')
xlabel('x')
ylabel('Cos')
title('Cosine Curves')
grid on

Dr J Siva Ram Prasad; Dept. of Mathematics


10
Differential Equations and Numerical Methods

Ex-16: Plot the line y = 2x and parabola = 2y in the range [-2, 2] by splitting it in to equal points of
width 0.1. Insert x label as “x”, y label as “y” and title of the graph as “Parabolas”. The parabola =
2x is yellow solid line with circle marker, = 2y is green dashed line with star marker. Insert legend
also.

y = 2x Let f = 2x

= 2y y= Let g =

x = -2:0.1:2;
f = 2*x;
g = x.^2/2;
plot(x,f,'-yo', x,g,'--g*')
grid on
legend('y = 2x', 'x2 = 2y')
xlabel('x')
ylabel('y')
title('Parabolas')

Dr J Siva Ram Prasad; Dept. of Mathematics


11

You might also like