SlideShare une entreprise Scribd logo
1  sur  109
Télécharger pour lire hors ligne
Mohamed Abd Elhay
Mohamed Abd Elahy
Embedded SW Engineer
Email/ mhmd.a.elhay@gmail.com
o MATLAB Application & usage
o MATLAB Environment
o MATLAB Variables
o MATLAB Operations.
o MATLAB Built-in Fun.
o MATLAB Scripts.
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.
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
The MATLAB Application:
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).
Code Generation
Blocksets
PC-based real-time
systems
StateflowStateflowStateflow
Toolboxes
DAQ cards
Instruments
Databases and files
Financial Datafeeds
Desktop Applications
Automated Reports
StatisticsStatistics 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
Signal Processing
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
Neural Networks
Optimization
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
11/14
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.
vs,vc
t
o .fig
MATLAB Figure
o .m
MATLAB function, script, or class
o .mat
MATLAB binary file for storing variables
o .mex
MATLAB executable (platform specific, e.g. ".mexmac" for the Mac, ".mexglx" for Linux)
Excel / COM
File I/O
C/C++
Java
Perl
ExcelCOM
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.
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.
Variable
browser
Command
window
Command history
MATLAB Disktop
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
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
• 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‛
o MATLAB is a weakly typed language
No need to declear 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.
• Variable can’t have the same name of keyword
oUse ‚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’
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.
Variables
• 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;
1-Scaler:
• 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)
2-Array:
• 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:
• Semicolon separated values between brackets
»column = [4;2;7;4]
• Command window:
• Workspace:
Column vector:
• 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
Vectors:
>> startP= 1;
>> endP= 10;
>> number_of_points= 100;
>> x= linspace (startP, endP, number_of_points)
>> step= 1;
>> x= startP : step : endP;
Vectors:
• Make matrices like vectors
• Element by element
» a= [1 2;3 4];
• By concatenating vectors or matrices (dimension matters)
Matrix:
• 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)
• magic:
>> Y = magic(3) %magic square matrix 3X3
• 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
• Arithmetic Operators: + - * /  ^ ‘
• Relational Operators: < > <= >= == ~=
• Logical Operators: Element wise & | ~
• Logical Operators: Short-circuit && ||
• Colon: (:)
Operation Orders:
Precedence Operation
1 Parentheses, innermost 1st.
2 Exponential, left to right
3 Multiplication and division, left to right
4 Addition and subtraction, left to right
• 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)];
• 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
• 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
o min(x); max(x) % minimum; maximum elements
o sum(x); prod(x) % summation ; multiplication of all elements
o length(x); % return the length of the vector
o size(x) % return no. of row and no. of columns
o anyVector(end) % return the last element in the vector
o find(x==value) % get the indices
o [v,e]=eig(x) % eign vectors and eign values
Exercise:
>>x = [ 16 3 2 13 ; 5 10 11 8 ; 9 6 7 12 ; 4 15 14 1 ]
o fliplr(x) % flip the vector left-right
o Z=X*Y % vectorial multiplication
o y= sin(x).*exp(-0.3*x) % element by element multiplication
o mean %Average or mean value of every column.
o transpose(A) or A’ % matrix Transpose
o sum((sum(A))')
o diag(A) % diagonal of matrix
Exercise:
>>x = [ 16 3 2 13 ; 5 10 11 8 ; 9 6 7 12 ; 4 15 14 1 ]
»sqrt(2)
»log(2), log10(0.23)
»cos(1.2), atan(-.8)
»exp(2+4*i)
»round(1.4), floor(3.3), ceil(4.23)
»angle(i); abs(1+i);
Exercise:
USE The
MATLAB
help
• 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.
Indexing:
• Matrices can be indexed in two ways
using subscripts(row and column)
using linear indices(as if matrix is a vector)
Matrix indexing: subscripts or linearindices
• Picking submatrices:
Indexing:
• To select rows or columns of a matrix:
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);
Indexing:
>> 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
Deleting Rows & Columns:
• Scripts are
o collection of commands executed in sequence
o written in the MATLAB editor
o saved as MATLAB files (.m extension)
• To create an MATLAB file from command-line
»edit helloWorld.m.
• or click
• COMMENT!
o Anything following a % is seen as a comment
o The first contiguous comment becomes the script's help file
o Comment thoroughly to avoid wasting time later
• All variables created and modified in a script exist in the
workspace even after it has stopped running
• Generate random vector to represent the salaries of 10
employees that in range of 700-900 L.E. Then present some
statistic about these employees salaries :
o Max. Salary
o Empl. Max_ID
o Min. Salary
o Empl. Min_ID
• Generate random vector to represent the salaries of 10
employees that in range of 700-900 L.E.
clear;
clc;
close all;
Salaries =randint(1,10,[700,900]);
MaxSalary = max(Salaries); % Max. Salary
EmplMax_ID = find(Salaries==MaxSalary); %Empl. Max_ID
MinSalary = min(Salaries); %Min. Salary
EmplMin_ID = find(Salaries==MinSalary); %Empl. Min_ID
• Any variable defined as string is considered a vector of
characters, dealing with it as same as dealing with vectors.
>> str = ‘hello matlab’;
>> disp(str)
>> msgbox(str)
>> Num = input(‘Enter your number:’)
>> str = input(‘Enter your name:’,’s’)
-----------------------------------------------------------------------------
>> str = ‘7234’
>> Num = str2num(str)
>> number = 55
>> str = num2str(number)
x = linspace(0,2*pi,200);
y = sin(x);
plot(x, y);
0 1 2 3 4 5 6 7 8 9 10
-2
-1.5
-1
-0.5
0
0.5
1
1.5
2
Plot in 2-D:
Plot in 2-D:
• label the axes and add a title:
xlabel('x = 0:2pi')
ylabel('Sine of x')
title('Plot of the Sine Function’,'FontSize',12)
Plot in 2-D:
• Multiple Data Sets in One Graph
x = 0:pi/100:2*pi;
y = sin(x);
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y,x,y2,x,y3)
• legend('sin(x)','sin(x-.25)','sin(x-.5)')
Plot in 2-D:
• Line color
plot(x,y,'color_style_marker')
o Color strings are 'c', 'm', 'y', 'r', 'g', 'b', 'w', 'k'.
o These correspond to cyan, magenta, yellow, red, green, blue,
white, and black.
• Line Style
plot(x,y,'color_style_marker')
• Line Marker
USE MATLAB HELP
Plot in 2-D:
Example:
x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin(x1),'r:',x2,sin(x2),'r+')
Plot in 2-D:
• All Properties Of Plot Command :
plot(x,y,'--rs',<
'LineWidth',2,...
'MarkerEdgeColor','k',...
'MarkerFaceColor','g',...
'MarkerSize',10)
Plot in 2-D:
• Imaginary and Complex Data:
t = 0:pi/10:2*pi;
Z=exp(i*t);
plot(real(z),imag(z))
OR
plot(z)
Exercise:
Plot the vector y with respect the vector x in
the XY plan considering style:
o Dotted line
o diamond marker
o green color
o line width of 3
Plot in 2-D:
• Adding Plots to an Existing Graph:
x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin(x1),'r:‘)
hold on
plot(x2,sin(x2),'r+')
hold off
Plot in 2-D:
• Figure Windows
o figure
o figure(n)
where n is the number in the figure title bar.
• Multiple Plots in One Figure:
x = linspace(0,2*pi,100);
y = sin(x);
y1 = cos(x);
subplot 211
plot(x, y);
subplot 212
plot(x, y1);
• area(x, y); %% think what
happened ??!!!
0 1 2 3 4 5 6 7
-1
-0.5
0
0.5
1
0 1 2 3 4 5 6 7
-1
-0.5
0
0.5
1
Plot on 3D:
t = 0:0.1:2*pi;
x = sin(t);
y = cos(t);
plot3(x,y,t)
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
-1
-0.5
0
0.5
1
0
1
2
3
4
5
6
7
Plot surface in the 3D :
x = linspace(1,10,20);
y = linspace(1,5,10);
[XX,YY] = meshgrid(x,y);
ZZ = sin(XX)./exp(YY);
mesh(ZZ)
0
2
4
6
8
10
12
14
16
18
20
0
2
4
6
8
10
-0.4
-0.3
-0.2
-0.1
0
0.1
0.2
0.3
0.4
Specialized Plotting Functions:
polar : to make polar plots
»polar(0:0.01:2*pi,cos((0:0.01:2*pi)*2))
•bar : to make bar graphs
»bar(1:10,rand(1,10));
•stairs : plot piecewise constant functions
»stairs(1:10,rand(1,10));
•fill : draws and fills a polygon with specified vertices
»fill([0 1 0.5],[0 0 1],'r');
Axes Control:
• For tow-dimensional graphs:
>>axis([xmin xmax ymin ymax])
• For three-dimensional graphs:
>>axis([xmin xmax ymin ymax zmin zmax])
• To reenable MATLAB automatic limit selection:
>>axis auto
• makes the x-axis and y-axis the same length:
>>axis square
Axes Control:
• Makes the axes visible (This is the default):
>>axis on
• Makes the axes invisible:
>>axis off
• Turns the grid lines on:
>>grid on
• Turns them back off again:
>>grid off
Exercise:
Plot the vector y with respect the vector x in
the XY plan considering style:
o Dotted line
o diamond marker
o green color
o line width of 3
Relational Operators:
•MATLAB uses mostlystandard relational operators
 equal ==
 notequal ~=
 greater than >
 less than <
 greater or equal >=
 less or equal <=
