Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Practical 1

Uploaded by

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

Practical 1

Uploaded by

Hafiz Muhammad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Practical 1

Introduction to MATLAB & its Basics

Objective:

 Overview of MATLAB.
 Basics of MATLAB

Tools/Software Requirement

 MATLAB

Theory
Introduction to MATLAB
MATLAB is a high-performance mathematical computing software. It integrates computation,
visualization, and programming in an easy-to-use environment where problems and solutions are expressed
in a familiar mathematical notation. Typical uses include

 Math and computation


 Algorithm development
 Data acquisition Modeling, simulation, and prototyping
 Data analysis, exploration, and visualization
 Scientific and engineering graphics
 Application development, including graphical user interface building

MATLAB is an interactive system whose basic data element is an array. This allows you to solve many
technical computing problems, especially those with matrix and vector formulations, in a fraction of the
time it would take to write a program in a scalar non interactive language such as C or Fortran.
The name MATLAB stands for matrix laboratory. MATLAB was originally written to provide easy access
to matrix software developed by the LINPACK and EISPACK projects. Today, MATLAB engines
incorporate the LAPACK and BLAS libraries, embedding the state of the art in software for matrix
computation.
MATLAB has evolved over a period of years with input from many users. In university environments, it is
the standard instructional tool for introductory and advanced courses in mathematics, engineering, and
science. In industry, MATLAB is the tool of choice for high-productivity research, development, and
analysis.
MATLAB features a family of add-on application-specific solutions called toolboxes. Very important to
most users of MATLAB, toolboxes allow you to learn and apply specialized technology. Toolboxes are
comprehensive collections of MATLAB functions (M-files) that extend the MATLAB environment to
solve particular classes of problems. Areas in which toolboxes are available include signal processing,
control /systems, neural networks, fuzzy logic, and many others.

THE MATLAB SYSTEM


The MATLAB system consists of five main parts:
1. Development Environment:

This is the set of tools and facilities that help you use MATLAB functions and files. Many of these
tools are graphical user interfaces. It includes the MATLAB desktop and Command Window, a command
history, an editor and debugger, and browsers for viewing help, the workspace, files, and the search path.
2. The MATLAB Mathematical Function Library:

This is a vast collection of computational algorithms ranging from elementary functions, like sum,
sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse, transfer functions,
fast Fourier transforms etc.

3. The MATLAB Language:

This is a high-level matrix/array language with control flow statements, functions, data structures,
input/output, and object-oriented programming features. It allows both "programming in the small" to
rapidly create quick and dirty throw-away programs, and "programming in the large" to create large and
complex application programs.
4. Graphics:

MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as
annotating and printing these graphs. It includes high-level functions for two-dimensional and three-
dimensional data visualization, image processing, animation, and presentation graphics. It also includes
low-level functions that allow you to fully customize the appearance of graphics as well as to build
complete graphical user interfaces on your MATLAB applications.
Procedure
a. STARTING MATLAB:

To start MATLAB from Windows, double-click the MATLAB icon on your Windows desktop. When
MATLAB starts, the central window in the desktop is the Command Window, where the special _ prompt
appears.
This prompt means that MATLAB is waiting for a command. You can quit MATLAB at any time with one
of the following:
b. General commands and operators in MATLAB
Once MATLAB has been successfully started, start the following set of activities to begin working on
MATLAB.
Task 1 Basic Arithmetic Operations

(a) Type 2+3 after the >> prompt, followed by Enter, i.e. press the Enter key, as indicated by <Enter>,
below:
>> 2+3 <Enter>
Commands are only carried out when you press Enter. The answer in this case is, of course, 5.
(b) Next try the following:
>> 3-2 <Enter> 2
>> 2*3 <Enter> 6
>> 1/2 <Enter> 0.5
>> 2ˆ3 <Enter> 8
>> 2\1 <Enter> 2
Differentiate between the symbols “/” and this “\” by using some more examples and mention the
difference here:

“/” Slash or matrix right division. B/A is roughly the same as B*inv(A) More
precisely, B/A = (A'\B')'. See \.
This is also used for division.
“\” Backslash or matrix left division. If A is a square matrix, A\Bis roughly the same
as inv(A)*B, except it is computed in a different way. If A is an n-by-n matrix and B is
a column vector with n components, or a matrix with several such columns, then X
= A\B is the solution to the equation AX = B computed by Gaussian elimination.
→ B A & right division: →

(c) MATLAB is sensible about anticipating some errors; it warns you in case you didn’t realize you
were dividing by zero, but still gives the answer Inf.
How does MATLAB handle 0/1 and 1/0?
The MATLAB response is shown below:

