You are on page 1of 38

Man

FACULTY OF ENGINEERING AND TECHNOLOGY


BACHELOR OF TECHNOLOGY

IT Workshop-II (203105258)
4TH SEMESTER
COMPUTER SCIENCE DEPARTMENT

Laboratory Manual
CERTIFICATE
This is to certify that

Mr./Ms.................................................................................

..................................................... with enrolment

no. ................................................................ has

successfully completed his/her laboratory experiments in

the IT Workshop-II (203105258) from the department

of Computer Engineering & Science during the academic

year ................................

Date of Submission:......................... Staff In charge: Prof. Manali Modi

Head Of Department: Dr. Kirit Modi


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

TABLE OF CONTENT

Sr. Date of Marks (out


Experiment Title Date of Start Sign
No Completion of 10)

Introduction and benefits of


1 MATLAB

Installation of MATLAB
2
Types of variables and matrices
3 in MATLAB.

Perform different operations on


4 variables and matrices in
MATLAB.

Perform data visualization and


summarizations in MATLAB.
5

Scripts and functions in


6 MATLAB.

Solving linear and non-linear


7 equations in MATLAB.

To perform LU Decomposition
8 on a given matrix in MATLAB.

To perform Single Value


9 Decomposition on a given
matrix.

Case study on any topic in any


10 field of an interest as an
application of MATLAB.

Enrollment No: Page No .:- 3


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

Practical 1: Introduction and benefits of MATLAB

In this introduction we will describe how MATLAB handles simple numerical expressions and
mathematical formulas.

The name MATLAB stands for MATrix LABoratory. MATLAB was written originally to
provide easy access to matrix software developed by the LINPACK (linear system package) and
EISPACK (Eigen system package) projects

Benefits:
● MATLAB is a high-performance language for technical computing. It integrates
computation, visualization, and programming environment. Furthermore, MATLAB is a
modern programming language environment: it has sophisticated data structures, contains
built-in editing and debugging tools, and supports object-oriented programming. These
factors make MATLAB an excellent tool for teaching and research.

● MATLAB has many advantages compared to conventional computer languages (e.g., C,


FORTRAN) for solving technical problems. MATLAB is an interactive system whose
basic data element is an array that does not require dimensioning. The software package
has been commercially available since 1984 and is now considered as a standard tool at
most universities and industries worldwide. It has powerful built-in routines that enable a
very wide variety of computations. It also has easy to use graphics commands that make
the visualization of results immediately available. Specific applications are collected in
packages referred to as toolbox. There are toolboxes for signal processing, symbolic
computation, control theory, simulation, optimization, and several other fields of applied
science and engineering.

Enrollment No: Page No .:- 4


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

Practical 2: Installation of MATLAB


For Installation we have to click this link: https://ww2.mathworks.cn/help/install/ug/install-
mathworks-software.html
After Installation we have to follow the following steps

A Minimum MATLAB Session:


The goal of this minimum session (also called starting and exiting sessions) is to learn the first
steps:
• How to log on
• Invoke MATLAB
• Do a few simple calculations
• How to quit MATLAB
Starting MATLAB:
Open MATLAB by double-clicking on the MATLAB shortcut icon (MATLAB 7.0.4) on the
Windows desktop. When we start MATLAB, a special window called the MATLAB desktop
appears. The desktop is a window that contains other windows.
The major tools within or accessible from the desktop are:
• The Command Window
• The Command History
• The Workspace
• The Current Directory
• The Help Browser
• The Start button

Enrollment No: Page No .:- 5


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

Figure 2.1: The graphical interface to the MATLAB workspace

When MATLAB is started for the first time, the screen looks like the one that shown in the
Figure 2.1. This illustration also shows the default configuration of the MATLAB desktop. It can
be customize the arrangement of tools and documents to as per needs. Now, we are interested in
doing some simple calculations..
MATLAB desktop on someoner computer, which contains the prompt (>>) in the Command
Window.
Usually, there are 2 types of prompt:
✔ >> for full version
✔ EDU> for educational version

Enrollment No: Page No .:- 6


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

Note: To simplify the notation, we will use this prompt, >>, as a standard prompt sign, though
our MATLAB version is for educational purpose.

Quitting MATLAB:

To end MATLAB session, type quit in the Command Window, or select File 🡪Exit
MATLAB in the desktop main menu.

Enrollment No: Page No .:- 7


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

