Matlab Basics
Matlab Basics
MATLAB BASICS
(I) logical operators:
Logical operators are used to compare the expressions or values.
a && b (and True if both a and b are true and output is 1. Otherwise output is 0
operator)
x = 4;
y = 3;
Ex.1: Write code to check whether x greater than 7 and y less than 4?
ans = logical
0
Ex.2: Write code to check whether x greater than 2 and y less than or equal 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
(x < 0) || (y == x)
ans = logical
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.
ans = 1×5
2 -4 0 -3 1
ans = 1×3
2 0 1
(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
Netbill(2000)
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)
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
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.
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”.
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)
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
Grade(70)
Grade(61)
Grade(42)
Grade(36)
Grade(34)
(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.
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.
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
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
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
% Observe if n = -5
Fibonacci(-5)
% Observe if n = 1
Fibonacci(1)
% Observe if n = 2
Fibonacci(2)
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
ans = 2×3
2 -1 0
-1 2 -1
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
while logicalcondition
Commands
end
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)
% test for n = 5
Factorial(5)
(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)
% test for n = 1
Prime(1)
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 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.
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.
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')