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

engineering _workshop_Lab1

This laboratory manual introduces MATLAB, covering its interface, basic arithmetic operations, and matrix manipulation. It highlights MATLAB's capabilities in computation, visualization, and programming, along with its strengths such as ease of learning and optimized performance for matrix operations. The document also includes exercises for students to practice using MATLAB effectively.

Uploaded by

almautulamreeka
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

engineering _workshop_Lab1

This laboratory manual introduces MATLAB, covering its interface, basic arithmetic operations, and matrix manipulation. It highlights MATLAB's capabilities in computation, visualization, and programming, along with its strengths such as ease of learning and optimized performance for matrix operations. The document also includes exercises for students to practice using MATLAB effectively.

Uploaded by

almautulamreeka
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

ENGINEERING WORKSHOP LAB

(EL-1006)

LABORATORY MANUAL

INTRODUCTION TO MATLAB
(LAB # 01)
Engr. Shehzad Ahmad

Engr. Tooba
Student Name: ______________________________________________

Roll No: ________________ Section: ____

Date performed: 28th January, 2024

MARKS AWARDED: ________ / 10

____________________________________________________________________________________________________________________________________________________________

NATIONAL UNIVERSITY OF COMPUTER AND EMERGING SCIENCES, ISLAMABAD


Introduction to MATLAB LAB 1

Lab # 01: Introduction to MATLAB


Learning Objectives:
In this lab, you will learn:
 The interface of MATLAB
 Basic arithmetic operators
 Matlab variables
 Matrix manipulation

Software Used: MATLAB

Description:

Matlab (stands for Matrix Laboratory), it integrates computation, visualization, and programming
in an easy-to-use environment, where problems and solutions are expressed in familiar
mathematical notation.

Examples:

 Matrix computations and linear algebra


 Solving nonlinear equations
 Numerical solution of differential equations
 Mathematical optimization
 Statistics and data analysis
 Signal processing
 Modelling of dynamical systems
 Solving partial differential equations
 Simulation of engineering systems

Strengths of MATLAB

 MATLAB is relatively easy to learn.


 MATLAB code is optimized to be relatively quick when performing matrix operations.
 MATLAB may behave like a calculator or as a programming language.
 MATLAB is interpreted, errors are easier to fix.

ENGINEERING WORKSHOP LAB NUCES FAST, ISLAMABAD Page 2 of 14


Introduction to MATLAB LAB 1

“Fig 1.1”

Desktop Tools
1. Command Window
Use the Command Window to enter variables and run functions and M-files.

“Fig 1.2”
2. Command History:
Statements you enter in the Command Window are logged in the Command History. In
the Command History, you can view previously run statements, and copy and execute selected
statements.
Enter a command “commandhistory” in Command Window to see commands historY.

ENGINEERING WORKSHOP LAB NUCES FAST, ISLAMABAD Page 3 of 14


Introduction to MATLAB LAB 1

“Fig 1.3”

“Fig 1.4”

ENGINEERING WORKSHOP LAB NUCES FAST, ISLAMABAD Page 4 of 14


Introduction to MATLAB LAB 1

“Fig 1.5”
3. Workspace Browser:
The MATLAB workspace consists of the set of variables (named arrays) built up during
a MATLAB session and stored in memory.

“Fig 1.6”
4. Variable Tab:
 Double-click a variable in the Workspace browser to see it in the Variable Tab.
 Use the Variable Tab to view and edit a visual representation of one- or two-dimensional
numeric arrays, strings, and cell arrays of strings that are in the workspace.

ENGINEERING WORKSHOP LAB NUCES FAST, ISLAMABAD Page 5 of 14


Introduction to MATLAB LAB 1

“Fig 1.7”

5. Current Folder:
It lists all the files that are available in current directory.

“Fig 1.8”

“Fig 1.9”

Reserved Words:
ENGINEERING WORKSHOP LAB NUCES FAST, ISLAMABAD Page 6 of 14
Introduction to MATLAB LAB 1
 Reserved Words List:
for end if while
function elseif case otherwise

switch continue else try


catch global persistent break

 This list is returned as an output of the ‘iskeyword’ function. For example,


>> iskeyword(‘case’)
ans =
1 (else 0 will be displayed)
 The function isvarname(‘MCS’) work in the same manner.
 Matlab will report an error if you try to use a reserved word as variable.

Basic Arithmetic Operations:


Operations Symbol Example

Addition + 3 + 22
Subtraction - 54.4 – 16.5
Multiplication * 3.14 * 6
Division / or \ 10/2 or 2\10
 Expressions are evaluated from left to right, with precedence;
Exponentiation > Multiplication & Division > Addition & Subtraction.

Variables Naming Rule:

 The first character MUST be alphabetic followed by any number of letters, digits, or
underscore.
 The variable names are case sensitive.
 Blanks are NOT allowed in a variable name.
 Variable names can contain up to 63 characters.
 Punctuation characters are not allowed, because many of them have special meanings in
Matlab.

Matlab Special Variables:


ans Default variable name for results
pi Value of p
inf infinity
NaN Not a number e.g. 0/0
i and j i = j = -1
realmin The smallest usable positive real number
realmax The largest usable positive real number

Examples:
>>a = 2
a=

ENGINEERING WORKSHOP LAB NUCES FAST, ISLAMABAD Page 7 of 14


Introduction to MATLAB LAB 1
>> 2*pi

ans =

6.2832
Types of Variables:
Type Examples

Integer 1362,-5656
Real 12.33,-56.3
Complex X=12.2 – 3.2i (i = sqrt(-1))

Complex numbers in MATLAB are represented in rectangular form. To separate real & imaginary
part

 H = real(X)
 K = imag(X)
 Conversion between polar & rectangular
 C1 = 1-2i
 Magnitude: mag_c1 = abs(C1)
 Angle: angle_c1 = angle(C1)
 Note that angle is in radians

Useful Matlab Commands:


 who List known variables
 whos List known variables plus their size
 clear all Clear all variables from work space
 clear x y Clear variables x and y from work space
 clc Clear the command window only and not any variable
 close all closes all open figures

 Extras:
Using up-arrow key allow user to recall most recently used commands
Another trick is to use a ‘letter’ prior using up-arrow

Other MATLAB symbols:


, separate statements and data

% start comment which ends at end of line

; (1) suppress output


(2) used as a row separator in a matrix

: specify range

MATLAB Matrices:
 MATLAB treats all variables as matrices. For our purposes a matrix can be thought of as an
array, in fact, that is how it is stored.
 Vectors are special forms of matrices and contain only one row OR one column.
 Scalars are matrices with only one row AND one column.

 A matrix can be created in MATLAB as follows (note the commas AND semicolons):
ENGINEERING WORKSHOP LAB NUCES FAST, ISLAMABAD Page 8 of 14
Introduction to MATLAB LAB 1
» matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]

