You are on page 1of 49

Introduction to Matlab and Simulink

For Engineers
Made by:
Eng. George Iskander Your Feedback is
valuable for me
george.iskander84@gmail.com
Mob: +20 122 750 9507

George Iskander - ITI 1


• MATLAB Fundamentals
• Programming with MATLAB
• Data Type, Plotting & Fitting, MATLAB Enhancement & Anonymous Function
• Simulink
• Introduction to GUI
• Extra :
 Connecting Hardware with Matlab

George Iskander - ITI 2


• Data Types in MATLAB
 Different Data Types
 Structure
 Cell
 Class (self-study)
• Plotting and Fitting
 Plotting 2D and 3D
 Curve Fitting App
 polyfit - polyval – mypolyfit()
• MATLAB Enhancment
 Logical Index
 Preallocation
• Anonymous Functions
George Iskander - ITI 3
Data Structure
• Basic data structure in MATLAB is the Array:
– 1D array = “vector” All elements of the array are
– 2D array = “matrix” of the same data type

• These data elements can be numbers, characters,


logical, structure, cells or objects.  whos()
Data Type

George Iskander - ITI 4


Data Structure
• Default data type is double. This default
can’t be changed. But you can cast
a variable to any other data type.
• Data Type:
– single, uint8, uint16, uint32, uint64
– double, int8, int16, int32, int64
• To cast a variable:
>> a = int64(a)
>> whos a
32 bit (4 Byte)
>> a = cast(a,’int8’)
64 bit (8 Byte)
George Iskander - ITI 5
Data Structure
• class(): is used to let you know the data type of a certain variable
>> typeofa = class(a)  Notice the o/p is a string
int64

• whos(): To display the type of all variables currently in workspace


• To check the data type of a variable
– isa(x, ‘Data Type’)
– Data Type can be : double, single, logical, char, u/int8, u/int16, u/int32, u/int64, cell,
struct.

George Iskander - ITI 6


Data Type Identification

Output is a
logical type

George Iskander - ITI 7


String Data Type
• String data type is a row vector of characters (char data type). We can manipulate
through its element as any vector. The string must be written between single quote.
• Concatenating strings is simple as
entering a row vector
>> lab=[‘My name’ ‘ is Ahmed’]
• To make a column of strings, the size
of all strings should be the same
>> names = [‘Mona’; ‘Dina’]
• To add ‘Mina’ beneath them
>> names(3,:)= ‘Mina’
>> names(end+1,:) = ‘Ahmed’
Subscripted assignment dimension mismatch.

George Iskander - ITI 8


String Data Type
• Char is a numerical data type. It converts the number to a known character. (Conversion
may use the ASCII code)
• fprintf() can directly print the numbers as string using %s
 Check sprintf()
• MATLAB when display a string variable, it doesn’t add single quote. Check the difference
between  >> x = 1 , y=‘1’
• Doing arithmatic operations on
char will convert it to double.

George Iskander - ITI 9


String Data Type

George Iskander - ITI 10


Structure Data Type
• An array must be homogenous. All elements must be of the same data type

• A struct data type is a heterogeneous. It can hold different data type in one variable

Struct Array
Heterogeneous (Different Homogenous (Same Data
Data type) Type)
Contain Fields Contain Elements
Reach fields by names Reach elements by indices

George Iskander - ITI 11


Structure Data Type
• To declare a struct variable with a field:

– Use a dot .
– Use struct()
Struct Name

Dot operator String (char)


Field Name
Numerical (double)

• A field of a struct can be struct with other fields. Struct


Struct
>> Myclass=struct('student',struct('Name','Ahmed','age',20),'number',1)

George Iskander - ITI 12


Structure Data Type

Very dynamic
Can make field
names as a
variable

George Iskander - ITI 13


Array of Structure
• It should obey both array and structure rules. Be heterogeneous and homogenous
– Array of the struct must have the same fields (homogenous)
– The content of the fields along the array can be different types (heterogeneous)
Example:
>> employee.name='George Iskander'
>> employee.age=32
>> employee.address.city='Giza' The structure is
>> employee.address.district='Third District' similar only for the
array but not its field
>> employee.department.name=['Meca';'Auto']
>> employee(2).name = ‘Asmaa’

George Iskander - ITI 14


Useful Hints
• To convert a field in structure array to an array. Put it between two
square brackets.
– Student(1).degree = 100; Student(2).degree = 90; Student(3).degree = 80
– Grades = [Student.degree]= [100 90 80]

