You are on page 1of 68

PRESENTED BY:

YOUSAF KHAN

ROLL #
2018-CE-01
MATLAB
MATLAB stands for matrix laboratory.
o High-performance language for
technical computing
o Integrates computation,
visualization, and programming in
an easy-to-use environment where
problems and solutions are
expressed in familiar mathematical
notation.
MATLAB
The MATLAB Application:

o Math and computation


o Algorithm development
o Data acquisition
o Modeling, simulation, and prototyping
o Data analysis, exploration, and visualization
o Scientific and engineering graphics
o Application development, including
graphical user interface building.
MATLAB
The MATLAB system have five main parts
1. Development Environment.
2. The MATLAB Mathematical Function Library.
3. The MATLAB Language.
4. Graphics.
5. The MATLAB Application Program Interface (API).
MATLAB Tool Box
Statistics Toolbox
o Contains about 250 functions and GUI’s for:
generating random numbers, probability
distributions, hypothesis Testing, statistical
plots and covers basic statistical functionality

Signal Processing Toolbox


o An environment for signal analysis
waveform generation, statistical signal
processing, and spectral analysis
o Useful for designing filters in conjunction
with the image processing toolbox
MATLAB Tool Box
Neural Network Toolbox
o GUI for creating, training, and simulating
neural networks.
o It has support for the most commonly used
supervised

Optimization Toolbox
o Includes standard algorithms for optimization
o Including minimax, goal attainment, and semi-
infinite minimization problems
MATLAB Tool Box
Curve Fitting Toolbox
o Allows you to develop custom linear and nonlinear models in a graphical user interface.
o Calculates fits, residuals, confidence intervals, first derivative and integral of the fit.
Another Tool boxes :
o Communications Toolbox
o Control System Toolbox
o Data Acquisition Toolbox
o Database Toolbox
o Image Processing Toolbox
o Filter Design Toolbox
o Financial Toolbox
o Fixed-Point Toolbox
o Fuzzy Logic Toolbox
Introduction to Simulink
o Simulink is a graphical, “drag and drop” environment for building
simple and complex signal and system dynamic simulations.
o It allows users to concentrate on the structure of the problem,
rather than having to worry (too much) about a programming
language.
o The parameters of each signal and system block is configured by the
user (right click on block)
o Signals and systems are simulated over a particular time.
MATLAB File Extensions
• .fig
MATLAB Figure
• .m
MATLAB function, script, or class
• .mat
MATLAB binary file for storing variables
• .mex
MATLAB executable (platform specific, e.g. ".mexmac" for
the Mac, ".mexglx" for Linux)
Connecting to MATLAB
Deploying with MATLAB
MATLAB History
o In the mid-1970s, Cleve Moler and several colleagues
developed 2 FORTRAN libraries
• LINPACK for solving linear equations
• EISPACK for solving eigenvalue problems.
o In the late 1970s, Moler, “chairman of the computer
science at the University of New Mexico”, wanted to
teach students linear algebra courses using the LINPACK
and EISPACK software.
o He didn't want them to have to program in FORTRAN,
because this wasn't the purpose of the course.
MATLAB History
o He wrote a program that provide simple interactive
access to LINPACK and EISPACK.
o Over the next years, when he visit another university, he
leave a copy of his MATLAB.
o In 1983, second generation of MATLAB was devoloped
written in C and integrated with graphics.
o The MathWorks, Inc. was founded in 1984 to market and
continue development of MATLAB.
MATLAB Environment
• MATLAB Desktop
MATLAB Environment
Command window
• save filename % save data from workspace to a file
• load filename % loads data from file to a workspace
• who % list variables exist in the workspace
• whos % list variables in details
• clear % clear data stored in the workspace
• clc % clears the command window
• ctrl+c % To abort a command
• exit or quit % to quit MATLAB
MATLAB Environment
Command window
• Through Command window:
o help command
Ex: >> help plot
o lookfor anystring
Ex: >> lookfor matrix
• Through Menus: (Using help window
o doc command
Ex: >> doc plot
MATLAB Variables
• To create a variable, simply assign a value to a name:
»var1=3.14
»myString=‘hello world’
• Variable name must start with letter.
• It is case sensitive (var1 is different from var1).
• To Check the variable name validation “isvarname [name]”
o isvarname X_001
o isvarname if
• To check the Max length supported by current MATLAB version
“namelengthmax”
MATLAB Variables
o MATLAB is a weakly typed language
(No need to declare variables!)
o MATLAB supports various types, the most often used are
»3.84
64-bit double (default)
»‘a’
16-bit char
o Most variables are vectors or matrices of doubles or chars
o Other types are also supported:
complex, symbolic, 16-bit and 8 bit integers.
MATLAB Environment
VARIABLES
• Variable can’t have the same name of keyword
o Use “iskeyword” to list all keywords
• Built-in variables. Don’t use these names!
o i and j can be used to indicate complex numbers
o Pi has the value 3.1415
o ans stores the last unassigned value (like on a calculator)
o Inf and –Inf are positive and negative infinity
o NaN represents ‘Not a Number’
MATLAB Environment
VARIABLES
• Warning:
MATLAB allows usage of the names of the built in function.
This is dangerous since we can overwrite the meaning of a
function.
• To check that we can use:
>> which sin ...
C:MATLABtoolboxmatlabelfun...
>> which ans … ans is a variable.
MATLAB Variables
1-Scaler:
• A variable can be given a value explicitly
»a = 10
shows up in workspace!
• Or as a function of explicit values and existing
variables
»c = 1.3*45-2*a
• To suppress output, end the line with a semicolon
»cooldude = 13/3;
MATLAB Variables
2-Array:
• Like other programming languages, arrays are an important
part of MATLAB
• Two types of arrays
1) Matrix of numbers (either double or complex
2) Cell array of objects (more advanced data structure)
MATLAB Variables
Row Vector:
• comma or space separated values between brackets
»row = [1 2 5.4 -6.6]
»row = [1, 2, 5.4, -6.6];
• Command window:

