PRACTICAL-1
AIM: Creating a One and Two-Dimensional Array (Row / Column Vector) (Matrix of given size) then,
(A). Performing Arithmetic Operations - Addition, Subtraction, Multiplication and Exponentiation.
(B). Performing Matrix operations - Inverse, Transpose, Rank with plots.
APPARATUS REQUIRED: Matlab2019.
THEORY:
MATLAB
MATLAB (matrix laboratory) is a multi-paradigm numerical computing environment and proprietary
programming language developed by MathWorks. MATLAB allows matrix manipulations, plotting
of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with
programs written in other languages.Although MATLAB is intended primarily for numerical computing,
an optional toolbox uses the MuPAD symbolic engine allowing access to symbolic computing abilities.
ARRAY
An array is collection of items stored at contiguous memory locations. The idea is to store multiple
items of same type together. This makes it easier to calculate the position of each element by simply
adding an offset to a base value, i.e., the memory location of the first element of the array (generally
denoted by the name of the array).
VECTORS AND MATRICES
Vectors and matrices combine scalar data into a single, multidimensional data object. You can modify
individual elements or perform arithmetic on entire vectors and matrices. For more information,
see Supported Operations for Vectors and Matrices.
USE OPERANDS OF EQUAL DIMENSIONS FOR ELEMENT-WISE OPERATIONS
If you perform element-wise operations on vectors or matrices with unequal dimensions, the chart
generates a size mismatch error when you simulate the model. For more information, see Supported
Operations for Vectors and Matrices.
DO NOT DEFINE VECTORS AND MATRICES WITH THE ML BASE TYPE
The ml base type supports only scalar data. If you define a vector or matrix with the ml base type, the
chart generates an error when you simulate the model. For more information, see ml Data Type.
DO NOT USE COMPLEX NUMBERS TO SET THE INITIAL VALUES OF VECTORS AND
MATRICES
If you initialize an element of a vector or matrix by using a complex number, the chart generates an
error when you simulate the model. You can set the values of vectors and matrices to complex
numbers after initialization. For more information, see Complex Data in Stateflow Charts.
DO NOT USE VECTORS AND MATRICES IN TEMPORAL LOGIC OPERATORS
Because time is a scalar quantity, you cannot use a vector or matrix as an argument for a temporal
logic operator. For more information, see Control Chart Execution by Using Temporal Logic.
ARITHMATIC OPERATIONS
ADDITION(+):Addition or unary plus. A+B adds A and B.A and B must have the same size,
unless one is a scalar. A scalar can be added to a matrix of any size.
SUBTRACTION(-): Subtraction or unary minus. A-B subtracts B from A.A and B must have the
same size, unless one is a scalar. A scalar can be subtracted from a matrix of
any size.
MULTIPLICATION(*): Matrix multiplication. C = A*B is the linear algebraic product of the
matrices A and B. More precisely,
DIVISION(/): Slash or matrix right division. B/A is roughly the same as B*inv (A). More
precisely, B/A = (A'\B')'. See the reference page for mrdivide for more
information.
EXPONENTION Y = exp(X) returns the exponential exp for each element in array X. For
(EXP): complex elements z = x + iy, it returns the complex exponential.
MATRIX OPERATIONS
INVERSE: If a matrix A is square and nonsingular (nonzero determinant), then the
equations AX = I and XA = I have the same solution X. This solution is called
the inverse of A and is denoted A-1. The inv function and the expression A^-1 both compute
the matrix inverse.
TRANSPOSE: For real matrices, the transpose operation interchanges aij and aji. For complex
matrices, another consideration is whether to take the complex conjugate of complex
entries in the array to form the complex conjugate transpose. MATLAB uses the apostrophe
operator (') to perform a complex conjugate transpose, and the dot-apostrophe operator (.')
to transpose without conjugation. For matrices containing all real elements, the two
operators return the same result.
RANK: The rank function provides an estimate of the number of linearly independent rows
or columns of a full matrix.k = rank (A) returns the number of singular values of A that are
larger than the default tolerance, max (size (A))*norm (A)*eps.k = rank (A, tol) returns the
number of singular values of A that are larger than tol.
(A). PERFORMING ARITHMETIC OPERATIONS - ADDITION, SUBTRACTION, MULTIPLICATION
AND EXPONENTIATION.
CODE:
A = [1 0; 2 4]
B = [5 9; 2 1]
add = A + B
sub = A-B
mul = A*B
div = B/5
exp = exp(A)
OUTPUT:
A=
1 0
2 4
B=
5 9
2 1
add =
6 9
4 5
sub =
-4 -9
0 3
mul =
5 9
18 22
div =
1.0000 1.8000
0.4000 0.2000
expo =
2.7183
(B). PERFORMING MATRIX OPERATIONS - INVERSE, TRANSPOSE, RANK WITH PLOTS.
CODE:
A = [1 2 3;5 7 2;8 9 4]
rank = rank(A)
inverse = inv(A)
transpose = A'
OUTPUT:
A=
1 2 3
5 7 2
8 9 4
rank =
inverse =
-0.3226 -0.6129 0.5484
0.1290 0.6452 -0.4194
0.3548 -0.2258 0.0968
transpose =
1 5 8
2 7 9
3 2 4
PRACTICAL-2
AIM: Performing Matrix Manipulations - Concatenating, Indexing, Sorting, Shifting, Reshaping,
Resizing and Flipping about a Vertical Axis / Horizontal Axis; Creating Arrays X & Y of given size (1 x N)
and Performing
(A). Relational Operations - >, <, ==, <=, >=, ~=
(B). Logical Operations - ~, &, |, XOR
APPARTUS REQUIRED: Matlab 2019.
THEORY:
CONCATENATION
You can concatenate two matrices to create a larger matrix. The pair of square brackets '[]' is the
concatenation operator.MATLAB allows two types of concatenations:
Horizontal concatenation
Vertical concatenation
When you concatenate two matrices by separating those using commas, they are just appended
horizontally. It is called horizontal concatenation.Alternatively, if you concatenate two matrices by
separating those using semicolons, they are appended vertically. It is called vertical concatenation.
INDEXING
Indexing into a matrix is a means of selecting a subset of elements from the matrix. MATLAB ® has
several indexing styles that are not only powerful and flexible, but also readable and expressive.
Indexing is a key to the effectiveness of MATLAB at capturing matrix-oriented ideas in understandable
computer programs.Indexing is also closely related to another term MATLAB users often hear:
vectorization.
SORTING
If A is a vector, then sort (A) sorts the vector elements.If A is a matrix, then sort (A) treats the columns
of A as vectors and sorts each column.If A is a multidimensional array, then sort (A) operates along the
first array dimension whose size does not equal 1, treating the elements as vectors.
SHIFTING
If A is an array of signed integers, then bitshift returns the arithmetic shift results, preserving the
signed bit when k is negative, and not preserving the signed bit when k is positive.If k is positive,
MATLAB® shifts the bits to the left and inserts k 0-bits on the right.
RESHAPING & RESIZING
B = reshape (A,sz) reshapes A using the size vector, sz, to define size(B). For example, reshape (A, [2,
3]) reshapes A into a 2-by-3 matrix. sz must contain at least 2 elements, and prod(sz) must be the
same as numel(A).B = reshape (A, sz1,... szN) reshapes A into a sz1-by-...-by-szN array
where sz1,...,szN indicates the size of each dimension.
FLIPPING
If A is vector, then flip(A) reverses the order of the elements along the length of the vector.If A is a
matrix, then flip(A) reverses the elements in each column.If A is an N-D array, then flip(A) operates on
the first dimension of A in which the size value is not 1.
RELATIONAL OPERATOR
In computer science, a relational operator is a programming language construct or operator that tests
or defines some kind of relation between two entities. These include numerical equality (e.g., 5 = 5)
and inequalities (e.g., 4 ≥ 3).In programming languages that include a distinct boolean data type in
their type system, like Pascal, Ada, or Java, these operators usually evaluate to true or false,
depending on if the conditional relationship between two operands holds or not.
Symbol Description
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to
LOGICAL OPERATORS
The logical data type represents true or false states using the numbers 1 and 0, respectively. Certain
MATLAB® functions and operators return logical values to indicate fulfillment of a condition. You can
use those logical values to index into an array or execute conditional code. For more information, see
how to find Array Elements That Meet a Condition.
Short-circuit &&, || Logical operations with short-circuiting
& Find logical AND
~ Find logical NOT
| Find logical OR
xor Find logical exclusive-OR
all Determine if all array elements are nonzero or true
any Determine if any array elements are nonzero
false Logical 0 (false)
find Find indices and values of nonzero elements
islogical Determine if input is logical array
logical Convert numeric values to logicals
true Logical 1 (true)
CONCATENATION
CODE:
A = [2 3 4,5 6 7,1 5 6]
B = [6 5 8,2 6 8,9 2 6]
A1 = cat(1,A,B)
A2 = cat(2,A,B)
OUTPUT:
A=
2 3 4 5 6 7 1 5 6
B=
6 5 8 2 6 8 9 2 6
y=
2 3 4 5 6 7 1 5 6
6 5 8 2 6 8 9 2 6
z=
2 3 4 5 6 7 1 5 6 6 5 8 2 6 8 9 2 6
SORTING
CODE:
A = [2 3 4,5 6 7,1 5 6]
B = [6 5 8,2 6 8,9 2 6]
A3 = magic(5)
B3 = sort(A)
C1 = sort(A,'ascend')
C2 = sort(A,'descend')
C3 = sortrows(A,1)
OUTPUT:
A=
2 3 4 5 6 7 1 5 6
B=
6 5 8 2 6 8 9 2 6
A3 =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
B3 =
1 2 3 4 5 5 6 6 7
C1 =
1 2 3 4 5 5 6 6 7
C2 =
7 6 6 5 5 4 3 2 1
C3 =
2 3 4 5 6 7 1 5 6
INDEXING
CODE:
A = [2 3 4,5 6 7,1 5 6]
A(3)
OUTPUT:
A=
2 3 4 5 6 7 1 5 6
ans =
RESHAPING AND RESIZING MATRIX
CODE:
A = 1:10;
B = reshape(A,[5,2])
A1 = [2 3 4;5 6 7;1 5 6]
A3 = rot90(A1)
OUTPUT:
B = 5×2
1 6
2 7
3 8
4 9
5 10
A1 =
2 3 4
5 6 7
1 5 6
A3 =
4 7 6
3 6 5
2 5 1
FLIPPING
CODE:
A = [2 3 4;5 6 7;1 5 6]
E1 = fliplr(A)
OUTPUT:
A=
2 3 4
5 6 7
1 5 6
E1 =
4 3 2
7 6 5
6 5 1
LOGICAL OPERATIONS
CODE:
A = [0110101001]
B = [1010100101]
E2 = xor(A,B)
E3 = or(A,B)
F1 = and(A,B)
F2 = not(A)
OUTPUT:
A=
110101001
B=
1.0101e+09
E2 =
logical
0
E3 =
logical
F1 =
logical
F2 =
logical
RELATIONAL OPERATOR
CODE:
A = [123]
B = [321]
display(A>B)
display(A<B)
display(A==B)
display(A>=B)
display(A<=B)
display(A~=B)
OUTPUT:
A=
123
B=
321
logical
0 %Greater than
logical
1 %Less than
logical
0 %Equal to
logical
0 %Greater than equal to
logical
1 %Less than equal to
logical
1 %Not equal to
PRACTICAL-3
AIM: Generating a set of Commands on a given Vector (Example: X = [1 8 3 9 0 1]) to
(A). Add up the values of the elements (Check with sum)
(B). Compute the Running Sum (Check with sum), where Running Sum for element j = the sum of the
elements from 1 to j, inclusive.
(C) Generating a Random Sequence using rand() / randn() functions and plot them.
APPARATUS REQUIRED: Matlab 2019.
THEORY:
VECTOR
In MATLAB a vector is a matrix with either one row or one column. The distinction between row
vectors and column vectors is essential. Many programming errors are caused by using a row vector
where a column vector is required, and vice versa. MATLAB vectors are used in many situations, e.g.,
creating x-y plots that do not fall under the rubric of linear algebra. In these contexts a vector is just a
convenient data structure.
FUNCTIONS USED
Sum (): if A is a vector, then sum(A) returns the sum of the elements.If A is a matrix,
then sum(A) returns a row vector containing the sum of each column.If A is a
multidimensional array, then sum(A) operates along the first array dimension whose size does
not equal 1, treating the elements as vectors. This dimension becomes 1 while the sizes of all
other dimensions remain the same.
Cumsum (): If A is a vector, then cumsum(A) returns a vector containing the cumulative sum
of the elements of A.If A is a matrix, then cumsum(A) returns a matrix containing the
cumulative sums for each column of A.If A is a multidimensional array, then cumsum(A) acts
along the first nonsingleton dimension.
Randn (): randn returns a random scalar drawn from the standard normal distribution.
Randn(n) returns an n-by-n matrix of normally distributed random numbers.
Plot (): If X and Y are both vectors, then they must have equal length. The plot function
plots Y versus X.If X and Y are both matrices, then they must have equal size.
The plot function plots columns of Y versus columns of X.If one of X or Y is a vector and the
other is a matrix, then the matrix must have dimensions such that one of its dimensions equals
the vector length. If the number of matrix rows equals the vector length, then
the plot function plots each matrix column versus the vector.
CODE:
A = randi(5,5)
plot(A)
title('Random Sequence')
xlabel('Variables')
ylabel('f(x)')
A1 = [1 2 4,9 2 5]
B1 = [3 8 6,2 5 6]
X1 = cumsum(A1,1)
Y1 = cumsum(A1,2)
U = sum(A1,1)
V = sum(A1,2)
OUTPUT:
A=
5 1 1 1 4
5 2 5 3 1
1 3 5 5 5
5 5 3 4 5
4 5 5 5 4
A1 =
1 2 4 9 2 5
B1 =
3 8 6 2 5 6
X1 =
1 2 4 9 2 5
Y1 =
1 3 7 16 18 23
U=
1 2 4 9 2 5
V=
23
PRACTICAL-4
AIM: Evaluating a given expression and rounding it to the nearest integer value using Round, Floor,
Ceil and Fix functions; Also, generating and Plots of
(A) Trigonometric Functions - sin(t),cos(t), tan(t), sec(t), cosec(t) and cot(t) for a given duration, ‘t’.
(B) Logarithmic and other Functions – log(A), log10(A), Square root of A, Real nth root of A.
APPARATUS REQUIRED: Matlab 2019.
THEORY:
FUNCTIONS USED
Round (): Round to nearest decimal or integer Y = round(X) rounds each element of X to the
nearest integer. In the case of a tie, where an element has a fractional part of exactly 0.5,
the round function rounds away from zero to the integer with larger magnitude.
1. Y = round(X,N) rounds to N digits:
2. N > 0: round to N digits to the right of the decimal point.
3. N = 0: round to the nearest integer.
4. N < 0: round to N digits to the left of the decimal point.
Floor (): Round toward negative infinity Y = floor(X) rounds each element of X to the nearest
integer less than or equal to that element.
1. Y = floor(t) rounds each element of the duration array t to the nearest number of seconds
less than or equal to that element.
2. Y = floor(t,unit) rounds each element of t to the nearest number of the specified unit of
time less than or equal to that element.
Ceil (): Round toward positive infinity Y = ceil(X) rounds each element of X to the nearest
integer greater than or equal to that element.
1. Y = ceil(t) rounds each element of the duration array t to the nearest number of seconds
greater than or equal to that element.
2. Y = ceil(t,unit) rounds each element of t to the nearest number of the specified unit of time
greater than or equal to that element.
Fix (): Round toward zero Y = fix(X) rounds each element of X to the nearest integer toward
zero. For positive X, the behavior of fix is the same as floor. For negative X, the behavior
of fix is the same as ceil.
LOGARITHMIC & OTHER FUNCTIONS
CODE:
a=1:1:50
b=log(a)
c=log10(a)
d=sqrt(a)
e=nthroot(a,5)
subplot(2,2,1)
plot(a,b);
xlabel('logx')
ylabel('x')
title('logx')
legend('logx')
grid on
subplot(2,2,2)
plot(a,c);
xlabel('x')
ylabel('log10x')
title('log10x')
legend('log10x')
grid on
subplot(2,2,3)
plot(a,d);
xlabel('x')
ylabel('sqrtx')
title('sqrtx')
legend('sqrtx')
grid on
subplot(2,2,4)
plot(a,e);
xlabel('x')
ylabel('nthroot')
title('nthroot')
legend('nthroot')
grid on
OUTPUT:
TRIGNOMETRIC FUNCTIONS
CODE:
A = pi:0.1:pi
X = sin(A)
figure,plot(A,X)
legend('sin(A)')
grid on
title('sin Function')
xlabel('time')
ylabel('sin(A)')
figure,stem(A,X)
legend('sin(A)')
grid on
Y = cos(A)
figure,plot(A,Y)
legend('cos(A)')
grid on
title('cos Function')
xlabel('time')
ylabel('cos(A)')
figure,stem(A,Y)
legend('cos(A)')
grid on
Z = tan(A)
figure,plot(A,Z)
legend('tan(A)')
grid on
title('tan Function')
xlabel('time')
ylabel('tan(A)')
figure,stem(A,Z)
legend('tan(A)')
grid on
M = asin(A)
figure,plot(A,M)
legend('cosec(A)')
grid on
title('cosec Function')
xlabel('time')
ylabel('cosec(A)')
figure,stem(A,M)
legend('cosec(A)')
grid on
N = acos(A)
figure,plot(A,N)
legend('sec(A)')
grid on
title('sec Function')
xlabel('time')
ylabel('sec(A)')
figure,stem(A,N)
legend('sec(A)')
grid on
OUTPUT:
Sin ()
Cos ()
tan ()
cosec ()
sec ()
ROUND OFF FUNCTIONS
CODE:
A=89.11
round(A)
floor(A)
ceil(A)
fix(A)
OUTPUT:
A=
89.1100
ans =
89
ans =
89
ans =
90
ans =
89