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

Lab_1

Uploaded by

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

Lab_1

Uploaded by

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

LAB EXPERIMENT # 01

INTRODUCTION TO MATALAB

Name: Konain Mazhar Reg#CPEN-211101045

Instructor: Engr. Sir Aqeel Subject: DSP

Signature:______________ Date:

OBJECTIVES:

The purpose of this lab is to familiarize with basic MATLAB functionality. You will also be able
to learn how vectors are defined and represented in MATLAB.

The MATLAB Working Environment:

The MATLAB Desktop:

MATLAB is a high-level computer language used for the programming of complex engineering
problems. MATLAB stands for Matrix Laboratory. As the name suggests, MATLAB a plethora
of functions used for different operations on matrices, where a matrix can be scalar (single
element), a vector (one dimensional) or an n x m Matrix (two dimensional). The MATLAB
desktop is the main MATLAB application window. In Figure 1, the desktop contains five sub-
windows: The Command Window, the Workspace Browser, the Current Directory Window, the
Command History Window, and one or more Figure Windows, which are shown only when the
user displays a graphic.
The Command Window is where the user type MATLABN commands and expressions at the
prompt (>>) and where the outputs of those commands are displayed. MATLAB defines the
workspace as the set of variables that the user creates in work session. The Workspace Browser
shows those variables and some information about them.
The Current Directory tab above the Workspace tab shows the contents of the current directory,
whose path is shown in the Current Directory Window. Clicking on the button to the right of the
window allows the user to change the current directory. MATLAB uses a search path to find M-
files and other MATLAB. Any file run in MATLAB must reside in the current directory or in the
directory that is on the search path. The easiest way to see which directories are on the search
path, or to add or modify a search path is to select Set Path from the File menu on the desktop,
and then use the Set Path dialog box.

The Command History Window contains a record of the commands a user has entered in the
Command Window, including both current and previous MATLAB sessions. Previously entered
MATLAB commands can be selected and re-executed from the Command History Window by
right-clicking on a command. This action launches a menu from which to select various options
in addition to executing the commands. This is a useful feature when experimenting with various
commands in a work session.

Getting Started:

To run MATLAB simply double-click the MATLAB icon on the desktop or find the MATLAB
command in the start menu. This will open a MATLAB command window, which displays a
prompt “>>”. The commands are typed at this prompt. The “>>” is the MATLAB prompt. There
is no need to type that part. Explore the built-in demos by typing demo.

MATLAB BASICS:

• Getting Help:
MATLAB provides an online help system accessible by using the help command. For
example, to get information about the function size, enter the following:
>> help size
There also is a help desk (formatted in HTML for viewing from a Web browser) with useful
introductory material. It is accessed from the Help menu. If you have no prior experience
with MATLAB, see the topic “Getting Started” in the help desk. Spend some time with this.
You can find in the help desk all the information you need to carry out the exercises.

• Variables:
MATLAB does not require the variables to be declared before their use. To assign value to a
variable equal “=” sign is used. To set x equal to 2 write at command prompt.
>> x = 2

MATLAB replies with


x=
2
Type 2^4 at the command prompt. Output will be.

Ans =
16
Ans is also MATLAB variable.

• Suppressing output:
When we type a command, function or variable name, its value appears on the screen.
Sometimes it is inconvenient if you do not want to display the output at every step of your
program. The output display of the value can be suppressed by putting the semicolon at the
end of command or variable name. If the semicolon is not present at the end of a command
line, MATLAB outputs the contents of the operation on the screen.

• Clearing the variables:


The command

>> clc

Clears the variable from the workspace. This is useful when we want to reclaim system
memory.

• Scalars, Vectors and Matrices:


Matlab simplest mathematical objects are scalars, vectors, and matrices. There are two types
of vectors. Row vectors and column vectors.

The simplest way to create a row vector is by using concatenation brackets or square
brackets. Various values in a row vector can be separated by space or comma. In column
vector various values are separated by semicolon.

>> x = [1 2 3 4]
>> y = [1; 2; 3; 4]
This will create a row vector x and column vector y. To convert a row vector into column
vector and vice versa transpose operator .’ is used.

>> x1 = x.’
>> y1 = y.’

This will create a column vector x and row vector y.