•Logical operatorselementwiseshort-circuit (scalars)
And &&
Or ||
Not~
Xor xor
•Boolean values: zero is false, nonzero is true
Relational Operators:
•MATLAB uses mostlystandard relational operators
 equal ==
 notequal ~=
 greater than >
 less than <
 greater or equal >=
 less or equal <=
•Logical operatorselementwiseshort-circuit (scalars)
And &&&
Or |||
Not~
Xor xor
•Boolean values: zero is false, nonzero is true
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
If / else / elseif :
a= input( ‘A‘ )
if rem(a,2) ==0
msgbox(‘a is even’);
end
If / else / elseif :
a= input( ‘A’ )
if rem(a,2) ==0
msgbox(‘a is even’);
else
msgbox(‘a is odd’);
end
If / else / elseif :
if y < 0
M = y + 3;
elseif y > 5
M = y – 3;
else
M = 0;
End
M
Switch case:
A='bye';
switch A
case 'hi'
msgbox('he says hi')
case 'bye'
msgbox('he says bye')
otherwise
msgbox('nothing')
end
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.
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
For Loop :
for n = 1:32
r(n) = n;
end
r
• Nested For Loop
for m = 1: 5
for n = 1: 7
A(m,n) = 1/(m+n-1);
end
end
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!
While loop:
x = 1;
while (x^2<10)
y=x^2;
plot(x,y,’or’); hold on
x = x+1;
end
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.
x=1;
for m=1:5
if (m==3)
continue;
end
x=m+x;
end
x
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: x=1;
for m=1:5
if (m==3)
continue;
end
x=m+x;
end
x
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:
x=1;
for m=1:5
if (m==3)
break;
end
x=m+x;
end
x
Error Trapping:
A= input( ‘ Matrix = ‘ )
try
B = inv (A);
catch
msgbox(‘Matrix is not square’)
end
User-defined Functions:
Functions look exactly like scripts, but for ONE difference
Functions must have a function declaration.
No need for return :
MATLAB 'returns' the variables whose names match those in the
function declaration.
User-defined Functions:
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.
User-defined Functions:
%this fun. To sum 2 no’s.
function x=SUM2(a,b)
global z
x=a+b+z;
end
%this fun. To sum 2 no’s.
function x=SUM2(a,b)
x=a+b;
end
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.
Matrix :
Create the 3D matrix
>> M=ones(4,4,4)
Matrix :
Cell Array:
• Used to store different data type (classes) like vectors, matrices,
strings,<etc in single variable.
• Variables declaration:
>> X=3
>> Y=[1 2 3;4 5 6]
>> Z(2,5)=15
>> A(4,6)=[3 4 5] %…..(wrong)
• cell array:
>> C{1}=[2 3 5 10 20]
>> C{2}=‘hello’
>> C{3}=eye(3)
1 0 0
0 1 0
0 0 1
C
2 3 5 10 20 h e l l o
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
77
Z
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’;
Student
age
name grade
Structure Array:
>> manager = struct ('Name', 'Ahmed', 'ID', 10, 'Salary', 1000)
manager =
Name: 'Ahmed'
ID: 10
Salary: 1000
Structure Array:
>> manager(3)=struct ('Name', 'Ali','ID',20, 'Salary',2000)
manager =
1x3 struct array with fields:
Name
ID
Salary
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
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
findsym :
>> syms a b n t x z
>> f = x^n; g = sin(a*t + b);
>> findsym(f)
• ans =n, x
>> findsym(g)
• ans =a, b, t
subs :
>> f = 2*x^2 - 3*x + 1
>> subs(f,2)
ans =3
>> syms x y
>> f = x^2*y + 5*x*sqrt(y)
>> subs(f, x, 3)
ans = 9*y+15*y^(1/2)
>> subs(f, y, 3)
ans = 3*x^2+5*x*3^(1/2)
Symbolic Matrix:
>> syms a b c
>> A = [a b c; b c a; c a b]
A =[ a, b, c ]
[ b, c, a ]
[ c, a, b ]
>> sum(A(1,:))
ans = a+b+c
>> sum(A(1,:)) == sum(A(:,2)) % This is a logical test.
ans =1
Simple:
• Simplify the expression.
>> syms x
>> m = sin(x)/cos(x)
>> simple(m)
• Show expression in a user friendly format
>> m = sin(x)/cos(x)
>> pretty(m)
Pretty:
Symbolic Plots:
• ezplot(...)
• Symbolic expression plot in the 2D
>> y = sin(x)*exp(-0.3*x)
>> ezplot(y,0,10)
• ezmesh(..)
• Symbolic expression plot in the 3D
>> z = sin(a)*exp(-0.3*a)/(cos(b)+2)
>> ezmesh(z,[0 10 0 10])
Limit:
>> syms h n x
>> limit( (cos(x+h) - cos(x))/h,h,0 )
Differentiation diff :
• Numerical Difference or Symbolic Differentiation
>> z = [1, 3, 5, 7, 9, 11];
>> dz = diff(z)
>> Syms x t
>> x=t^4;
>> xd3 = diff(x,3)
Differentiation diff(…) :
>> syms s t
>> f = sin(s*t)
>> diff(f,t)
ans = cos(s*t)*s
>> diff(f,t,2)
ans =-sin(s*t)*s^2
>> diff(y)./diff(x)
Integration int(…)
• Symbolic integration
>> int(y)
• Integration from 0 to 1
>> int(x,0,1)
• Integration from 0 to 2
>> int(x,0,2)
solve equation solve(...):
>> syms x y real
>> eq1 = x+y-5
>> eq2 = x*y-6
>> [xa, ya] = solve(eq1, eq2)
OR
>> answer = solve(eq1, eq2)
answer.x
answer.y
>> syms x y real
>> s = solve('x+y=9','x*y=20')
Differential Equations dsolve(..):
• Symbolic solution of ordinary differential equations
>> syms x real
>> diff_eq_sol = dsolve('m*D2x+b*Dx+k*x=0','Dx(0)=-1','x(0)=2')
>> syms m b k real
>> subs(diff_eq_sol, [m,b,k], [2,5,100])
• www.mathworks.com/
• ITI MATLAB Course
• MIT : Introduction to MATLAB
MATLAB Programming

