Basic MATLAB CODES
Basic MATLAB CODES
S. No Experiment Page.No
1 UNIT-I MATLAB BASICS
Introduction, MATLAB environment, MATLAB as a calcu- later,
MATLAB Online, Syntax and Semantics, Help, Data Types-Matrix, string,
cell and structure, Variables and Arrays, Initializing Variables,
Multidimensional Arrays, sub-arrays, Special Values, Displaying Output
Data, Data Files, Scalar and Array Operations, Hierarchy of Operations,
Built-in MATLAB Functions, Debugging MATLAB Programs.
1.3 Swap the values in two variable s without using temporary
variable.
1.4 Write a code to find whether the given number is even or not.
1.3 Write a function which should return either maximum or
minimum value of the element in an array.
1.4 Write a function that should sort the elements in the array
either in the ascending order or descending order
1.5 Write a program which should count the number of occurrences of
particular element in the array.
2 UNIT-II MATRICES AND OPERATORS
2.1 Write a program to find the maximum and minimum value of the
elements of the matrix
2.2 Write a program to compute the sum of diagonal elements of the given
matrix
2.3 Write a program to test whether the given matrix is
symmetric or not?
2.4 Obtain the rank of the following matrices
2.5 Write a program to check whether the given matrix is
invertible or not?
2.6 Write a program to check the given matrix is orthogonal or not?
2.7 Use the built-in function to compute the Eigen value and the Eigen
vector of the given matrix.
2.8 From the Eigen value is it possible to find whether the given matrix is
(i) Positive definite (ii)Positive semidefinite.
2.9 Create a vecto 10. Write a
code to perform the following operation
2.9.1
2.9.2 Make all the even indexed elements to zero.
2.9.3 Make all the odd indexed elements to zero
17
2.9.4
2.9.5 Generate
elements to zero
2.9.6 Add the
2.9.7
2.10 Write a program to solve the linear algebraic equation
2.11 Write a program to determine the eigen vector and eigen values of A
3 UNIT-III FUNCTIONS AND EXPRESSIONS
Introduction, Function I/O, Formal Definition of Functions, Sub
functions, Scope, Advantages of Functions, Scripts, and Problem-
Solving File Input-Output, Expressions, write a function which returns
the
3.1 Write a code to print the prime numbers from one to hundred.
3.2 Write a function which accepts the radius of the circle as input and
returns the area and perimeter of the circle.
3.3 Write a code which will compute sum of integers ranging
from 1 to 100.
3.4 t
to the code should be (i) Weight and (ii) Height of the person.
The output of ndex
3.5 Write a program to convert the temperature in degrees to
Celsius.
3.6 Write a program to check whether the given string (word) is palindrome
or not?
3.7 Find the roots of the polynomial
3.8 Analyse the RLC Circuit using suitable value of R L and C.
3.9 Analyse the function using Taylor series.
4 UNIT IV FLOW CONTROL AND FILES
18
¢) print the output as shown below
4.4 Write a program to f in d the current I in the circuit shown
below
a) By using conditional statements.
b) Without using any conditional statements.
5 UNIT V PLOTTING AND SIMULINK
Two Dimensional Plots- Plot, fplot, Multiple Graphs, Formatting,
Logarithmic Axes, Error Bars, Special Graphics, Histograms, Polar Plots ,
Multiple Plots on The Same Page, Multiple Figure Windows, Three-
Dimensional Plots- Line Plots, Mesh and Surface Plots, Special Graphics,
View Command. Simulink : Getting Started, Simulink Library Browser,
BasicElements-Blocks,Lines,building a System-Ga the ring Blocks,
Modifying theBlocks, Connecting theBlocks, Running Simulations,
Specification, Toolboxes, Building Systems.
5.1 The expression for sine wave is given by x( ¢) = Asin(27ft + ¢) Write
a code which accepts the input as (i ) Amplitude (A) (ii) Frequency (f) and
(iii) Phase(¢ )and generates the sine wave and plot the sine wave.
5.2 Write a program to convert the sine wave to (i) Half wave
rectified sinewave and (ii) Full wave rectified sine wave
5.3 Write a program which converts the sine wave to a square wave
Equivalent to - in
19
GENERAL GUIDELINES AND SAFETY INSTRUCTIONS
1. Sign in the log register as soon as you enter the lab and strictly observe your lab
timings.
2. Strictly follow the written and verbal instructions given by the teacher / Lab
Instructor. If you do not understand the instructions, the handouts and the procedures,
ask the instructor or teacher.
3. Never work alone! You should be accompanied by your laboratory partner and / or
the instructors / teaching assistants all the time.
4. It is mandatory to come to lab in a formal dress and wear your ID cards.
5. Do not wear loose-fitting clothing or jewelry in the lab. Rings and necklaces are usual
excellent conductors of electricity.
6. Mobile phones should be switched off in the lab. Keep bags in the bag rack.
7. Keep the labs clean at all times, no food and drinks allowed inside the lab.
8. Intentional misconduct will lead to expulsion from the lab.
9. Do not handle any equipment without reading the safety instructions. Read the
handout and procedures in the Lab Manual before starting the experiments.
10. Do your wiring, setup, and a careful circuit checkout before applying power. Do not
make circuit changes or perform any wiring when power is on.
11. Avoid contact with energized electrical circuits.
12. Do not insert connectors forcefully into the sockets.
13. NEVER try to experiment with the power from the wall plug.
14. Immediately report dangerous or exceptional conditions to the Lab instructor /
teacher: Equipment that is not working as expected, wires or connectors are broken,
20
EXPERIMENT NO. 1
OBJECTIVE: Study about the MATLAB BASICS and write the MATLAB program to
perform the following tasks:
1.5 Swap the values in two variable s without using temporary variable.
1.6 Write a code to find whether the given number is even or not.
1.3 Write a function which should return either maximum or minimum value of the
element in an array.
1.4 Write a function that should sort the elements in the array either in the ascending order
or descending order
1.5 Write a program which should count the number of occurrences of particular element in
the array.
:
SOFTWARE REQUIRED:
1.A. INTRODUCTION
MATLAB is a high-performance language for technical computing. It integrates computation,
visualization, and programming in an easy-to-use environment where problems and solutions are
expressed in familiar mathematical notation. The name MATLAB stands for matrix laboratory.
MATLAB was originally written to provide easy access to matrix.
21
3- Current Directory Browser: MATLAB file operations use the current directory
reference point. Any file you want to run must be in the current directory or on the
search path.
4-Workspace: The MATLAB workspace consists of the set of variables (named
arrays) built up during a MATLAB session and stored in memory.
1.1 Swap the values in two variable s without using temporary variable.
A. Solution: Swap with variable.
clc
clear all
close all
x1=input ('enter the first number X1: ');
x2=input ('enter the second number X2: ');
%swap using third variable
temp=x1;
x1=x2;
x2=temp;
disp('x1 is ')
22
disp(x1)
disp('x2 is ')
disp(x2)
1.2 Write a code to find whether the given number is even or not.
Solution:
clc
clear all
close all
% Program to check Even or Odd number
x=input('enter the no. ');
if mod(x,2)==0
disp('no is even ');
else
disp('no is odd ');
end
% Program to Generate Even and Odd number
xx=input('Enter the Even/Odd no. ')
k=1; % For Even
l=1; % For Odd
for i=1:xx
if mod(i,2)==0
even(k)=i;
k=k+1;
else
odd(l)=i;
l=l+1;
end
end
disp('Even no ')
23
disp(even);
disp('Odd no ')
disp(odd);
1.3 Write a function which should return either maximum or minimum value of the
element in an array.
Solution:
clc
clear all
close all
x=input('enter the number x ');
y=input ('enter the number y ');
disp ('max no is ');
if x>y
disp(x);
else
disp(y);
end
% max function
disp('using max function');
disp(max(x,y));
a=[1 2 8];
disp('max no. is A ')
disp(max(a));
b=[3 5 7];
disp('max no. is B ')
disp(max(b));
%for min replace max by min
disp('min A is ');
disp(min(a));
disp('min B is ');
disp(min(b));
1.4 Write a function that should sort the elements in the array either in the ascending
order or descending order.
Solution:
% Matlab function for Sort the Element
% Syntex
% First Example
%A=[10,20,1,3,89,100];
A=[10,40,30;100,200,1;11,77,15]
% Function
Ans=sort(A,2,'descend');
24
% Display Result
disp('Result: ');
disp(Ans);
1.5 Write a program which should count the number of occurrences of particular
element in the array.
Solution:
Clc;
Clear all;
x = [10 25 4 10 9 4 4]';
[GC,GR] = groupcounts(x)
GC =
3
1
2
1
GR =
4
9
10
25
25
EXPERIMENT NO. 2
OBJECTIVE: Study about the Matrices and operators and write the MATLAB program to
perform the following tasks:
2.1 Write a program to find the maximum and minimum value
of the elements of the matrix.
2.2 Write a program to compute the sum of diagonal elements
Of the given matrix
2.3 Write a program to test whether the given matrix is
symmetric or not?
2.4 Obtain the rank of the following matrices
2.5 Write a program to check whether the given matrix is
invertible or not?
2.6 Write a program to check the given matrix is orthogonal or
not?
2.7 Use the built-in function to compute the Eigen value and the
Eigen vector of the given matrix.
2.8 From the Eigen value is it possible to find whether the given
matrix is (i) Positive definite (ii)Positive semidefinite.
2.9 Create a vecto
10. Write a code to perform the following operation
2.9.1
2.9.2 Make all the even indexed elements to zero.
2.9.3 Make all the odd indexed elements to zero
2.9.4
2.9.5 Generate
elements to zero
2.9.6
2.9.7
2.10 Write a program to solve the linear algebraic equation
2.11 Write a program to determine the Eigen vector and Eigen
values of A
26
2.A MATRICES AND OPERATORS
2.A.1 Introduction, Colon Operator, Accessing Parts of a Matrix, Combining and Transforming
Matrices, Arithmetic operations
1 2 3 4 6 4 3 4 5
Now let's add 2 to each element of our vector, a, and store the result in a new vector.
Notice how MATLAB requires no special handling of vector or matrix math.
b=a+2
b = 1×9
3 4 5 6 8 6 5 6 7
Creating graphs in MATLAB is as easy as one command. Let's plot the result of our vector
addition with grid lines.
plot(b)
grid on
27
MATLAB can make other graph types as well, with axis labels.
bar(b)
xlabel('Sample #')
ylabel('Pounds')
28
One area in which MATLAB excels is matrix computation.
Creating a matrix is as easy as making a vector, using semicolons (;) to separate the rows of a
matrix.
A = [1 2 0; 2 5 -1; 4 10 -1]
A = 3×3
1 2 0
2 5 -1
4 10 -1
1 2 4
2 5 10
0 -1 -1
5 12 24
12 30 59
24 59 117
Instead of doing a matrix multiply, we can multiply the corresponding elements of two
matrices or vectors using the .* operator.
C = A .* B
C = 3×3
1 4 0
4 25 -10
0 -10 1
Let's use the matrix A to solve the equation, A*x = b. We do this by using the \ (backslash)
operator.
29
b = [1;3;5]
b = 3×1
1
3
5
x = A\b
x = 3×1
1
0
-1
0
0
0
MATLAB has functions for nearly every type of common matrix calculation.
There are functions to obtain eigenvalues ...
eig(A)
ans = 3×1
3.7321
0.2679
1.0000
12.3171
0.5149
0.1577
30
The "poly" function generates a vector containing the coefficients of the characteristic
polynomial.
The characteristic polynomial of a matrix A is
det( A)
p = round(poly(A))
p = 1×4
1 -5 5 -1
We can easily find the roots of a polynomial using the roots function.
These are actually the eigenvalues of the original matrix.
roots(p)
ans = 3×1
3.7321
1.0000
0.2679
plot(r);
31
At any time, we can get a listing of the variables we have stored in memory using
the who or whos command.
whos
Name Size Bytes Class Attributes
A 3x3 72 double
B 3x3 72 double
C 3x3 72 double
a 1x9 72 double
ans 3x1 24 double
b 3x1 24 double
p 1x4 32 double
q 1x7 56 double
r 1x10 80 double
x 3x1 24 double
You can get the value of a particular variable by typing its name.
A
A = 3×3
32
1 2 0
2 5 -1
4 10 -1
You can have more than one statement on a single line by separating each statement with
commas or semicolons.
If you don't assign a variable to store the result of an operation, the result is stored in a temporary
variable called ans.
sqrt(-1)
ans = 0.0000 + 1.0000i
As you can see, MATLAB easily deals with complex numbers in its calculations.
2.1 Write a program to find the maximum and minimum value of the elements of the
matrix.
A = [23 42 37 18 52];
M = max(A)
A = [23 42 37 18 52];
M = min(A)
2.2 Write a program to compute the sum of diagonal elements of the given matrix.
A = [1 -5 2;
-3 7 9;
4 -1 6];
b = trace(A)
2.3 Write a program to test whether the given matrix is symmetric or not?
Step-1: Create a 3-by-3 matrix.
A = [1 0 1i; 0 1 0;-1i 0 1]
A = 3×3 complex
33
tf = logical
0
The result is logical 0 (false) because A is not symmetric. In this case, A is equal to its
complex conjugate transpose, A', but not its nonconjugate transpose, A.'.
Change the element in A(3,1) to be 1i.
A(3,1) = 1i;
The matrix, A, is now symmetric because it is equal to its nonconjugate transpose, A.'.
I = eye( n ) returns an n -by- n identity matrix with ones on the main diagonal and zeros
elsewhere. I = eye( n , m ) returns an n -by- m matrix with ones on the main diagonal and zeros
elsewhere. I = eye( sz ) returns an array with ones on the main diagonal and zeros elsewhere. The
size vector, sz , defines size(I) .The rank is rank(A) which is 4.
(ii)
1 0 0 0
0 j 1 j
X=
0 1 1 1
0 j 1 j
2.5 Write a program to check whether the given matrix is invertible or not?
Program:
clear all;
close all;
clc;
34
A = 0.1*eye(300);
det(A)
if det (A)==0
disp('not invertible')
else
disp('invertible')
end
35
2.7 Use the built-in function to compute the Eigen value and the Eigen vector of the given
matrix.
Program:
A = [1 2 3; 4 5 6; 7 8 9] %Input Matrix
A = [1 2 3; 4 5 6; 7 8 9];
lambda = eig(A)
P=poly(A)
[eigvec, eigval] = eig(A)
Output
eigvec =
-0.2320 -0.7858 0.4082
-0.5253 -0.0868 -0.8165
-0.8187 0.6123 0.4082
eigval =
16.1168 0 0
0 -1.1168 0
0 0 -0.0000
2.8 From the Eigen value is it possible to find whether the given matrix is (i) Positive
definite (ii)Positive semidefinite.
A matrix M is called positive semidefinite if it is symmetric and all its eigenvalues are non-negative. If all
eigenvalues are strictly positive, then it is called a positive definite matrix.
Program: A = [1 2 3; 4 5 6; 7 8 9];
lambda = eig(A)
P=poly(A)
[eigvec,eigval] = eig(A)
isSym=@(A) isequal(A,A.');
disp('The given matrix is a symmetric matrix');
36
Output: Eigen_values_and_Eigen_Vectors
lambda =
16.1168
-1.1168
-0.0000
P=
1.0000 -15.0000 -18.0000 -0.0000
eigvec =
-0.2320 -0.7858 0.4082
-0.5253 -0.0868 -0.8165
-0.8187 0.6123 0.4082
eigval =
16.1168 0 0
0 -1.1168 0
0 0 -0.0000
37
2.9.2 Make all the even indexed elements to zero.
Program:
clc; clear all;
x= uint32(1):uint32(10)
X(2:2:end)=0
2.9.3 Make all the odd indexed elements to zero.
Program:
clc; clear all;
x= uint32(1):uint32(10)
X (1:2: end) =0
Program:
clc; clear all;
x= uint32(1):uint32(10)
Y=flip(X);
elements to zero.
Program:
clc; clear all;
x= uint32(1):uint32(10)
X(6:10)=0;
Y=X;
.
Program:
clc; clear all;
x= uint32(1):uint32(10)
X(1:2:end) = X(1:2:end) + 3
38
Program:
syms x y z
eqn1 = 5*x - 3*y + 2*z == 10;
eqn2 = -3*x + 8*y + 4*z == 20;
eqn3 = 2*x + 4*y - 9*z == 9;
[A, B] = equationsToMatrix([eqn1, eqn2, eqn3], [x, y, z])
X = linsolve(A,B)
Ans:
X= 1512/439
1404/439
521/439
39