Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
10 views24 pages

5th Unit Matlab

Uploaded by

pamidi.prameela
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views24 pages

5th Unit Matlab

Uploaded by

pamidi.prameela
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

5th unit

Introduction of matlab

The name of matlab stands for matrix laboratory matlab is fourth generation high level programming
language and numerical analysis environment uses for matlab include matrix calculations developing
and running algorithms,creating user interfaces and data visulazation.

Matlab is an interactive system for doing numerical computations anmerical analyst called cleve moler
wrote the first version of matlab in the 1970s it has since evolved into a successful commercial software
package.

It is a very powerful software package but it is also very simple to use it like to programming language it
can handle set of mathematical calculation in large set of data matlab have contain excellent graphics
facilities it is allow matrix manipulation and plotting of functions and data implementation of algorithms
and creating of user interface,it interfacing with programming written in other languags including c,c++.

Matlab in solving engineering problems:

Matalab is a high performancelanguage for technical computing it integrates computation visualization


and programming in an easy to use environment where problems and solutions are expressed in familiar
mathematical notation

Typical uses include:

Math and computation

Algorithm development.

Modeling simulation and prototyping

Data analysis,exploration and visualization

Scientific and engineering graphics

Application development including graphics user interface building

Matlab is an interactive system whose basic data elements is an array that does not require
dimensioning this allows you to slove many technical computing problems, especially those with matrix
and vector formaulations,in a fraction of the time it would take to write a program in a scalar
noninteractive language such as c or fortran.

The matlab stands for matrix laboratory matlab was originally written to provide easy access to mateix
software developed by the linpack and eispack projects which together represent the state of the art in
software for matrix computation.
Matalb has evolved over a period of years with input from many users in university environments it is
the satandard 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 application-specific solutions called toolboxes very important to most users
of matlab toolboxes allow you to learn and apply spcialized that extend the matlab environment to slove
particular classes of problems areas in which toolboxes are available include signal processing control
systems neural networks fuzzy logic,wavelets,simulation and many others.

The malab systems : the matlab contains of five main parts:

 The matlab language


 The matlab working environment
 Handle graphics
 The matlab mathematical functions library
 The matlab application program interface

Difference between c and matlab

Characteristics MATLAB C Language

C is a mid-
level general-
MATLAB is a high-performance scripting
purpose
language.
programming
Language Type language.

General-
purpose
programming
language with
Primarily used for matrix manipulations,
applications
implementation of algorithms, plotting of
in system
functions, and data.
programming,
game
development
Usage and more.
Characteristics MATLAB C Language

Low-level
syntax with
the
The High-level and matrix-based syntax procedural
suitable for the mathematical operations. and
structured
programming
Syntax approach.

C is an open-
It is not an open-source and has license cost
Open-source and source
attached.
Cost language

The Direct
manipulation
of memory
Native support for the matrix and array
using the
operations.
pointers; no
built-in matrix
Data Representation support.

C follows the
syntax of
programming
Relatively easy to learn due to its interactive
language
and availability of lot of tool kits for most of
thus, making
the functionalities.
it hard for the
newcomer to
Ease of Learning comprehend.

The Manual
memory
management
requires
Automatic memory management.
explicit
allocation
Memory and
Management deallocation.

Performance When it comes to basic mathematical C is overall


Characteristics MATLAB C Language

faster than
functions, MATLAB have a robust matlab in all
mechanism to handle it. kind of
operations.

Highly
portable can
MATLAB cannot run the same licensed
run on any
version on different operating systems.
Platform operating
Independence system.

Requires
separate
compilers
The Integrated environment with the tools for and tools;
simulation, debugging and visualization. lacks an
integrated
Development environment
Environment like Matlab.

Arithmetic operators in matlab:

MATLAB allows two different types of arithmetic operations −

 Matrix arithmetic operations


 Array arithmetic operations

Matrix arithmetic operations are same as defined in linear algebra. Array operations are
executed element by element, both on one dimensional and multi-dimensional array.

The matrix operators and arrays operators are differentiated by the period (.) symbol.
However, as the addition and subtraction operation is same for matrices and arrays, the
operator is same for both cases.