Contenu connexe

Tendances

Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
Santosh V
 
Matlab practical and lab session
Matlab practical and lab sessionMatlab practical and lab session
Matlab practical and lab session
Dr. Krishna Mohbey
 
Introduction to simulink (1)
Introduction to simulink (1)Introduction to simulink (1)
Introduction to simulink (1)
Memo Love
 
Basics of matlab
Basics of matlabBasics of matlab
Basics of matlab
Anil Maurya
 

Tendances (20)

Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
 
Introduction to matlab lecture 1 of 4
Introduction to matlab lecture 1 of 4Introduction to matlab lecture 1 of 4
Introduction to matlab lecture 1 of 4
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Matlab (Presentation on MATLAB)
Matlab (Presentation on MATLAB)Matlab (Presentation on MATLAB)
Matlab (Presentation on MATLAB)
 
Learn Matlab
Learn MatlabLearn Matlab
Learn Matlab
 
Seminar on MATLAB
Seminar on MATLABSeminar on MATLAB
Seminar on MATLAB
 
Matlab m files and scripts
Matlab m files and scriptsMatlab m files and scripts
Matlab m files and scripts
 
Matlab practical and lab session
Matlab practical and lab sessionMatlab practical and lab session
Matlab practical and lab session
 
Introduction to simulink (1)
Introduction to simulink (1)Introduction to simulink (1)
Introduction to simulink (1)
 
Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to Matlab
 
