You are on page 1of 31

INTRODUCTION TO MATLAB

CONTENTS
 What Is MATLAB ?
 The MATLAB Environment
 Some useful MATLAB Commands
 Generation of Vectors and Matrices
 Generation of signals
 Discrete signals
 Continuous signals
 MATLAB Graphics
 2-Dimensional Plots
 3-Dimensional Plots
 ezplots
 Flow Control
 Scripts and Functions
 Symbolic computations
 GUIs
WHAT IS MATLAB ?

 MATLAB = Matrix Laboratory


“MATLAB is a high-level language and interactive
environment that enables you to perform computationally
intensive tasks faster than with traditional programming
languages such as C, C++ and Fortran.

 Starting MATLAB”
On a PC you access it via the Start menu, in Programs under
a folder such as MatlabR12 or Student MATLAB.
Alternatively, you may have an icon set up that enables you
to start MATLAB with a simple double-click.
THE MATLAB ENVIRONMENT
 Workspace
Displays all the defined variables

 Command Window
To execute commands in the
MATLAB environment

 Command History
Displays record of the commands
used
 Current Directory
Displays where the new files are
stored

 File Editor Window


Define your functions
SOME USEFUL MATLAB COMMANDS
 help command  Online help
 lookfor keyword  Lists related commands
 which  Version and location info
 clear  Clears the workspace
 clc  Clears the command window
 close('name')  closes the named window
 close all  closes all the open figure windows
 diary filename  Sends output to file
 diary on/off  Turns diary on/off
 who, whos  Lists content of the workspace
 more on/off  Enables/disables paged output
 Ctrl+c  Aborts operation
 …  Continuation
 %  Comments
 Quit  simplest way to conclude a MATLAB session
What does Matlab code look like?

Remember:
Another simple example:

t = 0:pi/4:2*pi;
EVERYTHING IN MATLAB
y = sin(t); IS A MATRIX !
plot(t,y)

creates 1 x 200 Matrix

Argument and result: 1 x 200 Matrix


MATRICES
 Data in matlab is always held as a matrix. Most are 2-C, in
which individual elements are referenced by row and column.
This is a 2X9 matrix.

1 2 3 4 5 6 7 8 9

1 0 Pi/4 Pi/2 3*pi/4 pi 5*pi 3*pi 7*pi 2*pi


/4 /2 /4

2 0 0.707 1 0.707 0 - -1 - 0
0.70 0.70
7 7

 If this matrix is given the name m, then m(2,4)=0.707.


 Remember row then column
In matlab rows and columns always numbered starting at 1

!
GENERATION OF VECTORS AND MATRICES
 Building Vector with [ ]:
 If you enter A=[1 2 3] in the command window 1 2 3

 A=[1 ;2; 3] 1
2
3

2 7 4
 A = [2 7 4; 3 8 9]
3 8 9
OPERATIONS ON MATRICES
 eye Identity matrix
 linspace Vector with linearly spaced elements
ones Matrix of ones
 rand Uniformly distributed random numbers and
arrays
 randn Normally distributed random numbers and
arrays
 zeros Matrix of zeros
 : (colon) Vector with regularly spaced elements
 X(1,3) Extracting Data form 1 row and 3 column
 w=x(1,1:3) EXTRACTION OF A ROW FROM A MATRIX
 z=x(1:3,2) EXTRACTION OF A COLUMN FROM A MATRIX
 t(2,:)=[] DELETION OF A ROW FROM A MATRIX
 u(:,2)=[] DELETION OF A COULOMN FROM A MATRIX
CONT….
 Cat Concatenate arrays
 diag Create or extract diagonal
 fliplr Flip in left/right direction
 flipud Flip in up/down direction
 repmat Replicate and tile an array
 reshape Change shape
 rot90 Rotate 90◦
 tril Extract lower tridiagonal part
 triu Extract upper tridiagonal part
 det Determinant
 eig Eigenvalues and eigenvectors
 expm Matrix exponential
 inv Matrix inverse
 poly Characteristic polynomial
 rank Number of linearly independent rows or columns
 rcond Condition estimator
 trace Sum of diagonal elements
 {}\ and / Linear equation solution