matrix =

1 2 3
4 5 6
7 8 9
Row Vector:

 A matrix with only one row is called a row vector. A row vector can be created in MATLAB
as follows (note the commas):
» rowvec = [12 , 14 , 63]
rowvec =
12 14 63
 Row vector can also defined in a following way:
rowvec = 2 : 2 : 10; % start : step size : stop
 rowvec =
2 4 6 8 10

Column Vector:

 A matrix with only one column is called a column vector. A column vector can be created in
MATLAB as follows (note the semicolons):

» colvec = [13 ; 45 ; -2]

colvec =

13
45
-2

Extracting a Sub-Matrix:

 A portion of a matrix can be extracted and stored in a smaller matrix by specifying the names of
both matrices and the rows and columns to extract. The syntax is:

sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;

where r1 and r2 specify the beginning and ending rows and c1 and c2 specify the
beginning and ending columns to be extracted to make the new matrix.

 A column vector can be extracted from a matrix. As an example we create a matrix below:

» matrix=[1,2,3;4,5,6;7,8,9] Here we extract the column 2 of matrix and


make a column vector:
matrix = » col_two =matrix( 1:3 ,2: 2)
ENGINEERING WORKSHOP LAB NUCES FAST, ISLAMABAD Page 9 of 14
Introduction to MATLAB LAB 1

1 2 3 col_two = 2
4 5 6 5
7 8 9 8

 A row vector can be extracted from a matrix. As an example we create a matrix below:

» matrix=[1,2,3;4,5,6;7,8,9] Here we extract row 2 of matrix and make a row


vector. Note that 2:2 specifies the 2nd row and
matrix = 1:3 specifies columns of 2nd row.

1 2 3 » rowvec =matrix(2 : 2 , 1 : 3)
4 5 6 rowvec =
7 8 9 4 5 6

Concatenation:
 New matrices may be formed out of old ones
 Suppose we have:

a = [1 2; 3 4]
a=12
34
Input output

[a , a, a] ans = 1 2 1 2 1 2
3 4 3 4 3 4

[a ; a; a] ans =
1 2
3 4
1 2
3 4
1 2
3 4