Brief Introduction to Matlab
Brief  Introduction to MatlabBrief  Introduction to Matlab
Brief Introduction to Matlab
 
What is matlab
What is matlabWhat is matlab
What is matlab
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
 
Basics of matlab
Basics of matlabBasics of matlab
Basics of matlab
 
Matlab ploting
Matlab plotingMatlab ploting
Matlab ploting
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab Functions
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
 
Importance of matlab
Importance of matlabImportance of matlab
Importance of matlab
 

En vedette

Basics of programming in matlab
Basics of programming in matlabBasics of programming in matlab
Basics of programming in matlab
AKANKSHA GUPTA
 
Matlab programming project
Matlab programming projectMatlab programming project
Matlab programming project
Assignmentpedia
 
ประวัติส่วนตัว
ประวัติส่วนตัวประวัติส่วนตัว
ประวัติส่วนตัว
Lynnie1177
 
สังคม
สังคมสังคม
สังคม
Lynnie1177
 
Sp soft profile (15-may-2012)
Sp soft profile (15-may-2012)Sp soft profile (15-may-2012)
Sp soft profile (15-may-2012)
SP SOFTWARE
 
อังกฤษ
อังกฤษอังกฤษ
อังกฤษ
Lynnie1177
 
Fractales (1)
Fractales (1)Fractales (1)
Fractales (1)
cheliitaa
 
แบบโครงร่างโครงงานคอมพิวเตอร์
แบบโครงร่างโครงงานคอมพิวเตอร์แบบโครงร่างโครงงานคอมพิวเตอร์
แบบโครงร่างโครงงานคอมพิวเตอร์
Lynnie1177
 

En vedette (20)

Matlab for diploma students(1)
Matlab for diploma students(1)Matlab for diploma students(1)
Matlab for diploma students(1)
 
Matlab: Programming Environment
Matlab: Programming EnvironmentMatlab: Programming Environment
Matlab: Programming Environment
 
Matlab Programming Tips Part 1
Matlab Programming Tips Part 1Matlab Programming Tips Part 1
Matlab Programming Tips Part 1
 
Matlab Programming Assignment help , Matlab Programming Online tutors
Matlab Programming Assignment help , Matlab Programming Online tutorsMatlab Programming Assignment help , Matlab Programming Online tutors
Matlab Programming Assignment help , Matlab Programming Online tutors
 
2015 年逢甲大學資訊系:ASP.NET MVC 4 教育訓練1
2015 年逢甲大學資訊系:ASP.NET MVC 4 教育訓練12015 年逢甲大學資訊系:ASP.NET MVC 4 教育訓練1
2015 年逢甲大學資訊系:ASP.NET MVC 4 教育訓練1
 
Basics of programming in matlab
Basics of programming in matlabBasics of programming in matlab
Basics of programming in matlab
 
Matlab
MatlabMatlab
Matlab
 
Matlab programming project
Matlab programming projectMatlab programming project
Matlab programming project
 
Office 2010 migration
Office 2010 migrationOffice 2010 migration
Office 2010 migration
 
Montras com livros 2015
Montras com livros 2015Montras com livros 2015
Montras com livros 2015
 
Mô tả dự án
Mô tả dự ánMô tả dự án
Mô tả dự án
 