Practical 3: Types of variables and matrices in MATLAB.


(A) Creating MATLAB variables:
MATLAB variables are created with an assignment statement.
The syntax of variable assignment is.
Variable name = a value (or an expression)
For example,
>> x = expression
Where expression is a combination of numerical values, mathematical operators, variables, and
function calls. On other words, expression can involve:
● manual entry
● built-in functions
● user-defined functions
Controlling the appearance of floating point number:
MATLAB by default displays only 4 decimals in the result of the calculations, for example
-163:6667 as shown in above examples. However, MATLAB does numerical calculations in
double precision, which is 15 digits. The command format controls how the results of
computations are displayed. Here are some examples of the different formats together with the
resulting outputs.
>> format short
>> x=-163.6667
If we want to see all 15 digits, we use the command format long
>> format long
>> x= -1.636666666666667e+002
To return to the standard format, enter format short, or simply format.
There are several other formats. For more details, see the MATLAB documentation, or type help
format.
Note - Up to now, we have let MATLAB repeat everything that we enter at the prompt (>>).
Sometimes this is not quite useful, in particular when the output is pages en length. To prevent
MATLAB from echoing what we type, simply enter a semicolon (;) at the end of the command.
For example,
>> x=-163.6667;
and then ask about the value of x by typing,
>> x
x=
-163.6667
Managing the workspace:
The contents of the workspace persist between the executions of separate commands. Therefore,
it is possible for the results of one problem to have an effect on the next one. To avoid this
possibility, it is a good idea to issue a clear command at the start of each new independent
calculation.
>> clear
The command clear or clear all removes all variables from the workspace. This frees up system
memory. In order to display a list of the variables currently in the memory, type
Enrollment No: Page No .:- 8
Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

>> who
While, whos will give more details which include size, space allocation, and class of the
Variables.
Keeping track of on work session:
It is possible to keep track of everything done during a MATLAB session with the diary
command.
>> diary
or give a name to a created file,
>> diary FileName
Where FileName could be any arbitrary name choosen.
The function diary is useful if someone want to save a complete MATLAB session. They save
all input and output as they appear in the MATLAB window. When someone want to stop the
recording, enter diary off. If someone want to start recording again, enter diary on. The file that
is created is a simple text file. It can be opened by an editor or a word processing program and
edited to remove extraneous material, or to add someoner comments. Someone can use the
function type to view the diary file or someone can edit in a text editor or print. This command is
useful, for example in the process of preparing a homework or lab submission.

Miscellaneous Commands:
Here are few additional useful commands:
● To clear the Command Window, type clc
● To abort a MATLAB computation, type ctrl-c
● To continue a line, type . . .
Getting help:
>> help Command
Eg:
help sqrt
Use lookfor to find functions by keywords. The general form is
>> lookfor FunctionName
In the current version (MATLAB version 7), the doc function opens the on-line version of the
help manual. This is very helpful for more complex commands.
>> doc plot

Matrix:
Matrices are the basic elements of the MATLAB environment. A matrix is a two-dimensional
Array consisting of m rows and n columns. Special cases are column vectors (n = 1) and row
Vectors (m = 1).
Matrix Generation:
Matrices are fundamental to MATLAB. Therefore, we need to become familiar with matrix
generation and manipulation. Matrices can be generated in several ways.
Entering a vector:
Enrollment No: Page No .:- 9
Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

An array of dimension 1* n is called a row vector.The elements of vectors in MATLAB are


enclosed by square brackets and are separated by spaces or by commas.

For example, to enter a row vector, v, type


>> v = [1 4 7 10 13]
v=
1 4 7 10 13
An array of dimension m* 1 is called a column vector. The elements of vectors in MATLAB are
enclosed by square brackets and are separated by spaces or by commas.
Column vectors are created in a similar way; however, semicolon (;) must separate the
components of a column vector,
>> w = [1;4;7;10;13]
w=
1
4
7
10
13
Entering a Matrix:
A matrix is an array of numbers. To type a matrix into MATLAB someone must
● begin with a square bracket, [
● separate elements in a row with spaces or commas (,)
● use a semicolon (;) to separate rows
● end the matrix with another square bracket, ].

Here is a typical example. To enter a matrix A, such as,

Type,

>> A = [1 2 3; 4 5 6; 7 8 9]

MATLAB then displays the 3 *3 matrix as follows,

Enrollment No: Page No .:- 10


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