• To convert a field in structure array to a cell array. Put it between two


curly brackets.
– Student(1).Name=‘George’; Student(2).Name=‘Mona’; Student(3).Name=‘Mina’;
– Names = {Student.Name}

George Iskander - ITI 15


Useful Hints
• To generate an array of structure using the struct command you need to
send the values of the field in a cell array
>> employee1 =struct('name',{'George','Iskander'},'age',{30,50})
employee =
1×2 struct array with fields:
name
age
>> employee2 =struct('name',{'George','Iskander'},'age',30);
%Both element in the array with hold 30 in the age field
>> employee2 =struct('name',{{'George','Iskander'}},'age',30);
 Check the result

• If you have an array of structure and you want to change the value a certain
field .
>> IDs = {1000, 1001, 1002, 1003};
>> [employee.ID]=IDs{:};
George Iskander - ITI 16
Cell Data Type
• A cell array is used to collect data of different data types.
• Used more than struct data type for collecting different data type
• A cell array can contain cell arrays inside it.
• The cell is a special type of pointers that is known in C/C++.
• Each variable (scalar, vector, array, etc.) is stored in certain place in the
memory with a unique address not continuous.
• A cell is a variable that stores these addresses.
• Mostly used for collecting string sentences.

George Iskander - ITI 17


Cell Data Type
• To declare a cell variable: Numerical (int8)
– A new syntax is introduced { } String (char)
– Use cell(row,col) Struct
Cell Name A function that stores Array (Double)
empty cell () not {}
Double
Array (Double)

George Iskander - ITI 18


Cell Data Type

George Iskander - ITI 19


Cell Data Type
Cell Pointers
Equating cells is copying the Equating pointers copying
content of the cells to the addresses to another
another pointer

Protected pointers to avoid Leave the programmer to


mistake manipulate freely

C Pointers are also


included in MATLAB
Check libpointer
George Iskander - ITI 20
George Iskander - ITI 21
2D – Plot
• plot(x)  x is plotted verses its index
– If x is a matrix, each column will be drawn separately on the same figure
• plot(x,y)  x and y are plotted verse each other (must be equal)
• plot(x,y,specs)  specs is a string that contains specification of the curve
• plot(x1,y1,specs1,x2,y2,specs2,……,xn,yn, specsn)  plot several graphs
on the same figure

George Iskander - ITI 22


2D – Plot - Line Specs

George Iskander - ITI 23


2D – Plot
• Every plot function will call a new figure to plot the graph in it
• hold on  To plot on the same opened figure
• hold off  To plot on a different figure
• figure  to open an new empty figure you can specify its number
• subplot(M,N,P)  divide the figure to MxN axes and P is the number of
the division where the continuing is in the row direction

Try to plot
similar to it
George Iskander - ITI 24
2D – Plot
• legend(‘string1’,string2’,….)
• xlabel(‘A Label for the x-axis’)
• ylabel(‘A Label for the y-axis’)
• title(‘A Title for the plot’)
• axis([xmin xmax ymin ymax])
• text(x, y, ’Your Text’)
• gtext(‘Write a string in a selected place’)
• ginput()  To get a value from the graph
to the workspace
George Iskander - ITI 25
2D – Plot
• Example 1: 1
sin(x)
0.8 sin(x-pi/2)
>> x=0:pi/10:2*pi; sin(x-pi)
0.6
>> y1=sin(x);
0.4
>> y2=sin(x-pi/2);
0.2
>> y3=sin(x-pi);
0
>> plot(x,y1,'--',x,y2,':',x,y3)
-0.2
>> legend('sin(x)','sin(x-pi/2)','sin(x-pi)')
-0.4
 Try to draw same graph using hold on -0.6

-0.8

-1
0 1 2 3 4 5 6 7

George Iskander - ITI 26


2D – Plot
• Example 2: Draw a circle
• function circle(x,y,r)
ang=0:0.01:2*pi;
xp=r*cos(ang);
yp=r*sin(ang);
plot(x+xp,y+yp);
• end
OR
x=[-5:0.01:5];
plot(x,sqrt(25-x.^2),x,-sqrt(25-x.^2))

George Iskander - ITI 27


2D – Plot

• Example 3: Draw unit step using area() :


1 𝑥≥0
𝑢( ) =
0 𝑥<0

• Example 4: Draw ramp using area() :