ประวัติส่วนตัว
ประวัติส่วนตัวประวัติส่วนตัว
ประวัติส่วนตัว
 
Unlocking funding opportunities final
Unlocking funding opportunities finalUnlocking funding opportunities final
Unlocking funding opportunities final
 
สังคม
สังคมสังคม
สังคม
 
Sp soft profile (15-may-2012)
Sp soft profile (15-may-2012)Sp soft profile (15-may-2012)
Sp soft profile (15-may-2012)
 
Mô tả dự án
Mô tả dự ánMô tả dự án
Mô tả dự án
 
อังกฤษ
อังกฤษอังกฤษ
อังกฤษ
 
Fractales (1)
Fractales (1)Fractales (1)
Fractales (1)
 
Pr i ncess!!!
Pr i ncess!!!Pr i ncess!!!
Pr i ncess!!!
 
แบบโครงร่างโครงงานคอมพิวเตอร์
แบบโครงร่างโครงงานคอมพิวเตอร์แบบโครงร่างโครงงานคอมพิวเตอร์
แบบโครงร่างโครงงานคอมพิวเตอร์
 

Similaire à MATLAB Programming

Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
Kurmendra Singh
 

Similaire à MATLAB Programming (20)

Matlab workshop
Matlab workshopMatlab workshop
Matlab workshop
 
Mat lab workshop
Mat lab workshopMat lab workshop
Mat lab workshop
 
Introduction to Matlab.ppt
Introduction to Matlab.pptIntroduction to Matlab.ppt
Introduction to Matlab.ppt
 
Matlab lec1
Matlab lec1Matlab lec1
Matlab lec1
 
MatlabIntro (1).ppt
MatlabIntro (1).pptMatlabIntro (1).ppt
MatlabIntro (1).ppt
 
Matlab Tutorial.ppt
Matlab Tutorial.pptMatlab Tutorial.ppt
Matlab Tutorial.ppt
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
matlab_tutorial.ppt
matlab_tutorial.pptmatlab_tutorial.ppt
matlab_tutorial.ppt
 
matlab_tutorial.ppt
matlab_tutorial.pptmatlab_tutorial.ppt
matlab_tutorial.ppt
 
matlab_tutorial.ppt
matlab_tutorial.pptmatlab_tutorial.ppt
matlab_tutorial.ppt
 
Matlab1
Matlab1Matlab1
Matlab1
 
From zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyondFrom zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyond
 
A complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projectsA complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projects
 
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulinkMATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
MATLAB for Technical Computing
MATLAB for Technical ComputingMATLAB for Technical Computing
MATLAB for Technical Computing
 
Introduction to Matlab - Basic Functions
Introduction to Matlab - Basic FunctionsIntroduction to Matlab - Basic Functions
Introduction to Matlab - Basic Functions
 
Summer training matlab
Summer training matlab Summer training matlab
Summer training matlab
 
Matlab-1.pptx
Matlab-1.pptxMatlab-1.pptx
Matlab-1.pptx
 

Plus de محمدعبد الحى (15)

Iso26262 component reuse_webinar
Iso26262 component reuse_webinarIso26262 component reuse_webinar
Iso26262 component reuse_webinar
 
Interfacing using ِAtmega16/32
Interfacing using ِAtmega16/32 Interfacing using ِAtmega16/32
Interfacing using ِAtmega16/32
 
Can bus
Can busCan bus
Can bus
 
Lin bus
Lin busLin bus
Lin bus
 
Embedded Systems in Automotive
Embedded Systems in Automotive Embedded Systems in Automotive
Embedded Systems in Automotive
 
CPU Architecture
CPU ArchitectureCPU Architecture
CPU Architecture
 
8 bit microcontroller
8 bit microcontroller8 bit microcontroller
8 bit microcontroller
 
Timers
TimersTimers
Timers
 
Interrupts
InterruptsInterrupts
Interrupts
 
Uart
UartUart
Uart
 
Sw testing
Sw testingSw testing
Sw testing
 
Rtos
RtosRtos
Rtos
 
Dio
DioDio
Dio
 
Micro controller
Micro controllerMicro controller
Micro controller
 
Day1
Day1Day1
Day1
 

Dernier

%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Dernier (20)

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