Matrix Generators:
MATLAB provides a function that generates elementary matrices. The matrix of zeros, the
matrix of ones, and the identity matrix are returned by the functions zeros, ones, and eye,
respectively.

Table 3.1: Elementary matrices


For a complete list of elementary matrices and matrix manipulations, type help elmat or doc
elmat. Here are some examples:

>> b=ones(3,1)
b=
1
1
1

Equivalently, we can define b as >> b=[1;1;1]

>> eye(3)
ans =
100
010
001

>> c=zeros(2,3)
c=
000
000

Two other important matrix generation functions are rand and randn, which generate matrices
of (pseudo-)random numbers using the same syntax as eye.
In addition, matrices can be constructed in a block form. With C denoted by
C = [12; 3 4], we may create a matrix D as follows

>> D = [C zeros(2); ones(2) eye(2)]

Enrollment No: Page No .:- 11


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

D=
1200
3400
1110
1101

Special matrices:

MATLAB provides a number of special matrices (see Table 3.2). These matrices have
interesting properties that make them useful for constructing examples and for testing
algorithms.

Table 3.2: Special matrices

MATLAB environment behaves like a super-complex calculator. Someone can enter


commands at the >> command prompt.
MATLAB is an interpreted environment. In other words, someone give a command and
MATLAB executes it right away.

Practical 4: Different operations on variables and matrices in


MATLAB.

Using MATLAB as a calculator:


let's suppose someone want to calculate the expression, 1 + 2 * 3. Someone type it at the prompt
command (>>) as follows,

>> 1+2*3
Enrollment No: Page No .:- 12
Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

ans =
7
Someone will have noticed that if someone do not specify an output variable, MATLAB uses a
default variable ans, to store the results of the current calculation.
Note that the variable ans is created (or overwritten, if it is already existed). To avoid this,
someone may assign a value to a variable or output argument name. For example,

>> x = 1+2*3
x=
7
will result in x being given the value 1 + 2 * 3 = 7. This variable name can always be used to
refer to the results of the previous computations. Therefore, computing 4x will result in
>> 4*x
ans =
28.0000

Table 4.1: Basic arithmetic operators


Overwriting Variable:
Once a variable has been created, it can be reassigned. In addition, if someone do not wish to see
the intermediate results, someone can suppress the numerical output by putting a semicolon (;) at
the end of the line. Then the sequence of commands looks like this:
>> t = 5;
>> t = t+1
t=
6
Error messages:
If we enter an expression incorrectly, MATLAB will return an error message. For example,
Enrollment No: Page No .:- 13
Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

in the following, we left out the multiplication sign, *, in the following expression
>> x = 10;
>> 5x
??? 5x
|
Error: Unexpected MATLAB expression.
Making Corrections:
To make corrections, we can, of course retype the expressions. But if the expression is lengthy,
we make more mistakes by typing a second time. A previously typed command can be recalled
with the up-arrow key. When the command is displayed at the command prompt, it can be
modified if needed and executed.
Controlling the hierarchy of operations or precedence:
Let's consider the previous arithmetic operation, but now we will include parentheses. For
Example, 1 + 2 * 3 will become (1 + 2) * 3

>> (1+2)*3
ans =
9
And, from previous example
>> 1+2*3
ans =
7

By adding parentheses, these two expressions give different results: 9 and 7.

Table 4.2: Hierarchy of arithmetic operations


MATLAB arithmetic operators obey the same precedence rules as those in most computer
programs. For operators of equal precedence, evaluation is from left to right.
Now, consider another example:
In MATLAB, it becomes
>> 1/(2+3^2)+4/5*6/7
ans =
0.7766
or, if parentheses are missing,
Enrollment No: Page No .:- 14
Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

>> 1/2+3^2+4/5*6/7
ans =
10.1857
So here what we get: two different results. Therefore, we want to emphasize the importance of
precedence rule in order to avoid ambiguity.
Entering multiple statements per line:
It is possible to enter multiple statements per line. Use commas (,) or semicolons (;) to enter
more than one statement at once. Commas (,) allow multiple statements per line without
suppressing output.
>> a=7; b=cos(a), c=cosh(a)
b=
0.6570
c=
548.3170

Matrix Operations:
Matrix arithmetic operations
As we mentioned earlier, MATLAB allows arithmetic operations: +, -, *, and ^ to be carried out
on matrices. Thus,
● A+B or B+A is valid if A and B are of the same size
● A*B is valid if A's number of column equals B's number of rows
● A^2 is valid if A is square and equals A*A
● α*A or A* α multiplies each element of A by α