[a, zeros(2); zeros(2), a'] ans = 1 2 0 0


3 4 0 0
0 0 1 3
0 0 2 4

Scalar Matrix Addition & Subtraction:


» a=3;
» b=[1, 2, 3;4, 5, 6]
b=
1 2 3
4 5 6
» c= b+a % Add a to each element of b
c=
4 5 6
7 8 9

ENGINEERING WORKSHOP LAB NUCES FAST, ISLAMABAD Page 10 of 14


Introduction to MATLAB LAB 1
Scalar - Matrix Multiplication:

» a=3;
» b=[1, 2, 3; 4, 5, 6]
b=
1 2 3
4 5 6
» c = a * b % Multiply each element of b by a

c=
3 6 9
12 15 18

Other matrices Operations:


Let a=[1 4 3;4 2 6 ;7 8 9]
 det(a) : Find the determinent of a matrix.
ans = 48

 inv(a) : Find the inverse of matrix.

ans =

-0.6250 -0.2500 0.3750


0.1250 -0.2500 0.1250
0.3750 0.4167 -0.2917
 a' : Find the transpose of a matrix.
ans =
1 4 7
4 2 8
3 6 9

 min(a) :Return a row vector containing the minimum element from each column.
ans = 1 2 3

 min(min(a)): Return the smallest element in matrix:


ans = 1

 max(a) : Return a row vector containing the maximum element from each column.
ans = 7 8 9

 max(max(a)): Return the max element from matrix:


ans = 9

 a.^2 :Bitwise calculate the square of each element of matrix:


ans =
1 16 9
16 4 36
49 64 81

ENGINEERING WORKSHOP LAB NUCES FAST, ISLAMABAD Page 11 of 14


Introduction to MATLAB LAB 1
 sum (a) : treats the columns of ‘a’ as vectors, returning a row vector of the sums of each
column.
ans = 12 14 18
 sum(sum(a)): Calculate the sum of all the elements in the matrix.
ans = 44

 size (a) : gives the number or rows and the number of columns:
>> [r c] = size(a)
r=3 c=3
 Let a =[ 4 5 6] , length(a) finds the number of elements in row vector.

Bitwise Multiplication of Two Vectors:

Let a=[1 2 3] ; b=[4 5 6];

 a.*b :Bitwise multiply the each element of vector ‘a’ and ‘b’:

ans =
4 10 18

Matrix Division:

 MATLAB has several options for matrix division. You can “right divide” and “left divide”.

Right Division: use the slash character


»A/B
This is equivalent to the MATLAB expression
» A*inv (B)

Left Division: use the backslash character


»A\B
This is equivalent to the MATLAB expression
» inv (A)*B

Matrix of Zeros:

 Syntax : zeros array


 Format : zeros(N), zeros(M,N)
 Description:
This function is used to produce an array of zeros, defined by the arguments.

(N) is an N-by-N matrix of array.


(M,N) is an M-by-N matrix of array.

 Example;
>> zeros(2) >> zeros(1,2)
ans = ans =
0 0 0 0
ENGINEERING WORKSHOP LAB NUCES FAST, ISLAMABAD Page 12 of 14
Introduction to MATLAB LAB 1
0 0

Matrix of Ones:

 Syntax : ones array


 Format : ones(N), ones(M,N)
 Description:
This function is used to produce an array of ones, defined by the arguments.
(N) is an N-by-N matrix of array.
(M,N) is an M-by-N matrix of array.
 Example;
>> ones(2) >> ones(1,2)
ans = ans =
1 1 1 1
1 1
Identity Matrix:

 Syntax : identity matrix


 Format : eye (N), eye (M,N)
 Description:
Create an NxN or MxN identity matrix (i.e., 1’s on the diagonal elements with all others
equal to zero). (Usually the identity matrix is represented by the letter “I”. Type

 Example;
>> I=eye(3)
I=
100
010
001

Exercises:-
NOTE:
 Solve these questions in MATLAB and write answers/code in the manual.

Q.1 Run the MATLAB help desk by typing helpdesk. The help desk provides a hypertext interface
to the MATLAB documentation.

Q.2 Use MATLAB as a calculator. Try the following:


 pi*pi – 10
 sin(pi/4)
 ans ˆ 2 %<--- "ans" holds the last result

Q.3 Create a vector


a. ‘A’ of even whole numbers between 31 and 75.
b. ‘B’ of odd whole numbers between 75 and 131.

ENGINEERING WORKSHOP LAB NUCES FAST, ISLAMABAD Page 13 of 14


Introduction to MATLAB LAB 1
Q.4 Make sure that you understand the colon notation. In particular, explain in words what the
following MATLAB code will produce.
 jkl = 0 : 6
 jkl = 2 : 4 : 17
 jkl = 99 : -1 : 88
 ttt = 2 : (1/9) : 4
 tpi = pi * [ 0:0.1:2 ];

Q.5 Enter the following in MATLAB.

A=
[ 26 34 ] [ 16 62 ]
,B=

Find AB, and A-1.

TASKS:
Matrix Manipulation:
A. Generate a 6x6 matrix A with magic command and replace first column with:
1
-2
-3
-4
-5
-6

B. Generate a 6x1 matrix z as given


1
2
3
4
5
6

C. Solve linear system of equations Ax=z

D. Compute determinant of matrix A

E. Extract a 4x4 matrix (first 4 rows and first 4 columns) from matrix A.

F. Write commands to make a matrix of 2nd , 4th and 6th columns of the original matrix?

ENGINEERING WORKSHOP LAB NUCES FAST, ISLAMABAD Page 14 of 14

You might also like