MATLAB Programming

  • 2. Mohamed Abd Elahy Embedded SW Engineer Email/ mhmd.a.elhay@gmail.com
  • 3.
  • 4. o MATLAB Application & usage o MATLAB Environment o MATLAB Variables o MATLAB Operations. o MATLAB Built-in Fun. o MATLAB Scripts.
  • 5. 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.
  • 6. 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 The MATLAB Application:
  • 7. 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). Code Generation Blocksets PC-based real-time systems StateflowStateflowStateflow Toolboxes DAQ cards Instruments Databases and files Financial Datafeeds Desktop Applications Automated Reports
  • 8. StatisticsStatistics 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 Signal Processing
  • 9. 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 Neural Networks Optimization
  • 10. 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
  • 11. 11/14 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. vs,vc t
  • 12. o .fig MATLAB Figure o .m MATLAB function, script, or class o .mat MATLAB binary file for storing variables o .mex MATLAB executable (platform specific, e.g. ".mexmac" for the Mac, ".mexglx" for Linux)
  • 13. Excel / COM File I/O C/C++ Java Perl
  • 15. 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.
  • 16. 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.
  • 18. 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
  • 19. 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
  • 20. • 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‛
  • 21. o MATLAB is a weakly typed language No need to declear 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.
  • 22. • Variable can’t have the same name of keyword oUse ‚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’ Variables
  • 23. • 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. Variables
  • 24. • 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; 1-Scaler:
  • 25. • 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) 2-Array:
  • 26. • 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:
  • 27. • Semicolon separated values between brackets »column = [4;2;7;4] • Command window: • Workspace: Column vector:
  • 28. • 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 Vectors:
  • 29. >> startP= 1; >> endP= 10; >> number_of_points= 100; >> x= linspace (startP, endP, number_of_points) >> step= 1; >> x= startP : step : endP; Vectors:
  • 30. • Make matrices like vectors • Element by element » a= [1 2;3 4]; • By concatenating vectors or matrices (dimension matters) Matrix:
  • 31. • 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)
  • 32. • magic: >> Y = magic(3) %magic square matrix 3X3 • 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
  • 33. • Arithmetic Operators: + - * / ^ ‘ • Relational Operators: < > <= >= == ~= • Logical Operators: Element wise & | ~ • Logical Operators: Short-circuit && || • Colon: (:) Operation Orders: Precedence Operation 1 Parentheses, innermost 1st. 2 Exponential, left to right 3 Multiplication and division, left to right 4 Addition and subtraction, left to right
  • 34. • 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)];
  • 35. • 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
  • 36. • 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
  • 37. o min(x); max(x) % minimum; maximum elements o sum(x); prod(x) % summation ; multiplication of all elements o length(x); % return the length of the vector o size(x) % return no. of row and no. of columns o anyVector(end) % return the last element in the vector o find(x==value) % get the indices o [v,e]=eig(x) % eign vectors and eign values Exercise: >>x = [ 16 3 2 13 ; 5 10 11 8 ; 9 6 7 12 ; 4 15 14 1 ]
  • 38. o fliplr(x) % flip the vector left-right o Z=X*Y % vectorial multiplication o y= sin(x).*exp(-0.3*x) % element by element multiplication o mean %Average or mean value of every column. o transpose(A) or A’ % matrix Transpose o sum((sum(A))') o diag(A) % diagonal of matrix Exercise: >>x = [ 16 3 2 13 ; 5 10 11 8 ; 9 6 7 12 ; 4 15 14 1 ]
  • 39. »sqrt(2) »log(2), log10(0.23) »cos(1.2), atan(-.8) »exp(2+4*i) »round(1.4), floor(3.3), ceil(4.23) »angle(i); abs(1+i); Exercise: USE The MATLAB help
  • 40. • 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. Indexing:
  • 41. • Matrices can be indexed in two ways using subscripts(row and column) using linear indices(as if matrix is a vector) Matrix indexing: subscripts or linearindices • Picking submatrices: Indexing:
  • 42. • To select rows or columns of a matrix: Indexing:
  • 43. • 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); Indexing:
  • 44. >> 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 Deleting Rows & Columns:
  • 45. • Scripts are o collection of commands executed in sequence o written in the MATLAB editor o saved as MATLAB files (.m extension) • To create an MATLAB file from command-line »edit helloWorld.m. • or click
  • 46.
  • 47. • COMMENT! o Anything following a % is seen as a comment o The first contiguous comment becomes the script's help file o Comment thoroughly to avoid wasting time later • All variables created and modified in a script exist in the workspace even after it has stopped running
  • 48. • Generate random vector to represent the salaries of 10 employees that in range of 700-900 L.E. Then present some statistic about these employees salaries : o Max. Salary o Empl. Max_ID o Min. Salary o Empl. Min_ID
  • 49. • Generate random vector to represent the salaries of 10 employees that in range of 700-900 L.E. clear; clc; close all; Salaries =randint(1,10,[700,900]); MaxSalary = max(Salaries); % Max. Salary EmplMax_ID = find(Salaries==MaxSalary); %Empl. Max_ID MinSalary = min(Salaries); %Min. Salary EmplMin_ID = find(Salaries==MinSalary); %Empl. Min_ID
  • 50. • Any variable defined as string is considered a vector of characters, dealing with it as same as dealing with vectors. >> str = ‘hello matlab’; >> disp(str) >> msgbox(str) >> Num = input(‘Enter your number:’) >> str = input(‘Enter your name:’,’s’) ----------------------------------------------------------------------------- >> str = ‘7234’ >> Num = str2num(str) >> number = 55 >> str = num2str(number)
  • 51. x = linspace(0,2*pi,200); y = sin(x); plot(x, y); 0 1 2 3 4 5 6 7 8 9 10 -2 -1.5 -1 -0.5 0 0.5 1 1.5 2 Plot in 2-D:
  • 52. Plot in 2-D: • label the axes and add a title: xlabel('x = 0:2pi') ylabel('Sine of x') title('Plot of the Sine Function’,'FontSize',12)
  • 53. Plot in 2-D: • Multiple Data Sets in One Graph x = 0:pi/100:2*pi; y = sin(x); y2 = sin(x-.25); y3 = sin(x-.5); plot(x,y,x,y2,x,y3) • legend('sin(x)','sin(x-.25)','sin(x-.5)')
  • 54. Plot in 2-D: • Line color plot(x,y,'color_style_marker') o Color strings are 'c', 'm', 'y', 'r', 'g', 'b', 'w', 'k'. o These correspond to cyan, magenta, yellow, red, green, blue, white, and black. • Line Style plot(x,y,'color_style_marker') • Line Marker USE MATLAB HELP
  • 55. Plot in 2-D: Example: x1 = 0:pi/100:2*pi; x2 = 0:pi/10:2*pi; plot(x1,sin(x1),'r:',x2,sin(x2),'r+')
  • 56. Plot in 2-D: • All Properties Of Plot Command : plot(x,y,'--rs',< 'LineWidth',2,... 'MarkerEdgeColor','k',... 'MarkerFaceColor','g',... 'MarkerSize',10)
  • 57. Plot in 2-D: • Imaginary and Complex Data: t = 0:pi/10:2*pi; Z=exp(i*t); plot(real(z),imag(z)) OR plot(z)
  • 58. Exercise: Plot the vector y with respect the vector x in the XY plan considering style: o Dotted line o diamond marker o green color o line width of 3
  • 59. Plot in 2-D: • Adding Plots to an Existing Graph: x1 = 0:pi/100:2*pi; x2 = 0:pi/10:2*pi; plot(x1,sin(x1),'r:‘) hold on plot(x2,sin(x2),'r+') hold off
  • 60. Plot in 2-D: • Figure Windows o figure o figure(n) where n is the number in the figure title bar. • Multiple Plots in One Figure: x = linspace(0,2*pi,100); y = sin(x); y1 = cos(x); subplot 211 plot(x, y); subplot 212 plot(x, y1); • area(x, y); %% think what happened ??!!! 0 1 2 3 4 5 6 7 -1 -0.5 0 0.5 1 0 1 2 3 4 5 6 7 -1 -0.5 0 0.5 1
  • 61. Plot on 3D: t = 0:0.1:2*pi; x = sin(t); y = cos(t); plot3(x,y,t) -1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1 -1 -0.5 0 0.5 1 0 1 2 3 4 5 6 7
  • 62. Plot surface in the 3D : x = linspace(1,10,20); y = linspace(1,5,10); [XX,YY] = meshgrid(x,y); ZZ = sin(XX)./exp(YY); mesh(ZZ) 0 2 4 6 8 10 12 14 16 18 20 0 2 4 6 8 10 -0.4 -0.3 -0.2 -0.1 0 0.1 0.2 0.3 0.4
  • 63. Specialized Plotting Functions: polar : to make polar plots »polar(0:0.01:2*pi,cos((0:0.01:2*pi)*2)) •bar : to make bar graphs »bar(1:10,rand(1,10)); •stairs : plot piecewise constant functions »stairs(1:10,rand(1,10)); •fill : draws and fills a polygon with specified vertices »fill([0 1 0.5],[0 0 1],'r');
  • 64. Axes Control: • For tow-dimensional graphs: >>axis([xmin xmax ymin ymax]) • For three-dimensional graphs: >>axis([xmin xmax ymin ymax zmin zmax]) • To reenable MATLAB automatic limit selection: >>axis auto • makes the x-axis and y-axis the same length: >>axis square
  • 65. Axes Control: • Makes the axes visible (This is the default): >>axis on • Makes the axes invisible: >>axis off • Turns the grid lines on: >>grid on • Turns them back off again: >>grid off
  • 66. Exercise: Plot the vector y with respect the vector x in the XY plan considering style: o Dotted line o diamond marker o green color o line width of 3
  • 67. Relational Operators: •MATLAB uses mostlystandard relational operators  equal ==  notequal ~=  greater than >  less than <  greater or equal >=  less or equal <= •Logical operatorselementwiseshort-circuit (scalars) And && Or || Not~ Xor xor •Boolean values: zero is false, nonzero is true
  • 68. Relational Operators: •MATLAB uses mostlystandard relational operators  equal ==  notequal ~=  greater than >  less than <  greater or equal >=  less or equal <= •Logical operatorselementwiseshort-circuit (scalars) And &&& Or ||| Not~ Xor xor •Boolean values: zero is false, nonzero is true
  • 69. 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
  • 70. If / else / elseif : a= input( ‘A‘ ) if rem(a,2) ==0 msgbox(‘a is even’); end
  • 71. If / else / elseif : a= input( ‘A’ ) if rem(a,2) ==0 msgbox(‘a is even’); else msgbox(‘a is odd’); end
  • 72. If / else / elseif : if y < 0 M = y + 3; elseif y > 5 M = y – 3; else M = 0; End M
  • 73. Switch case: A='bye'; switch A case 'hi' msgbox('he says hi') case 'bye' msgbox('he says bye') otherwise msgbox('nothing') end
  • 74. 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.
  • 75. 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
  • 76. For Loop : for n = 1:32 r(n) = n; end r • Nested For Loop for m = 1: 5 for n = 1: 7 A(m,n) = 1/(m+n-1); end end
  • 77. 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!
  • 78. While loop: x = 1; while (x^2<10) y=x^2; plot(x,y,’or’); hold on x = x+1; end
  • 79. 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. x=1; for m=1:5 if (m==3) continue; end x=m+x; end x
  • 80. 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: x=1; for m=1:5 if (m==3) continue; end x=m+x; end x
  • 81. 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: x=1; for m=1:5 if (m==3) break; end x=m+x; end x
  • 82. Error Trapping: A= input( ‘ Matrix = ‘ ) try B = inv (A); catch msgbox(‘Matrix is not square’) end
  • 83. User-defined Functions: Functions look exactly like scripts, but for ONE difference Functions must have a function declaration. No need for return : MATLAB 'returns' the variables whose names match those in the function declaration.
  • 85. 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.
  • 86. User-defined Functions: %this fun. To sum 2 no’s. function x=SUM2(a,b) global z x=a+b+z; end %this fun. To sum 2 no’s. function x=SUM2(a,b) x=a+b; end
  • 87. 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.
  • 88. Matrix : Create the 3D matrix >> M=ones(4,4,4)
  • 90. Cell Array: • Used to store different data type (classes) like vectors, matrices, strings,<etc in single variable. • Variables declaration: >> X=3 >> Y=[1 2 3;4 5 6] >> Z(2,5)=15 >> A(4,6)=[3 4 5] %…..(wrong) • cell array: >> C{1}=[2 3 5 10 20] >> C{2}=‘hello’ >> C{3}=eye(3) 1 0 0 0 1 0 0 0 1 C 2 3 5 10 20 h e l l o
  • 91. 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 77 Z
  • 92. 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’; Student age name grade
  • 93. Structure Array: >> manager = struct ('Name', 'Ahmed', 'ID', 10, 'Salary', 1000) manager = Name: 'Ahmed' ID: 10 Salary: 1000
  • 94. Structure Array: >> manager(3)=struct ('Name', 'Ali','ID',20, 'Salary',2000) manager = 1x3 struct array with fields: Name ID Salary
  • 95. 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
  • 96. 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
  • 97. findsym : >> syms a b n t x z >> f = x^n; g = sin(a*t + b); >> findsym(f) • ans =n, x >> findsym(g) • ans =a, b, t
  • 98. subs : >> f = 2*x^2 - 3*x + 1 >> subs(f,2) ans =3 >> syms x y >> f = x^2*y + 5*x*sqrt(y) >> subs(f, x, 3) ans = 9*y+15*y^(1/2) >> subs(f, y, 3) ans = 3*x^2+5*x*3^(1/2)
  • 99. Symbolic Matrix: >> syms a b c >> A = [a b c; b c a; c a b] A =[ a, b, c ] [ b, c, a ] [ c, a, b ] >> sum(A(1,:)) ans = a+b+c >> sum(A(1,:)) == sum(A(:,2)) % This is a logical test. ans =1
  • 100. Simple: • Simplify the expression. >> syms x >> m = sin(x)/cos(x) >> simple(m) • Show expression in a user friendly format >> m = sin(x)/cos(x) >> pretty(m) Pretty:
  • 101. Symbolic Plots: • ezplot(...) • Symbolic expression plot in the 2D >> y = sin(x)*exp(-0.3*x) >> ezplot(y,0,10) • ezmesh(..) • Symbolic expression plot in the 3D >> z = sin(a)*exp(-0.3*a)/(cos(b)+2) >> ezmesh(z,[0 10 0 10])
  • 102. Limit: >> syms h n x >> limit( (cos(x+h) - cos(x))/h,h,0 )
  • 103. Differentiation diff : • Numerical Difference or Symbolic Differentiation >> z = [1, 3, 5, 7, 9, 11]; >> dz = diff(z) >> Syms x t >> x=t^4; >> xd3 = diff(x,3)
  • 104. Differentiation diff(…) : >> syms s t >> f = sin(s*t) >> diff(f,t) ans = cos(s*t)*s >> diff(f,t,2) ans =-sin(s*t)*s^2 >> diff(y)./diff(x)
  • 105. Integration int(…) • Symbolic integration >> int(y) • Integration from 0 to 1 >> int(x,0,1) • Integration from 0 to 2 >> int(x,0,2)
  • 106. solve equation solve(...): >> syms x y real >> eq1 = x+y-5 >> eq2 = x*y-6 >> [xa, ya] = solve(eq1, eq2) OR >> answer = solve(eq1, eq2) answer.x answer.y >> syms x y real >> s = solve('x+y=9','x*y=20')
  • 107. Differential Equations dsolve(..): • Symbolic solution of ordinary differential equations >> syms x real >> diff_eq_sol = dsolve('m*D2x+b*Dx+k*x=0','Dx(0)=-1','x(0)=2') >> syms m b k real >> subs(diff_eq_sol, [m,b,k], [2,5,100])
  • 108. • www.mathworks.com/ • ITI MATLAB Course • MIT : Introduction to MATLAB