Table 4.3: Array operators

>> C = A.*B
C=
10 40 90
160 250 360
490 640 810

Enrollment No: Page No .:- 15


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

>> A.^2
ans =
149
16 25 36
49 64 81

Table 4.4: Summary of matrix and array operations

to enter a row vector, v,


type
>> v = [1 4 7 10 13]
v=
1 4 7 10 13

Column vector,

>> w = [1;4;7;10;13]
w=
1
4
7
10
13

Transpose operation:

A row vector is converted to a column vector using the transpose operator.


The transpose operation is denoted by an apostrophe or a single quote (').

>> w = v'
w=
Enrollment No: Page No .:- 16
Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

1
4
7
10
13

>> A'
ans =
147
258
360

Accessing the elements:

To access blocks of elements, we use MATLAB's colon notation (:). For example, to access the
first three elements of v, we write,

>> v(1:3)
ans =
147

All elements from the third through the last elements,


>> v(3,end)
ans =
7 10 13

Where end signifies the last element in the vector.

If v is a vector, writing
>> v(:)

produces a column vector, whereas writing

>> v(1:end)

produces a row vector.

Enrollment No: Page No .:- 17


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

Accessing the element of Matrix in Matlab:

>> A = [1 2 3; 4 5 6; 7 8 9]

MATLAB then displays the 3 *3 matrix as follows,

We can then view a particular element in a matrix by specifying its location. We write,
>> A(2,1)
ans =
4
A (2, 1) is an element located in the second row and first column. Its value is 4.
Updating the value in the matrix:
We select elements in a matrix just as we did for vectors, but now we need two indices. The
element of row i and column j of the matrix A is denoted by A(i,j). Thus, A(i,j) in MATLAB
refers to the element Aij of matrix A. The first index is the row number and the second index is
the column number. For example, A(1,3) is an element of first row and third column. Here,
A(1,3)=3.
Correcting any entry is easy through indexing. Here we substitute A(3,3)=9 by
A(3,3)=0. The result is

>> A(3,3) = 0
A=
123
456
780

Single elements of a matrix are accessed as A(i,j), where i >=1 and j >=1. Zero or negative
subscripts are not supported in MATLAB.

Colon operator:

The colon operator will prove very useful and understanding how it works is the key to efficient
and convenient usage of MATLAB. It occurs in several different forms.

Suppose we want to enter a vector x consisting of points (0, 0:1, 0:2, 0:3, ... , 5). We can use the
command

>> x = 0:0.1:5;

Enrollment No: Page No .:- 18


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

The row vector has 51 elements.

Linear spacing:

There is a command to generate linearly spaced vectors: linspace. It is similar to the colon
operator (:), but gives direct control over the number of points.
For example,
y = linspace(a,b)
generates a row vector y of 100 points linearly spaced between and including a and b.
y = linspace(a,b,n)

Generates a row vector y of n points linearly spaced between and including a and b. This is
useful when we want to divide an interval into a number of subintervals of the same length.
For example,
>> theta = linspace(0,2*pi,101)

Divides the interval [0; 2pi] into 100 equal subintervals, then creating a vector of 101 elements.

Colon operator in a matrix:

The colon operator can also be used to pick out a certain row or column. For example, the
statement A (m:n,k:l specifies rows m to n and column k to l. Subscript expressions refer to
portions of a matrix. For example,
>> A(2,:)
ans =
456
is the second row elements of A.
The colon operator can also be used to extract a sub-matrix from a matrix A.

Enrollment No: Page No .:- 19


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

>> A(:,2:3)
ans =
23
56
80

A (:,2:3) is a sub-matrix with the last two columns of A.


A row or a column of a matrix can be deleted by setting it to a null vector, [ ].
>> A(:,2)=[]
ans =
13
46
70
It is important to note that the colon operator (:) stands for all columns or all rows. To create a
vector version of matrix A, do the following
>> A (:)
ans =
1
2
3
4
5
6
7
8
0

As a special case, a colon (:) as the row or column specifier covers all entries in that row or
column; thus
● A(:,j) is the jth column of A, while
Enrollment No: Page No .:- 20
Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

● A(i,:) is the ith row, and


● A(end,:) picks out the last row of A.

The keyword end, used in A(end,:), denotes the last index in the speci¯ed dimension. Here
are some examples.
>> A
A=
123
456
789
>> A(2:3,2:3)
ans =
56
89

>> A(end:-1:1,end)
ans =
9
6
3

>> A([1 3],[2 3])


ans =
23
89

Deleting row or column:


To delete a row or column of a matrix, use the empty vector operator, [ ].
>> A(3,:) = []

Enrollment No: Page No .:- 21


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

A=
123
456
Third row of matrix A is now deleted. To restore the third row, we use a technique for creating a
matrix
>> A = [A(1,:);A(2,:);[7 8 0]]
A=
123
456
780
Matrix A is now restored to its original form.

Dimension:
To determine the dimensions of a matrix or vector, use the command size. For example,
>> size(A)
ans =
33
Means 3 rows and 3 columns.

Concatenating matrices:
Matrices can be made up of sub-matrices. Here is an example. First, let's recall our previous
Matrix A.
A=
123
456
789
The new matrix B will be,
>> B = [A 10*A; -A [1 0 0; 0 1 0; 0 0 1]]
B=
1 2 3 10 20 30
4 5 6 40 50 60
7 8 9 70 80 90
-1 -2 -3 1 0 0
-4 -5 -6 0 1 0

Enrollment No: Page No .:- 22


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

-7 -8 -9 0 0 1

Hands on Practice
Type a valid expression, for example,
5 + 5

And press ENTER


When someone click the Execute button, or type Ctrl+E, MATLAB executes it
immediately and the result returned is −
ans = 10
Let us take up few more examples −
3 ^ 2 % 3 raised to the power of 2

When someone click the Execute button, or type Ctrl+E, MATLAB executes it
immediately and the result returned is −
ans = 9
Another example,
sin(pi /2) % sine of angle 90o

When someone click the Execute button, or type Ctrl+E, MATLAB executes it
immediately and the result returned is −
ans = 1
Another example,
7/0 % Divide by zero

When someone click the Execute button, or type Ctrl+E, MATLAB executes it
immediately and the result returned is −
ans = Inf
warning: division by zero
Another example,
732 * 20.3

When someone click the Execute button, or type Ctrl+E, MATLAB executes it
immediately and the result returned is −
ans = 1.4860e+04

Enrollment No: Page No .:- 23


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

MATLAB provides some special expressions for some mathematical symbols, like pi
for π, Inf for ∞, i (and j) for √-1 etc. Nan stands for 'not a number'.

Use of Semicolon (;) in MATLAB


Semicolon (;) indicates end of statement. However, if someone want to suppress and
hide the MATLAB output for an expression, add a semicolon after the expression.
For example,
x = 3;
y = x + 5

When someone click the Execute button, or type Ctrl+E, MATLAB executes it
immediately and the result returned is −
y = 8

Adding Comments
The percent symbol (%) is used for indicating a comment line. For example,
x = 9 % assign the value 9 to x

Someone can also write a block of comments using the block comment operators %
{ and % }.
The MATLAB editor includes tools and context menu items to help someone add,
remove, or change the format of comments.

Commonly used Operators and Special Characters


MATLAB supports the following commonly used operators and special characters −

Operator Purpose

+ Plus; addition operator.

- Minus; subtraction operator.

* Scalar and matrix multiplication operator.

Enrollment No: Page No .:- 24


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

.* Array multiplication operator.

^ Scalar and matrix exponentiation operator.

.^ Array exponentiation operator.

\ Left-division operator.

/ Right-division operator.

.\ Array left-division operator.

./ Array right-division operator.

: Colon; generates regularly spaced elements and


represents an entire row or column.

() Parentheses; encloses function arguments and array


indices; overrides precedence.

[] Brackets; enclosures array elements.

. Decimal point.

… Ellipsis; line-continuation operator

, Comma; separates statements and elements in a row

Enrollment No: Page No .:- 25


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

; Semicolon; separates columns and suppresses display.

% Percent sign; designates a comment and specifies


formatting.

_ Quote sign and transpose operator.

._ Nonconjugated transpose operator.

= Assignment operator.

Special Variables and Constants


MATLAB supports the following special variables and constants −

Name Meaning

ans Most recent answer.

eps Accuracy of floating-point precision.

i,j The imaginary unit √-1.

Inf Infinity.

NaN Undefined numerical result (not a number).

pi The number π

Enrollment No: Page No .:- 26


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

Naming Variables
Variable names consist of a letter followed by any number of letters, digits or
underscore.
MATLAB is case-sensitive.
Variable names can be of any length, however, MATLAB uses only first N characters,
where N is given by the function namelengthmax.

Saving Someoner Work


The save command is used for saving all the variables in the workspace, as a file
with .mat extension, in the current directory.
For example,
save myfile
Someone can reload the file anytime later using the load command.
load myfile
In MATLAB environment, every variable is an array or matrix.
Someone can assign variables in a simple way. For example,
x = 3 % defining x and initializing it with a value

MATLAB will execute the above statement and return the following result −
x = 3
It creates a 1-by-1 matrix named x and stores the value 3 in its element. Let us check
another example,
x = sqrt(16) % defining x and initializing it with an expression

MATLAB will execute the above statement and return the following result −
x = 4
Please note that −
● Once a variable is entered into the system, someone can refer to it later.

● Variables must have values before they are used.

● When an expression returns a result that is not assigned to any variable, the system
assigns it to a variable named ans, which can be used later.
For example,
sqrt(78)
Enrollment No: Page No .:- 27
Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

MATLAB will execute the above statement and return the following result −
ans = 8.8318
Someone can use this variable ans −
sqrt(78);
9876/ans

MATLAB will execute the above statement and return the following result −
ans = 1118.2
Let's look at another example −
x = 7 * 8;
y = x * 7.89

MATLAB will execute the above statement and return the following result −
y = 441.84

Multiple Assignments
Someone can have multiple assignments on the same line. For example,
a = 2; b = 7; c = a * b

MATLAB will execute the above statement and return the following result −
c = 14

I have forgotten the Variables!


The who command displays all the variable names someone have used.
who
MATLAB will execute the above statement and return the following result −
Someoner variables are:
a ans b c
The whos command displays little more about the variables −

● Variables currently in memory


● Type of each variables
● Memory allocated to each variable
● Whether they are complex variables or not
whos

Enrollment No: Page No .:- 28


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

MATLAB will execute the above statement and return the following result −
Attr Name Size Bytes Class
==== ==== ==== ==== =====
a 1x1 8 double
ans 1x70 757 cell
b 1x1 8 double
c 1x1 8 double

Total is 73 elements using 781 bytes


The clear command deletes all (or the specified) variable(s) from the memory.
clear x % it will delete x, won't display anything
clear % it will delete all variables in the workspace
% peacefully and unobtrusively

Long Assignments
Long assignments can be extended to another line by using an ellipses (...). For
example,
initial_velocity = 0;
acceleration = 9.8;
time = 20;
final_velocity = initial_velocity + acceleration * time

MATLAB will execute the above statement and return the following result −
final_velocity = 196

The format Command


By default, MATLAB displays numbers with four decimal place values. This is known
as short format.
However, if someone want more precision, someone need to use
the format command.
The format long command displays 16 digits after decimal.
For example −
format long
x = 7 + 10/3 + 5 ^ 1.2

MATLAB will execute the above statement and return the following result−
x = 17.2319816406394
Another example,
Enrollment No: Page No .:- 29
Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

format short
x = 7 + 10/3 + 5 ^ 1.2

MATLAB will execute the above statement and return the following result −
x = 17.232
The format bank command rounds numbers to two decimal places. For example,

format bank
daily_wage = 177.45;
weekly_wage = daily_wage * 6

MATLAB will execute the above statement and return the following result −
weekly_wage = 1064.70
MATLAB displays large numbers using exponential notation.
The format short e command allows displaying in exponential form with four decimal
places plus the exponent.
For example,
format short e
4.678 * 4.9

MATLAB will execute the above statement and return the following result −
ans = 2.2922e+01
The format long e command allows displaying in exponential form with four decimal
places plus the exponent. For example,
format long e
x = pi

MATLAB will execute the above statement and return the following result −
x = 3.141592653589793e+00
The format rat command gives the closest rational expression resulting from a
calculation. For example,
format rat
4.678 * 4.9

MATLAB will execute the above statement and return the following result −
ans = 34177/1491

Enrollment No: Page No .:- 30


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

Creating Vectors
A vector is a one-dimensional array of numbers. MATLAB allows creating two types of
vectors −

● Row vectors
● Column vectors
Row vectors are created by enclosing the set of elements in square brackets, using
space or comma to delimit the elements.
For example,
r = [7 8 9 10 11]

MATLAB will execute the above statement and return the following result −
r =

7 8 9 10 11
Another example,
r = [7 8 9 10 11];
t = [2, 3, 4, 5, 6];
res = r + t

MATLAB will execute the above statement and return the following result −
res =

9 11 13 15 17
Column vectors are created by enclosing the set of elements in square brackets,
using semicolon(;) to delimit the elements.
c = [7; 8; 9; 10; 11]

MATLAB will execute the above statement and return the following result −
c =
7
8
9
10
11

Creating Matrices
A matrix is a two-dimensional array of numbers.
Enrollment No: Page No .:- 31
Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

In MATLAB, a matrix is created by entering each row as a sequence of space or


comma separated elements, and end of a row is demarcated by a semicolon. For
example, let us create a 3-by-3 matrix as −
m = [1 2 3; 4 5 6; 7 8 9]

MATLAB will execute the above statement and return the following result −
m =
1 2 3
4 5 6
7 8 9
MATLAB is an interactive program for numerical computation and data visualization.
Someone can enter a command by typing it at the MATLAB prompt '>>' on
the Command Window.
In this section, we will provide lists of commonly used general MATLAB commands.

Commands for Managing a Session


MATLAB provides various commands for managing a session. The following table
provides all such commands −

Command Purpose

clc Clears command window.

clear Removes variables from memory.

exist Checks for existence of file or variable.

global Declares variables to be global.

help Searches for a help topic.

lookfor Searches help entries for a keyword.

Enrollment No: Page No .:- 32


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

quit Stops MATLAB.

who Lists current variables.

whos Lists current variables (long display).

Commands for Working with the System


MATLAB provides various useful commands for working with the system, like saving
the current work in the workspace as a file and loading the file later.
It also provides various commands for other system-related activities like, displaying
date, listing files in the directory, displaying current directory, etc.
The following table displays some commonly used system-related commands −

Command Purpose

cd Changes current directory.

date Displays current date.

delete Deletes a file.

diary Switches on/off diary file recording.

dir Lists all files in current directory.

load Loads workspace variables from a file.

path Displays search path.

Enrollment No: Page No .:- 33


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

pwd Displays current directory.

save Saves workspace variables in a file.

type Displays contents of a file.

what Lists all MATLAB files in the current directory.

wklread Reads .wk1 spreadsheet file.

Input and Output Commands


MATLAB provides the following input and output related commands −

Command Purpose

disp Displays contents of an array or string.

fscanf Read formatted data from a file.

format Controls screen-display format.

fprintf Performs formatted writes to screen or file.

input Displays prompts and waits for input.

Enrollment No: Page No .:- 34


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

; Suppresses screen printing.

The fscanf and fprintf commands behave like C scanf and printf functions. They


support the following format codes −

Format Code Purpose

%s Format as a string.

%d Format as an integer.

%f Format as a floating point value.

%e Format as a floating point value in scientific notation.

%g Format in the most compact form: %f or %e.

\n Insert a new line in the output string.

\t Insert a tab in the output string.

The format function has the following forms used for numeric display −

Format Function Display up to

format short Four decimal digits (default).

format long 16 decimal digits.

Enrollment No: Page No .:- 35


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

format short e Five digits plus exponent.

format long e 16 digits plus exponents.

format bank Two decimal digits.

format + Positive, negative, or zero.

format rat Rational approximation.

format compact Suppresses some line feeds.

format loose Resets to less compact display mode.

Vector, Matrix and Array Commands


The following table shows various commands used for working with arrays, matrices
and vectors −

Command Purpose

cat Concatenates arrays.

find Finds indices of nonzero elements.

length Computes number of elements.

linspace Creates regularly spaced vector.

Enrollment No: Page No .:- 36


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

logspace Creates logarithmically spaced vector.

max Returns largest element.

min Returns smallest element.

prod Product of each column.

reshape Changes size.

size Computes array size.

sort Sorts each column.

sum Sums each column.

eye Creates an identity matrix.

ones Creates an array of ones.

zeros Creates an array of zeros.

cross Computes matrix cross products.

dot Computes matrix dot products.

det Computes determinant of an array.

Enrollment No: Page No .:- 37


Faculty of Engineering & Technology
Subject Name : ITW-II
Subject Code : 203105258
B.Tech : CSE, Year : 2, Semester : 4

inv Computes inverse of a matrix.

Enrollment No: Page No .:- 38

You might also like