The following table gives brief description of the operators –


Sr.N
Operator & Description
o.

+
1 Addition or unary plus. A+B adds the values stored in variables 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.
-
2 Subtraction or unary minus. A-B subtracts the value of 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.
*
Matrix multiplication. C = A*B is the linear algebraic product of the matrices A and B.
More precisely,
3

For non-scalar A and B, the number of columns of A must be equal to the number of rows
of B. A scalar can multiply a matrix of any size.
.*
4 Array multiplication. A.*B is the element-by-element product of the arrays A and B. A and
B must have the same size, unless one of them is a scalar.
/
5 Slash or matrix right division. B/A is roughly the same as B*inv(A). More precisely, B/A =
(A'\B')'.
./
6 Array right division. A./B is the matrix with elements A(i,j)/B(i,j). A and B must have the
same size, unless one of them is a scalar.
\
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
7
column vector with n components, or a matrix with several such columns, then X = A\B is
the solution to the equation AX = B. A warning message is displayed if A is badly scaled or
nearly singular.
.\
8 Array left division. A.\B is the matrix with elements B(i,j)/A(i,j). A and B must have the
same size, unless one of them is a scalar.
^
Matrix power. X^p is X to the power p, if p is a scalar. If p is an integer, the power is
9 computed by repeated squaring. If the integer is negative, X is inverted first. For other
values of p, the calculation involves eigenvalues and eigenvectors, such that if [V,D] =
eig(X), then X^p = V*D.^p/V.
.^
10 Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. A and B must have
the same size, unless one of them is a scalar.
'
11 Matrix transpose. A' is the linear algebraic transpose of A. For complex matrices, this is the
complex conjugate transpose.
.'
12 Array transpose. A.' is the array transpose of A. For complex matrices, this does not involve
conjugation.

Relation operator in matlab:

Relational Operators
Relational operators can also work on both scalar and non-scalar data. Relational operators
for arrays perform element-by-element comparisons between two arrays and return a logical
array of the same size, with elements set to logical 1 (true) where the relation is true and
elements set to logical 0 (false) where it is not.

The following table shows the relational operators available in MATLAB −

Show Examples

Sr.N
Operator & Description
o.

<
1
Less than
<=
2
Less than or equal to
>
3
Greater than
>=
4
Greater than or equal to
==
5
Equal to
~=
6
Not equal to
Logical Operators
MATLAB offers two types of logical operators and functions −

 Element-wise − These operators operate on corresponding elements of logical


arrays.
 Short-circuit − These operators operate on scalar and, logical expressions.

Element-wise logical operators operate element-by-element on logical arrays. The symbols


&, |, and ~ are the logical array operators AND, OR, and NOT.

Short-circuit logical operators allow short-circuiting on logical operations. The symbols &&
and || are the logical short-circuit operators AND and OR.

Show Examples

Bitwise Operations
Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &, |, and
^ are as follows −

p q p&q p|q p^q

0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

Assume if A = 60; and B = 13; Now in binary format they will be as follows −

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

MATLAB provides various functions for bit-wise operations like 'bitwise and', 'bitwise or' and
'bitwise not' operations, shift operation, etc.
The following table shows the commonly used bitwise operations −

Show Examples

Function Purpose

bitand(a, b) Bit-wise AND of integers a and b


bitcmp(a) Bit-wise complement of a
bitget(a,pos) Get bit at specified position pos, in the integer array a
bitor(a, b) Bit-wise OR of integers a and b
bitset(a, pos) Set bit at specific location pos of a
Returns a shifted to the left by k bits, equivalent to multiplying by 2k.
Negative values of k correspond to shifting bits right or dividing by 2|k| and
bitshift(a, k)
rounding to the nearest integer towards negative infinite. Any overflow bits
are truncated.
bitxor(a, b) Bit-wise XOR of integers a and b
swapbytes Swap byte ordering

Set Operations
MATLAB provides various functions for set operations, like union, intersection and testing for
set membership, etc.

The following table shows some commonly used set operations −

Show Examples

Sr.N
Function & Description
o.