An array has dimensions M × N, where M and N are positive integers. M is the number of
rows and N is the number of columns.
If M= N = 1, the variable is a scalar.
If M = 1and N > 1, then the variable is a row vector.
If M > 1 and N = 1, then the variable is a column vector.
If both M and N are greater than one, then the variable is a matrix.
If M = N, then the variable is a square matrix.
The coefficients of an array are real or complex numbers.

• Strings:
Characters enclosed in single quotes are defined as strings. In the simplest case strings are
used for displaying messages.

>> str = ‘This is a message.’

• Comments

Starting a line with percent % sign tells MATLAB that line is a comment. As with other
programming languages it is very important to comment your code. If comments are placed
in very beginning of m-file, then by typing help filename, MATLAB prints the comments
that appear at the beginning of file. This will allow the user to expand MATLAB help
facility.

• The disp command:

A variable can be displayed by entering the variable name without semicolon. A more
flexible way of displaying the variable is by using disp(var) command where variable stands
for arbitrary variable name.
Finally, combined messages can be created by converting numerical variables into strings
and concatenating them with the string variable containing the message.

x = sqrt(25);
message = ‘The value of x is : ‘;
d = [message num2str(x)];
disp(d)

The output of above piece of code is.


The value of x is: 5
MATRIX INDEX:

Matrices can be represented conveniently in MATLAB by writing individual rows, separated by


semicolons for example, typing.

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

creates a 3 x 3 matrix in MATLAB in which the first the workspace row has elements 1, 2, 3, the
second row has elements 4, 5, 6, and so on (note the use of the brackets [ ]). If, instead, we write
the same line without the final semicolon, we would get

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

One of MATLAB most powerful index operators is the colon operator ”:”. It is used in several
different forms. For example, writing

>> 1:5
produces the row of integers 1 2 3 4 5
If we wanted to create a 1 x N matrix, X, containing the sequence 1, 2 . . . N for an integer value
of N, we would write.

>> X = 1:N;

Alternatively, we could use the fact that a:b is the same as colon(a,b) and write.

>> X = colon (1, N);

Non-uniform spacing can be obtained by specifying an increment. For example,

>> 100:-10:50 produces the sequence.

100 90 80 70 60 50

The same sequence would be produced by the statement colon (100,10,50).


When used in matrix indexing, the colon operator selects parts of a matrix. For example, the
following statement extracts the third column of A:

>> C3 = A (:,3)
C3 =
3
6
9

Similarly, we extract the second row as follows:

>> R2 = A (2,:)
R2 =
456

Finally, the following statement extracts the top two rows:

>> T2 = A (1:2,1:3)
T2 =
123
456

GENERATING MATRICES:

MATLAB provides four functions that generate the following basic matrices:
-- zeros(M,N) generates an M x N matrix of zeros.
-- ones(M,N) generates a M x N matrix of ones.
-- rand(M,N) generates a M x N matrix whose entries are uniformly distributed
random numbers in the interval [0:0; 1:0].
-- randn(M,N) generates a M x N matrix whose numbers are normally distributed (i.e., Gaussian)
numbers with mean 0 and variance 1.

For example:

>> A = 5*ones (3, 3)


A=
555
555
555

>> B = rand (2, 4)

B=
0.2311 0.4860 0.7621 0.0185
0.6068 0.8913 0.4565 0.8214

MATRIX CONCATENATION:

Matrix concatenation is the process of joining small matrices to create larger matrices. The
concatenation operator is the pair of square brackets, [ ]. Earlier in this section when we wrote.

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

All we did was concatenate three rows (separated by semicolons) to create a 3£3 matrix. Note
that individual elements are separated by a space. Separating the elements by commas would
yield the same result. Also note the order in which the elements were concatenated. The group of
three elements before the first semicolon formed the first row, the next group formed the second
row, and so on. Clearly the number of elements between semicolons must be equal. This concept
is applicable also when the elements themselves are matrices. For example, consider the 2 x 2
matrix.

>> B=[1 2; 3 4];

The statement

>> C = [B B;B+4 B-1]

in which B + 4 and B - 1 indicate adding 4 and subtracting 1 from all elements of B, respectively,
yields the result.

C=
1212
3434
5601
7823