Another special value that you may meet is NaN, which stands for Not-a-Number. It is the answer to
calculations like 0/0.
(d) Assigning Values to Variables
MATLAB allows for very easy definition of variables without defining their type unlike other
programming languages.

i. Enter the command (in programming jargon a statement) a = 2, i.e. the MATLAB command line should
look like this:

>> a = 2 <Enter>
This statement assigns the value of 2 to variable a. (Note that this value is displayed immediately after the
statement is executed.) Now try entering the statement
>> a = a + 7
Followed on a new line by a = a * 10.
Mention your answer here: ________90____
ii. Now enter the statement
>> b = 3; <Enter>
The semicolon (;) prevents the value of b from being displayed. However, b still has the value 3 as you can
see by entering its name without a semicolon, i.e. by executing the following command:
>> b <Enter>.
iii. Assign any values you like to two variables x and y. Now see if you can in a single statement assign the sum of x
and y to a third variable z. One way of doing this is
>> x = 2; y = 3; <Enter>
>> z = x + y <Enter>
Z=5
Notice that, in addition to doing the arithmetic with variables with assigned values, several commands
separated by semicolons (or by commas) can be put on one line.
Task 2 Matrices:

A Matrix array is two-dimensional, having both multiple rows and multiple columns, similar to
vector arrays:

It begins with “[“, and end with “]”

Spaces or commas are used to separate elements in a row and semicolon or enter is used to separate
rows.

Example:

>> f = [1 2 3; 4 5 6]

f=
1 2 3

4 5 6

>> h = [2 4 6 1 3 5]

h=2 4 6 1 3 5

Some useful commands:

a) Size of a Matrix

In order to find out the size of a matrix, use the size command

Example:
>> f = [1 2 3; 4 5 6]

Enter the command Size (f) and it will return the answer in terms of rows and columns

ans =

2 3

b) Accessing an entry from a Matrix

-- matrixname(row, column)

-- Colon may be used in place of a row or column reference to select the entire row or column.

Example: f = [ 1 2 3; 4 5 6]

>> f (2,2)

ans =

-- Colon may be used in place of a row or column reference to select the entire row or column.

Example:

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

>> f (:,2)

ans =

2
5
8

Table 1.1 List of command and its use

zeros(n) returns an n x n matrix of zeros


zeros(m,n) returns a m x n matrix of zeros
ones(n) returns a n x n matrix of ones
ones(m,n) returns a m x n matrix of ones
rand(n) returns a n x n matrix of random number
rand(m,n) returns a m x n matrix of random number

size (A) for a m x n matrix A, returns the row vector [m,n]


containing the number of rows and columns in matrix.
length(A) returns the larger of the number of rows or columns in A.
Transpose B = A’
Identity Matrix eye(n) → returns an n x n identity matrix eye(m,n) →
returns an m x n matrix with ones on the main diagonal
and zeros elsewhere.
Addition C=A+B C=A–B
and subtraction
Scalar Multiplication B = αA, where α is a scalar.
Matrix C = A*B
Multiplication
Matrix Inverse B = inv(A), A must be a square matrix in this case.
rank (A) → returns the rank of the matrix A.
Matrix Powers = A.^2 → squares each element in the matrix
= A * A → computes A*A, and A must be a square
matrix.
Determinant det (A), and A must be a square matrix.

Note: In the table above, A, B, C are matrices, and m, n, α are scalars.

Array Operations:
a) Scalar-Array Mathematics
For addition, subtraction, multiplication, and division of an array by a scalar simply apply the
operations to all elements of the array.
Example:
>> f = [1 2; 3 4]

f=

1 2

3 4

>> g = 2*f – 1 (Each element in the array f is multiplied by 2, then subtracted by 1)

ANS =

g=
1 3

5 7

Table 1.2 Element-by-Element Array-Array Mathematics

Operation Algebraic Form MATLAB


Addition a+b a+b
Subtraction a–b a–b
Multiplication axb a .* b
Division a÷b a ./ b
Exponentiation ab a .^ b

Example:

>> x = [1 2 3];
>> y = [4 5 6];
>> z = x.* y // each element in x is multiplied by the corresponding
element in

y. z = 4 10 18

b) Solutions to Systems of Linear Equations Example:


A system of 3 linear equations with 3 unknowns (x1, x2, x3):
3x1 + 2x2 – x3 = 10
-x1 + 3x2 + 2x3 = 5
x1 – x2 – x3 = -1
Let:

Then, system can be described as: Ax = b

In MATLAB: In MATLAB:
>> A = [ 3 2 -1; -1 3 2; 1 -1 -1]; >> A = [ 3 2 -1; -1 3 2; 1 -1 -1];
>> B = [ 10; 5; -1]; >> B = [ 10; 5; -1];
>> x = inv(A)*B >> x = A\B
x= x=
-2.0000 -2.0000
5.0000 5.0000
-6.0000 -6.0000
Answer: Answer:

Note: left division: → B A & right division: →

Q. Find the determinant of any 3x3 Matrix having symbol A.

Paste your answer here:

Plotting a Point/Equations

a) Plotting a point:
>> plot ( variablename, ‘symbol’)
The function plot () creates a graphics window, called a Figure window, and named by //default“Figure
No. 1”
Example: Complex number

>> z = 1 + 0.5j;

>> plot (z, ‘.’)


Figure 1.1 plotting a point on graph

b) Plotting Curves:

Lets x and y are two matrices and y is dependent on x. To generate a linear plot of the values of x
(horizontal axis) and y (vertical axis), we consider the following example.

Example

x = [0:1:10] (X has the values ranging from 0 to 10 with an increment of 1)


y = x.^2

Then by entering command plot (x,y) will generate a linear plot of the values of x (horizontal
axis) and y (vertical axis).

Figure 1.2 plotting a curve on graph

c) Multiple Curves:
• plot (x, y, w, z) – multiple curves can be plotted on the same graph by using multiple arguments
in a plot command. The variables x, y, w, and z are vectors. Two curves will be plotted: y vs. x,
and z vs. w.
d) Multiple Figures:
• figure (n) – used in creation of multiple plot windows. place this command before the plot()
command, and the corresponding figure will be labeled as “Figure n” close – closes the figure
n window.
• close all – closes all the figure windows.
e) Subplots:
subplot (m, n, p) – m by n grid of windows, with p specifying the current plot as the pth window

Example: (polynomial function)


Plot the given polynomial using linear/linear scale
First, generate the polynomial:
x = linspace (0, 10, 100);
y = 2*x.^2 + 7*x + 9;
% plotting the polynomial:
figure (1);
subplot (2,2,1), plot (x,y);

title ('Polynomial, linear/linear scale');


ylabel ('y'), grid;

subplot (2,2,2), plot (x,y);


title ('Polynomial, log/linear scale');
ylabel ('y'), grid;

Matlab Ouput:

Figure 1.3 Figure of Subplots for a polynomial

.m Files in MATLAB
An m file or script file is a simple text file where one can place MATLAB commands and save it in order
to recall them later. MATLAB reads these files commands and executes them exactly as it would if you
has typed each command sequentially at the command window’s prompt. A slight disadvantage with M-
file is that you must follow the prescribed format, or else it will not run correctly.
Example:

The following function M-file finds the value of function f(x) = sin x + 𝑥 3 for any value of x. Type it in
and save as excercisefunction.m in your current directory.

% excercisefunction.m
% input : x
% output: p, solved in terms of x
function p = excercisefunction (x) % Notice the format
p = sin (x) + x^3
Call this function from the command window using the following command and then update it to find the
value for x = 3,4,5,6.
Excercisefunction (3) (It will return the value for x = 3)

Q. Make your own function f(y) for cos (y) + 𝒚𝟐 for any value of y. Type it
and recall it. Make sure you save your name and date as well.
Program:
y = (2*pi)*(50/1000)*[0:40];
x = cos(y) + y.^2;
plot(x)

Output:

Observations / Analysis:
It is observed that the graph is generated for given values, in the function, the following terms
and their meanings are given below:
(50/1000): this is a scaling term.
[0:40]: this term is used to define the starting and ending point of the graph, the graph is
generated between 0 and 40.
Post LAB Activity

1.) Set x = 4, y = 12, z = -2 and find the following

(a) y/x*z (b) y/(x*z)

Are these different? Why or why not?


Yes, the above values are different, this is because the MATLAB functions according to
DEMAS rules, so it first read the bracket values in 2nd case.
2.) Find the square root of x, y, and z above using the built in MATLAB.
3.) Create the following row vector a = [1,2,3,4,5,6] two different ways.

4.) Make a column vector ‘b’ that is the transpose of ‘a’ two different ways.
Evaluation Criteria:

Performance Exemplary Satisfactory Developing Unsatisfactory Marks


Criteria
(5) (3-4) (1-2) (0)

Procedure Steps of Steps of Steps of experiments Procedure is


experiments are experiments are are incomplete and missing.
clear, sequential present but lacking procedure is lacking.
and in complete completeness. Conclusion is Conclusion is
sentences. Pictures incomplete. missing.
of Responses are Result & Analysis is
included. Result & written in
Analysis is written incomplete
in a complete form. sentence.

Understanding Understands Understands Understands few Wasn’t able to


the Concept everything of the majority of the things. understand
topic. portion. anything.

Lab Instructor: Dr. Liaquat Ali Khan/Lab Engr. Wahaj Rafique

You might also like