intersect(A,B)
1 Set intersection of two arrays; returns the values common to both A and B. The values
returned are in sorted order.
intersect(A,B,'rows')
2 Treats each row of A and each row of B as single entities and returns the rows common
to both A and B. The rows of the returned matrix are in sorted order.
ismember(A,B)
3 Returns an array the same size as A, containing 1 (true) where the elements of A are
found in B. Elsewhere, it returns 0 (false).
ismember(A,B,'rows')
Treats each row of A and each row of B as single entities and returns a vector
4
containing 1 (true) where the rows of matrix A are also rows of B. Elsewhere, it returns
0 (false).
issorted(A)
Returns logical 1 (true) if the elements of A are in sorted order and logical 0 (false)
5
otherwise. Input A can be a vector or an N-by-1 or 1-by-N cell array of strings. A is
considered to be sorted if A and the output of sort(A) are equal.

issorted(A, 'rows')
Returns logical 1 (true) if the rows of two-dimensional matrix A is in sorted order, and
6
logical 0 (false) otherwise. Matrix A is considered to be sorted if A and
the output of sortrows(A) are equal.
setdiff(A,B)
7 Sets difference of two arrays; returns the values in A that are not in B. The values in the
returned array are in sorted order.
setdiff(A,B,'rows')
Treats each row of A and each row of B as single entities and returns the rows from A
8
that are not in B. The rows of the returned matrix are in sorted order.
The 'rows' option does not support cell arrays.
setxor
9
Sets exclusive OR of two arrays
union
10
Sets union of two arrays
unique
11
Unique values in array

Elements wise multiplication/ division /power operations and array


multiplication/ division/ power operations:
Introduction
MATLAB has two different types of arithmetic operations: array operations and matrix
®

operations. You can use these arithmetic operations to perform numeric computations, for
example, adding two numbers, raising the elements of an array to a given power, or multiplying
two matrices.
Matrix operations follow the rules of linear algebra. By contrast, array operations execute
element by element operations and support multidimensional arrays. The period character ( .)
distinguishes the array operations from the matrix operations. However, since the matrix and
array operations are the same for addition and subtraction, the character pairs .+ and .- are
unnecessary.
Array Operations
Array operations execute element by element operations on corresponding elements of vectors,
matrices, and multidimensional arrays. If the operands have the same size, then each element in
the first operand gets matched up with the element in the same location in the second operand. If
the operands have compatible sizes, then each input is implicitly expanded as needed to match
the size of the other.
As a simple example, you can add two vectors with the same size.
A = [1 1 1]
A =

1 1 1
B = [1 2 3]
B =

1 2 3
A+B
ans =

2 3 4
If one operand is a scalar and the other is not, then MATLAB implicitly expands the scalar to be
the same size as the other operand. For example, you can compute the element-wise product of a
scalar and a matrix.
A = [1 2 3; 1 2 3]
A =

1 2 3
1 2 3
3.*A
ans =

3 6 9
3 6 9
Implicit expansion also works if you subtract a 1-by-3 vector from a 3-by-3 matrix because the
two sizes are compatible. When you perform the subtraction, the vector is implicitly expanded to
become a 3-by-3 matrix.
A = [1 1 1; 2 2 2; 3 3 3]
A =

1 1 1
2 2 2
3 3 3
m = [2 4 6]
m =

2 4 6
A - m
ans =
-1 -3 -5
0 -2 -4
1 -1 -3
A row vector and a column vector have compatible sizes. If you add a 1-by-3 vector to a 2-by-1
vector, then each vector implicitly expands into a 2-by-3 matrix before MATLAB executes the
element-wise addition.
x = [1 2 3]
x =

1 2 3
y = [10; 15]
y =

10
15
x + y
ans =

11 12 13
16 17 18
If the sizes of the two operands are incompatible, then you get an error.
A = [8 1 6; 3 5 7; 4 9 2]
A =

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

2 4
A - m
Matrix dimensions must agree.
For more information, see Compatible Array Sizes for Basic Operations.
The following table provides a summary of arithmetic array operators in MATLAB. For
function-specific information, click the link to the function reference page in the last column.
Operato
Purpose Description Reference Page
r

+ Addition A+B adds A and B. plus