• Workspace: Row Vector:


MATLAB Variables
Column vector:
• Semicolon separated values between brackets
»column = [4;2;7;4]
• Command window:

• Workspace: Column vector:


MATLAB Variables
Vectors:
• The difference between a row and a column vector can get by:
o Looking in the workspace
o Displaying the variable in the command window
o Using the size function

• To get a vector's length, use the length function


MATLAB Variables
Vectors:
>> startP= 1;
>> endP= 10;
>> number_of_points= 100;
>> x= linspace (startP, endP, number_of_points)

>> step= 1;
>> x= startP : step : endP;
MATLAB Variables
Matrix:
• Make matrices like vectors
• Element by element
» a= [1 2;3 4];
• By concatenating vectors or matrices (dimension matters)
MATLAB Special matrices
• ones:
>> x = ones(1,7) % All elements are ones
• zeros:
>> x = zeros(1,7) % All elements are zeros
• eye:
>> Y = eye(3) % Create identity matrix 3X3
• diag:
>> x = diag([1 2 3 4],-1) % diagonal matrix with main diagonal
shift(-1)
MATLAB Special matrices
• magic:
>> Y = magic(3) %magic square matrix
• rand:
>> z = rand(1,4) % generate random numbers
from the period [0,1] in a vector 1x4
• randint:
>> x = randint(2,3, [5,7]) % generate random integer
numbers from (5-7) in a matrix 2x3
MATLAB Operations
• Arithmetic Operators: + - * / ^ ‘
• Relational Operators: < > <= >= == ~=
• Logical Operators: Element wise & | ~
• Logical Operators: Short-circuit && ||
• Colon: (:)
Operation Order :
MATLAB Operations
• Addition and subtraction are element-wise ‛ sizes must match‛:

• All the functions that work on scalars also work on vectors


»t = [1 2 3];
»f = exp(t);
is the same as
»f = [exp(1) exp(2) exp(3)];
MATLAB Operations
• Operators (* / ^) have two modes of operation:
1-element-wise :
• Use the dot: .(.*, ./, .^). ‚BOTH dimensions must match.‛
»a=[1 2 3]; b=[4;2;1];
»a.*b, a./b, a.^b all errors
»a.*b', a./b’, a.^(b’) all valid
MATLAB Operations
• Operators (* / ^) have two modes of operation:
2-standard:
• Standard multiplication (*) is either a dot-product or an outer-
product
• Standard exponentiation (^) can only be done on square
matrices or scalars
• Left and right division (/ ) is same as multiplying by inverse
Vectors & matrix operations
Indexing:
• MATLAB indexing starts with 1, not 0
• a(n) returns the nth element

• The index argument can be a vector.


In this case, each element is looked up individually, and
returned as a vector of the same size as the index vector.
Vectors & matrix operations
Indexing:
• Matrices can be indexed in two ways
using subscripts(row and column)
using linear indices(as if matrix is a vector)

• Picking submatrices:
Vectors & matrix operations
Indexing:
• To select rows or columns of a matrix: Indexing:
Vectors & matrix operations
Indexing:
• To get the minimum value and its index:
»[minVal , minInd] = min(vec);
maxworks the same way
• To find any the indices of specific values or ranges
»ind = find(vec == 9);
»[ind_R,ind_C] = find(vec == 9);
»ind = find(vec > 2 & vec < 6);
Vectors & matrix operations
Deleting Rows & Columns:
>> X =[ 16 3 2 13 ; 5 10 11 8 ; 9 6 7 12 ; 4 15 14 1 ]
>>X(:,2) = [] % delete the second column of X

X=
16 2 13
5 11 8
9 7 12
4 14 1
MATLAB Programming
Relational Operators:
•MATLAB uses mostly standard relational operators
 equal ==
 notequal ~=
 greater than >
 less than <
 greater or equal >=
 less or equal <=
• Logical operators element wise short-circuit (scalars)
And &&
Or ||
Not~
Xor xor
•Boolean values: zero is false, nonzero is true
MATLAB Programming
If / else / elseif :
• Basic flow-control, common to all languages
• MATLAB syntax is somewhat unique