𝑥 𝑥≥0
𝑟𝑎𝑚𝑝( ) =
0 𝑥<0

George Iskander - ITI 28


• It is required to plot the following graph

George Iskander - ITI 29


• It is required to plot the following graph

George Iskander - ITI 30


3D – Plot
• plot3()  displays a three-dimensional plot of a set of data points.
• plot3(X1,Y1,Z1,...), where X1, Y1, Z1 are vectors or
matrices, plots one or more lines in
three-dimensional space through the points whose coordinates are the elements
5

of X1, Y1, and Z1.


>> t=-5:0.01:5 0

>> x = t+2
>> y = t-2 -5
5

>> plot3(x,y,t) 0
10
5
-5
0
-10 -5

George Iskander - ITI 31


3D – Plot
• mesh()  To draw a plan
Example:
The equation of a plan is : 7x – y + z = 3
>> x= -3:0.01:3;
>> y= -3:0.01:3
>> [X Y] = meshgrid(x,y);
>> Z=3 – 7*X+Y;
>> mesh(X,Y,Z)

X, Y, Z must be matrices

George Iskander - ITI 32


3D – Plot
Example 2:
The equation of a plan is : 7x – y + z = 3
>> x= -2*pi:0.01:2*pi;
>> y= -2*pi:0.01:2*pi;
>> [X Y] = meshgrid(x,y);
>> Z=sin(X);
>> mesh(X,Y,Z)

 Investigate the output of meshgrid

George Iskander - ITI 33


Examples
Interpolation Approximation Function
The interpolated curve should path through all points The approximate curve passes as near as possible to
(data) the given point (data)

Kinds of interpolation Forms of LSA:


• La grange polynomial • Linear form
• Newton polynomial • Quadratic form
• Piecewise Interpolation • Linearized form
• Linear piecewise Interpolation
• Cubic Spline

George Iskander - ITI 34


• Why do we use curve fitting?
1. To get an approximate function for a given points
2. To get additional points
3. Be able to plot a smooth curve for the given data
4. Differentiate & integrate a group of points

• How to choose between interpolation and L.S.A?


1. If an experiment is done, so outputs is not so accurate LSA is preferred
2. By knowing a previous relation between the output and Input
3. By experience where the distribution of the points can help

George Iskander - ITI 35


Least Square Approximation
• How to choose the best curve that path near the given data?
1. Minimize the sum of error
2. Minimize the sum of absolute error
3. Minimize the sum of the square of the error

George Iskander - ITI 36


Curve Fitting Apps

George Iskander - ITI 37


Curve Fitting Function
• Polynomials are introduced in MATLAB by its coefficients
– Example : 2𝑥 3 + 4𝑥 2 + 3 = 0  coef = [ 2 4 0 3 ]

• polyfit (x,y,n)  finds the coefficients of a polynomial F(X) of degree N that


fits the data Y best in a least-squares sense.

• polyval(coef,x)  returns the value of a polynomial F(X) evaluated at X


using the coefficients (coef)

• interp1(X,Y,XX)  X and Y are the points that we need to interpolate more


points XX
George Iskander - ITI 38
myPolyfit()
• Write an M-file that ask the user to select any number of points using
ginput() and then specify the degree of the fitting curve.
• The program will calculate the coefficients based on the required
polynomial degree.

HINT:
y = a x + b for a first order curve can be written as
𝑎
𝑦 = 𝑥 1 ×
𝑏
we need to find the vector of the coefficients
George Iskander - ITI 39
Other Plotting Functions

• semilogx() – semilogy - loglog


• pie(x) – pie3(x)
• hist(x,n) – area(x,y)
• bar() – bar3()

George Iskander - ITI 40


Logical Index
• Given a vector v, create another vector w, that contains only the
non-negative elements of v.

George Iskander - ITI 41


Pre-allocation
• Loops that incrementally increase the size of a data structure each time through the loop
can adversely affect performance and memory use.
• Resizing arrays often requires MATLAB® to spend extra time looking for larger contiguous
blocks of memory, and then moving the array into those blocks.
• Preallocating the maximum amount of space required for the array improves code
execution time
tic tic
x = 0; x = zeros(1, 1000000);
for k = 2:1000000 for k = 2:1000000
x(k) = x(k-1) + 5; x(k) = x(k-1) + 5;
end end
toc toc

Elapsed time is 0.301528 seconds. Elapsed time is 0.011938 seconds.