+ Unary plus +A returns A. uplus

- Subtraction A-B subtracts B from A minus

- Unary minus -A negates the elements of A. uminus

.* Element-wise multiplication A.*B is the element-by-element product of A and B. times

.^ Element-wise power A.^B is the matrix with elements A(i,j) to the B(i,j) power. power
Operato
Purpose Description Reference Page
r

./ Right array division A./B is the matrix with elements A(i,j)/B(i,j). rdivide

.\ Left array division A.\B is the matrix with elements B(i,j)/A(i,j). ldivide

.' Array transpose A.' is the array transpose of A. For complex matrices, this does not involve transpos
conjugation.
e

Matrix Operations
Matrix operations follow the rules of linear algebra and are not compatible with
multidimensional arrays. The required size and shape of the inputs in relation to one another
depends on the operation. For nonscalar inputs, the matrix operators generally calculate different
answers than their array operator counterparts.
For example, if you use the matrix right division operator, /, to divide two matrices, the matrices
must have the same number of columns. But if you use the matrix multiplication operator, *, to
multiply two matrices, then the matrices must have a common inner dimension. That is, the
number of columns in the first input must be equal to the number of rows in the second input.
The matrix multiplication operator calculates the product of two matrices with the formula,
C(i,j)= ∑ A(i,k)B(k,j).
n k=1
To see this, you can calculate the product of two matrices.
A = [1 3;2 4]
A =

1 3
2 4
B = [3 0;1 5]
B =

3 0
1 5
A*B
ans =

6 15
10 20
The previous matrix product is not equal to the following element-wise product.
A.*B
ans =

3 0
2 20
The following table provides a summary of matrix arithmetic operators in MATLAB. For
function-specific information, click the link to the function reference page in the last column.
Operato
Purpose Description Reference Page
r

* Matrix multiplication C = A*B is the linear algebraic product of the matrices A and B. The number of columns mtimes
of A must equal the number of rows of B.

\ Matrix left division x = A\B is the solution to the equation Ax = B. Matrices A and B must have the same mldivide
number of rows.

/ Matrix right division x = B/A is the solution to the equation xA = B. Matrices A and B must have the same mrdivide
number of columns. In terms of the left division operator, B/A = (A'\B')'.

^ Matrix power A^B is A to the power B, if B is a scalar. For other values of B, the calculation involves mpower
eigenvalues and eigenvectors.

' Complex conjugate A' is the linear algebraic transpose of A. For complex matrices, this is the complex conjugate ctranspos
transpose transpose.
e

Usage of line space operator CLC,CLEAR,WHO,WHOS commands:

Syntax and usage of decision making statements if end statement if


else end statement used in matlab
Decision making structures require that the programmer should specify one or more
conditions to be evaluated or tested by the program, along with a statement or statements
to be executed if the condition is determined to be true, and optionally, other statements to
be executed if the condition is determined to be false.

Following is the general form of a typical decision making structure found in most of the
programming languages −
if-end

if-else-end

nested-if-end

if-elseif-elseif-else-end

switch case

nested switch case

if-end Statement
An if-end statement is the simplest decision-making statement. It decides
whether a particular block of code has to be executed or not, based on the given
boolean condition. Only when the given condition is true, it executes the
statements inside the block otherwise not.

Syntax:
if (condition)

% statement(s) will execute


% if the boolean expression is true

<statements>

end

Example:
% MATLAB program to illustrate

% if-end statement

number = 28;

if number>10

fprintf('The number is greater than 10.');

end

Output:
The number is greater than 10.

if-else-end statement
In conditional if Statement the additional block of code is merged as else
statement which is performed when if the condition is false else condition won’t
be executed when if the condition is True.

Syntax:
if (condition)

% statement(s) will execute

% if the boolean expression is true

<statement(s)>
else

<statement(s)>

% statement(s) will execute

% if the boolean expression is false

end

Example 1
% MATLAB program to illustrate

% if-else-end statement

number = 28;

if number<10

fprintf('The number is greater than 10');

else

fprintf('The number is not less than 10');

end

Output:
The number is not less than 10

Example 2: You can also chain if-else-end statements with more than one
condition.