Note how matrix B was duplicated twice in the top half of C, corresponding to the two
occurrences of B before the first semicolon in the statement C = [B B;B+4 B-1].
TRIGONOMETRIC FUNCTIONS:

Those known to MATLAB are sin ,cos ,tan.


>> x=3*cos (pi/3)
x=

1.5000
>> y=4*sin (pi/6)
y=

2.0000
>> x=3*cosd (pi/3)
x=

2.9995
>> y=4*sind (pi/6)
y=

0.0366
‘d’ denotes the degree ,if we use ‘d’ the result of trigonometric function will be in degrees.

OTHER ELEMENTARY FUNCTIONS:

These include sqrt ,exp ,log ,log10


>> sqrt (25)
ans =
5
>> log (10)
ans =
2.3026

>> log10 (10)


ans =
1
Log10 ( ) indicates the log with base 10.
>> exp (2)
ans =
7.3891

SCALAR PRODUCT:

The scalar produce is defined by multiplying the corresponding elements together and
adding the results to give a single number. Suppose we have the following vectors:

u= [8 -11 10]
v= [10 ; -21 ; -52]
w= [2 1 3]

The command for scalar produce is "*". However, the vector (or matrix) dimensions must
agree, i.e. 1xn vector can be multiplied with nx1 vector.

>> u*v
ans =

-209
>> u*w
??? Error using ==> mtimes
Inner matrix dimensions must agree.
>> u*w'
ans =
35
>> u*u'
ans =
285

SIZE OF A MATRIX:

We can find out the size of a matrix by command size.


>> A=[1 2 3;4 5 6;8 9 10]
A=
1 2 3
4 5 6
8 9 10
>> size(A)
ans =
3 3

Flip: This command is used to flip array left or right.


>>a= 2 4 6 8 10;
>>fliplr(a)
ans
10 8 6 4 2

PRACTICE QUESTIONS

Q1. What is the difference between u*w and u.*w commands. ? Take any 3x3 matrices of u
and w. write Matlab code and show the results as well.

Code:

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

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

Matrix_multiplication = u * w;

Elementwise_multiplication = u .* w;

Disp(“Matrix multiplication:”);

Disp(matrix_multiplication);

Disp(“Element-wise multiplication:”);

Disp(elementwise_multiplication);

Output:

>> u1

Matrix multiplication:

30 24 18
84 69 54

138 114 90

Element-wise multiplication:

9 16 21

24 25 24

21 16 9

Q2. Write the outputs of the commands for the following matrix

A=[ 1 2 5; 8 6 1; 5 2 9]

• A(:,:)
• A(:,1)
• A(2,:)
• A(2:3,2:3)
• A(:,2)

A(:,:)

Output:

Copy code

125861529

matlabCopy code

% Command: A(:,1) A(:,1)

Output:

Copy code

185

matlabCopy code

% Command: A(2, A(2,

Output:
Copy code

861

matlabCopy code

% Command: A(2:3,2:3) A(2:3,2:3)

Output:

Copy code

6129

matlabCopy code

% Command: A(:,2) A(:,2)

Output:

Copy code

262

Q3. Write the MATLAB code to find the roots of the quadric equation 3x2+4x-2 using the
MATLAB built in command and also by using quadratic equation. Write MATLAB code
and results as well.
3x2+4x-2
A = 3;

B = 4;

C = -2;

Roots_builtin = roots([a, b, c]);

Delta = b^2 – 4*a*c;

Root1 = (-b + sqrt(delta)) / (2*a);

Root2 = (-b – sqrt(delta)) / (2*a);

Disp(“Roots using MATLAB built-in function:”);

Disp(roots_builtin);
Disp(“Roots using quadratic formula:”);

Disp(root1);

Disp(root2);

OUTput:

Roots using MATLAB built-in function:

-1.4363

0.4363

Roots using quadratic formula:

-1.4363
Q4. Write MATLAB code to generate the sequence 20 40 60 80 100 120 140.

CODE:

Sequence = [];

initialValue = 20;

commonDifference = 20;

for I = 1:7
term = initialValue + (i-1) * commonDifference;
sequence = [sequence, term];

end
disp(sequence);
output:

20 40 60 80 100 120 140

You might also like