George Iskander - ITI 42
Pre-allocation
• Use the appropriate preallocation function for the kind of array you want to initialize:
zeros( ) for numeric arrays
cell( ) for character arrays or heterogeneous array
repmat() for general case, it is the fastest in implentation

Preallocating a Non-double Matrix


When you preallocate a block of memory to hold a matrix of some type other than double, avoid
using the method
>> A = int8(zeros(100));

This statement preallocates a 100-by-100 matrix of int8, first by creating a full matrix
of double values, and then by converts each element to int8.
Creating the array as int8 values saves time and memory. For example:
>> A = zeros(100, 'int8');

George Iskander - ITI 43


inline ( )
• inline(expr): constructs an inline function object.
– expr is a string that contains the wanted expression for F(x). The inline function automatically
determines the variables of the function.
Examples
>> g = inline('t^2') If inline does not return the desired
g = Inline function: function variables or not in the required
g(t) = t^2 order, you can specify the desired
variables explicitly
>> f = inline('3*sin(2*x.^2)‘
f = Inline function: >> f = inline('sin(alpha*x)','x','alpha')
f(x) = 3*sin(2*x.^2) f = Inline function:
f(x,alpha) = sin(alpha*x)
>> f = inline('sin(alpha*x)')
f = Inline function:
f(alpha,x) = sin(alpha*x)
Check  argnames(f) and formula(f)
George Iskander - ITI 44
Function Handle
• It is a MATLAB data type that stores an association to a function.
• Useful for:
– Pass a function to another function. (such as integral and fzero).
– Specify callback functions. (specify the function that will respond to a certain event).
– Construct handles to functions defined inline instead of stored in a program file.

• Types of Function Handle:


– Named function handle  >> f = @myrand;
– Anonymous function handle

• Multiple function handles can be stored in a cell array (or structure) as if they are
any other variable.
• To check a variable is a function handle, use >>isa(h,'function_handle')
George Iskander - ITI 45
Anonymous Function
What Are Anonymous Functions?
• An anonymous function is a function that is not stored in a program file, but is associated with a
variable whose data type is function_handle.
• Anonymous functions can accept inputs and return outputs, just as standard functions do.
However, they can contain only a single executable statement.
• The @ operator creates the handle, and the parentheses () immediately after the @ operator
include the variables followed by the equation or single statement
Examples
>> sqr = @(x) x.^2;
>> a = sqr(5)
a = 25
>> q = integral(sqr,0,1); %It can be an input to other MATLAB functions
OR q = integral(@(x) x.^2,0,1);
George Iskander - ITI 46
Anonymous Function
Multiple Anonymous Functions
• The expression in an anonymous function can include another anonymous function.
>> g = @(c) (integral(@(x) (x.^2 + c*x + 1),0,1));
• Step by Step
– @(x) (x.^2 + 2*x + 1)
– integral(@(x) (x.^2 + c*x + 1),0,1) 
– g = @(c) (integral(@(x) (x.^2 + c*x + 1),0,1));
>> g(2)
ans = 2.3333
Functions with No Inputs
• If your function does not require any inputs. You must use empty parentheses . WHY??
>> t = @() datestr(now); d = t()  Check the difference with >> d = t;
d = '18-Dec-2018 05:11:11'
George Iskander - ITI 47
Anonymous Function
• To copy the function handler to another handler omit the parentheses
>> d = t
d = @() datestr(now)
Functions with Multiple Inputs
• myfunction = @(x,y) (x^2 + y^2 + x*y); x = 1; y = 10; z = myfunction(x,y)
z = 111
Functions with Multiple Outputs
You do not explicitly define output arguments when you create an anonymous function. If
the expression in the function returns multiple outputs, then you can request them when
you call the function.
>> mul= @(x,y) size(x*y) ; [row, col] = mul([2;1],[1,2])  Check the result
George Iskander - ITI 48
Anonymous Function
Arrays of Anonymous Functions
>> f = {@(x) (x.^2); @(y) (y + 10); @(x,y) (x.^2 + y + 10)};
>> x = 1;y = 10;
>> f{1}(x), f{2}(y), f{3}(x,y)

>> eq={@sin , @cos, @tan}


>> eq{1}(pi/2), eq{2}(0), floor(eq{3}(pi))

Activity : Modify fzeroX() to accept a function handle as the first input and
the second input be the values of x (range of x).

George Iskander - ITI 49

You might also like