SPECIAL VARIABLES, CONSTANTS & FUNCTIONS
 i or j √−1
 Inf Infinity
 NaN Not-a-Number
 pi 3.14159 26535 897 …

 calendar Calendar
 clock Wall clock (complete date and time)
 date You’d never guess
 etime Elapsed time
 tic, toc Stopwatch
 weekday Day of the week
Basic Matlab
Functions in Matlab
function [output variables]=function_name (input variables)

Input and output variables, can be of any type.

function [out_1,out_2,out_3] = Function_Dec (in_1,in_2,in_3)

out_1=in_1+in_2+in_3;
out_2=[ 'hello' ; 'world' ];
out_3=[1,2,3,4,5];

return;
ADDING TITLES, AXIS LABELS, AND ANNOTATIONS

t=0:0.1:2*pi;
x=sin(t);
y=cos(t);
plot(t,x,’*’)
text(3.2,0,'Sin wave')
hold on
plot(t,y,’-r’)
text(4,-0.8,'cos wave')
hold off
xlabel('time')
ylabel('amplitude')
title('cos & sine functions')
legend('sine function','cos function')
Symbol Color Symbol Line Style Symbol Marker
k Black − Solid + Plus sign
r Red −− Dashed o Circle
b Blue : Dotted ∗ Asterisk
g Green −. Dash-dot . Point
c Cyan none No line × Cross
m Magenta s Square
y Yellow d Diamond
v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram

plot(t,x,'--rs','LineWidth',2, 'MarkerEdgeColor','k','MarkerFaceColor','g','MarkerSize',10)

title(’The lemniscate xˆ2-yˆ2=(xˆ2+yˆ2)ˆ2’,’FontSize’, 16, ’FontName’, ’Helvetica’,


’FontWeight’, ’bold’)
3-D PLOTS

t = 0:pi/50:10*pi;
plot3(t,exp(-0.02*t).*sin(t), exp(-0.02*t).*cos(t))
xlabel('x-axis'), ylabel('y-axis'), zlabel('z-axis')
CONT….

x=0:0.1:10;
y=0:0.1:10;
z=exp(-(x.^2+y.^2));
plot3(x,y,z,'linewidth',4)
xlabel('x-variable'), ylabel('y-variable'),
zlabel('function f(x,y)')
MESH 3-D MESH SURFACE

[x, y] = meshgrid(-2.1:0.15:2.1, -6:0.15:6);


u = 80 * y.^2 .* exp(-x.^2 - 0.3*y.^2);
mesh(u)
surf(u)

contour(u)
clc
FLOW CONTROL clear all
a = input('Enter first number: ');
b = input('Enter second number: ');
 Conditional statements:
if a < b
The most famous conditional statement in all disp( [ num2str(b) ' is larger.'] );
programming languages is the if-statement, elseif a > b
which usually has the form: disp( [ num2str(a) ' is larger.'] );
If condition else
Actions to be done if true condition disp( 'Numbers are equal.' );
end
elseif another_condition
clc
Actions to be done if true another_condition clear all
Else grade = input('enter the marks'); % example
if grade > 95
Actions to be done if both condition and disp('The grade is A');
another_condition are false elseif grade <= 95 & grade > 86
disp('The grade is B');
end elseif grade <= 86 & grade > 76
disp('The grade is C');
elseif grade <= 76 & grade > 66
disp('The grade is D');
elseif grade <= 66 & grade > 34
disp('The grade is E');
else
disp('Fails');
end
LOOPS

Looping is very famous in all


programming languages. The most clc
common loopsare the for-loops and clear all
the while-loops. Let’s start by the n=input(enter the number);
for-loop: interfact=1;
Initialization for the counter
if n==0|| n==1
interfact=1; % Initialize the loop
For condition_on_counter else
………………. for i=1:n
………………. Actions to be done as interfact=i*interfact; % Update the loop
long as true condition_on_counter end
………………. factn=interfact
end
changing the value of the counter
end
WHILE-LOOP