• No need for parentheses : command blocks are between


reserved words
MATLAB Programming
If / else / elseif :
a= input( ‘A‘ )
if rem(a,2) ==0
msgbox(‘a is even’);
end
MATLAB Programming
If / else / elseif :
a= input( ‘A’ )
if rem(a,2) ==0
msgbox(‘a is even’);
else
msgbox(‘a is odd’);
end
MATLAB Programming
If / else / elseif :
if y < 0
M = y + 3;
elseif y > 5
M = y – 3;
else
M = 0;
End
M
MATLAB Programming
Switch case:
A='bye';
switch A
case 'hi’
msgbox('he says hi')
case 'bye‘
msgbox('he says bye')
otherwise
msgbox('nothing')
end
MATLAB Programming
Switch  case:
• SWITCH expression must be a scalar or string constant.

• Unlike the C language switch statement, MATLAB switch does not fall
through.
If the first case statement is case statements do not execute.

• So, break statements are not required.


MATLAB Programming
For Loop :
• For loops : use for a known number of iterations
• MATLAB syntax:

• The loop variable:


o Is defined as a vector
o Is a scalar within the command block
o Does not have to have consecutive values (but it's usually cleaner if they're consecutive)
• The command block:
o Anything between the for line and the end
MATLAB Programming
For Loop :
for n = 1:32
r(n) = n;
end
r
MATLAB Programming
While loop:
• The while is like a more general for loop:
• Don't need to know number of iterations

• The command block will execute while the conditional


expression is true
o Beware of infinite loops!
MATLAB Programming
While loop:
x = 1;
while (x^2<10)
y=x^2;
plot(x,y,’or’); hold on
x = x+1;
end
MATLAB Programming
Continue:
• The continue statement passes control to the next iteration of
the loop
• Skipping any remaining statements in the body of the loop.
• In nested loops, continue passes control to the next iteration
of the loop enclosing it.
MATLAB Programming
Continue:
• The continue statement passes control to the next iteration of
the loop
• Skipping any remaining statements in the body of the loop.
• In nested loops, continue passes control to the next iteration of
the loop enclosing it.
• Example: 
MATLAB Programming
Break:
• The break statement lets you exit early from a for loop or while
loop.
• In nested loops, break exits from the innermost loop only.
• Example:
MATLAB Programming
Error Trapping:

A= input( ‘ Matrix = ‘ )
try
B = inv (A);
Catch
msgbox(‘Matrix is not square’)
end
MATLAB Programming
User-defined Functions:

MATLAB provides three basic types of variables:


Local Variables:
Each MATLAB function has its own local variables.
Global Variables:
If several functions, and possibly the base workspace, all declare a
particular name as global, then they all share a single copy of that variable.
Persistent Variables:
You can declare and use them within M-file functions only. Only the function
in which the variables are declared is allowed access to it.
MATLAB Programming
User-defined Functions:
MATLAB Data Structure
Matrix:

1-One dimension matrix


Only one row or one column (vector)
2-Two dimensions
Has rows and columns
3-three dimension matrix (multidimensional array)
Has rows, columns and pages.
MATLAB Data Structure
Matrix :
Create the 3D matrix
>> M=ones(4,4,4)
MATLAB Data Structure
Matrix :
MATLAB Data Structure
Cell Array:
• Used to store different data type (classes) like vectors,
matrices, strings,<etc in single variable.
MATLAB Data Structure
Cell Array:
Z{2,5} = linspace(0,1,10)
Z{1,3} = randint(5,5,[0 100])
Z{1,3}(4,2) =77
Note:
• The default for cell array elements is empty
• The default for matrix elements is zero
MATLAB Data Structure
Structure Array:

• Variables with named ‚data container‛ called fields.


• The field can contain any kind of data.
• Example:
>> Student.name=‘Ali’;
>> Student.age=20;
>> Student.grade=‘Excellent’;
MATLAB Data Structure
Structure Array:
>> manager = struct ('Name', 'Ahmed', 'ID', 10, 'Salary', 1000)
manager =
Name: 'Ahmed'
ID: 10
Salary: 1000
MATLAB Data Structure
Structure Array:

>> manager(3)=struct ('Name', 'Ali','ID',20, 'Salary',2000)


manager =
1x3 struct array with fields:
Name
ID
Salary
MATLAB Data Structure
Structure Array:

• The need of Structure Array


x.y.z = 3
x.y.w = [ 1 2 3]
x.p = ‘hello’
• Note: x can be array
SymbolicTool Bar
Symbolic Variable:

• syms x t
• x = sin(t)*exp(-0.3*t);

• sym(2)/sym(5)
• ans =
• 2/5

• sym(2)/sym(5) + sym(1)/sym(3)
• ans =
• 11/15
Benefit of MATLAB
• The benefits of MATLAB is that everything is stored in
matrices , make our analysis easy.

• Easy syntax, practically the same as for tan mist MATLAB user
are previous for tan easies.

• MATLAB is widely used tool in electrical engineering


community.

• An arsenal of tool boxes.

You might also like