% MATLAB program to illustrate

% if-else chaining

number = 28;

if number<10
fprintf('The number is less than 10\n');

else

if number<20

fprintf('The number is less than 20\n');

else

fprintf('The number is less than 30\n');

end

end

Output:
The number is less than 30

Nested if-end Statement


There comes some situations where multiple conditions have to be satisfied to
execute a block of code then we use nested if-end statements. This is nothing but
another if condition(s) inside an if condition.

Syntax:
if (condition)

% Executes when the boolean expression 1 is true

if (condition)

% Executes when the boolean expression 2 is true

end

end

Example:
% MATLAB program to illustrate

% Nested if-end statements

number = 2;

if number<10

fprintf('The number is less than 10\n');

% Executes when then above if

% condition is true

if number<5

fprintf('Also The number is less than 5');

end

end

Output:
The number is less than 10

Also The number is less than 5

if-elseif-elseif-else-end
An if statement can be followed by one (or more) optional elseif and an else statement, which
is very useful to test various conditions.

Syntax:
if (condition)

% Executes when the expression 1 is true

<statement(s)>

elseif (condition)
% Executes when the boolean expression 2 is true

<statement(s)>

elseif (condition)

% Executes when the boolean expression 3 is true

<statement(s)>

else

% executes when the none of the above condition is true

<statement(s)>

end

Example:

% MATLAB program to illustrate

% if-elseif-else-end statement
number = 28;

if number<10

fprintf('The number is less than 10\n');

elseif number<20

fprintf('The number is less than 20\n');

elseif number<30

fprintf('The number is less than 30\n');

else

fprintf('The number is less than 40\n');


end

Output:
The number is less than 30

Switch case
A switch block is familiar to if-elif-else-end statements. It works as same as in
other languages except for syntax. But there are few key differences between
them. A switch block conditionally executes one set of statements from several
choices. Each choice is covered by a case statement. A switch expression can be
any of the following.

Numbers

Characters

Strings

Objects

Here comparison of string expressions and case expressions is case-sensitive.


Every character of a switch string expression must be matched with the case
string expression.

Syntax:
switch (condition)

case condition

<statements>

case (condition)

<statements>


otherwise

<statements>

end

Example 1:
grade = 'A';

switch(grade)

case 'A'

fprintf('Excellent!\n' );

case 'B'

fprintf('Well done\n' );

case 'C'

fprintf('Good\n' );

case 'D'

fprintf('You passed\n' );

case 'F'

fprintf('Better try again\n' );

otherwise

fprintf('Invalid grade\n' );

end

Output:

Excellent!
Syntax and usage of loop statements:
There may be a situation when you need to execute a block of code several number of
times. In general, statements are executed sequentially. The first statement in a function is
executed first, followed by the second, and so on.

Programming languages provide various control structures that allow for more complicated
execution paths.

A loop statement allows us to execute a statement or group of statements multiple times


and following is the general form of a loop statement in most of the programming languages

MATLAB stands for Matrix Laboratory. It is a high-performance language that is


used for technical computing. It was developed by Cleve Molar of the company
MathWorks.Inc in the year 1984.It is written in C, C++, Java. It allows matrix
manipulations, plotting of functions, implementation of algorithms and creation
of user interfaces.
1. While Loop:
While loop works same as it does in other common languages like python, java
etc. But here syntax varies from language to language. While loop is used to
execute a block of statements repeatedly until a given a condition is satisfied. And
when the condition becomes false, the line immediately after the loop in program
is executed.

Syntax:
while expression

statements

end

Example 1:
%MATLAB code to illustrate

%for loop

count=0;

while (count < 3)

fprintf('Hello From matlab\n');

count=count+1;

end

output:

Hello from matlab

Hello from matlab

Hello from matlab


2. For Loop:
For loops are used for sequential traversal. As syntax varies from language to
language. Let us learn how to use for loop for sequential traversals.

Syntax:

for initial value:step value:final value

statements

end

or

for initial value:final value

statements

end

Example:

%MATLAB code to illustrate

%for loop

for i = 1:5

fprintf('%d ',i)

end

output:
1 2 3 4 5

You might also like