Initialization for a counter


while condition_on_the_counter a = 1;
………………. while length(a) < 10
a = [0 a] + [a 0]
………………. Actions to be done as long as end
true condition_on_the_counter
<<operations_on_the_counter>>
……………….
end
clc
SWITCH clc
clear all
x = 3.0; % numeric variable
units = input('enter units of number x as string','s'); %
string variable
•SWITCH – Switch among several
cases based on expression switch units
case 'in' % multiple matches
•The general form of SWITCH y = 2.54*x; % converts to centimeters
statement is: disp ([num2str(x) ' ' units ' converted to cm is :'
num2str(y)])
% disp is used to print pretty in the command
SWITCH switch_expr window
CASE case_expr, % in the above a string vector is being printed
statement, …, statement case 'm'
y = x*100; % converts to centimeters
CASE {case_expr1, case_expr2, disp ([num2str(x) ' ' units ' converted to cm is :'
case_expr3, …} num2str(y)])
statement, …, statement case 'mm'
y = x/10;

disp ([num2str(x) ' ' units ' converted to cm is :'
OTHERWISE num2str(y)])
statement, …, statement case 'cm'
END y = x;
disp ([num2str(x) ' ' units ' converted to cm is :'
num2str(y)])
otherwise
disp (['unknown units:' units])
y = nan; % not a number
end
SYMBOLIC EXPRESSIONS
 Symbolic MathToolbox, you can carry out algebraic or symbolic calculations
suchas factoring polynomials or solving algebraic equations. Type help
symbolic to make sure that the Symbolic Math Toolbox is installed on your
system.
 Differentiation: you can use diff to differentiate symbolic expressions .
 To do multiple partials withrespect to mixed variables you must use diff
repeatedly, as in diff(diff(sin(x*y/z), x), y).
 There is one instance where differentiation must be represented by the
letter D. For example, to use the symbolic ODE solver on the differential
equation
 y = dsolve('D2y = -a*y')
 Integration: MATLAB can compute definite and indefinite integrals. Here is
an indefinite integral:
 int (’xˆ2’, ’x’)
 Limits
 You can use limit to compute right- and left-handed limits and limits at
 infinity. For example, here is limx→0sin(x)/x:
 >> syms x; limit(sin(x)/x, x, 0)
CONT..
clc
clear all
syms x y
a=(x - y)*(x - y).^2
b=expand(a)
c=factor(b)
simplify((x.^3 - y.^3)/(x - y))
intg=int(b,x)
difrntn=diff(b,y)
solve(’xˆ2 - 2*x - 4 = 0’)
 Substitution
You can then plug numbers into that function, to make a graph or table of
values for instance. But you can also substitute numerical values directly
into an expression with subs.
GRAPHICS

 Graphing with ezplot


 The simplest way to graph a function of one variable is with ezplot,
which expects a string or a symbolic expression representing the
function to be plotted.
 For example, to graph x2 + x + 1 on the interval −2 to 2 (using the
string form of ezplot)
 ezplot3(’cos(2*pi*t)’, ’sin(2*pi*t)’, ’t’, [-2, 2])
 ezmesh(’xˆ2 - yˆ2’, [-2, 2], [-2, 2])
GUI

 A graphical user interface (GUI) is a system of graphical elements


that allow a user to interact with software using mouse operations.
 get(H)
where H is an object handle, displays all of the property names
associated with the object.
 set(H)
displays all of the possible values that can be taken by every property
associated with the object.
 set(H,’Property ’)
displays all of the possible values for the Property associated with the
object.
 gcf Get Current Figure
 gca Get Current Axes
 gco Get Current Object
 GCBO Get handle to current callback object.
THE 10 STYLES OF MATLAB UICONTROL OBJECTS

 Push Button.
 Toggle Button.
 Check Box.
 Radio Button.
 Editable Text.
 List Box.
 Pop-up Menu.
 Slider.
 Frame.
 Static Text
DISPLAYING DATE AND TIME IN GUI
SIMPLE COS, SIN, EXP PLOTS IN GUI
MY CALUCLATOR

You might also like