You are on page 1of 44

INTRODUCTION TO MATLAB

MATLAB Stands for MATrix LABoratory It is a high- performance numerical computation and visualization software. MATLAB integrates matrix computation, numerical analysis, signal processing, data analysis, and graphics in an easy to use environment where problems and solutions are expressed just as they are written mathematically without traditional programming.

MATLAB also features a family of application specific

solutions called Toolboxes.


Toolboxes are libraries of

MATLAB functions that customize MATLAB for solving particular classes of problems.

Matrices & arrays lie at the heart of MATLAB programming MATLAB offers

i. array data structures ii. Programming features iii. Graphical User Interface (GUI) tools

GUI is a user interface incorporating graphics objects

such as windows, icons, buttons, menus and text.


Selecting or activating these objects in some way usually

causes an action or change to occur.


The most common activation method is to use a mouse

or other pointing device to control the movement of a pointer on the screen and to press a mouse button to signal object selection or some action.

BHAVANI M, ECE DEPT. SCET

BASIC FEATURES: Running MATLAB creates one or more windows on the computer monitor. One such window entitled MATLAB is called the MATLAB desktop. This window is the primary GUI for MATLAB.
Within the MATLAB window, there is another window

called as the COMMAND WINDOW. This is the place where we interact with MATLAB.

BHAVANI M, ECE DEPT. SCET

BHAVANI M, ECE DEPT. SCET

>> _ the cursor blinks to the right of the prompt when

the command window is active. This indicates that MATLAB is waiting to perform a mathematical operation. SIMPLE MATH MATLAB can do basic math >>4+6+2 (enter key) ans = 12 >>4*6+2*3 (enter key) ans= 30 MATLAB calls the result ans. >>a=4 >>a=4
BHAVANI M, ECE DEPT. SCET

>> b=6; semicolon at the end of the statement suppresses the display in the command window. PRECEDENCE: Expressions are evaluated from left to right with the exponentiation operation having the highest precedence, followed by multiplication & division with equal precedence, followed by addition & subtraction having equal precedence. Parentheses can be used to alter this ordering in which case these rules of precedence are applied within each set of parentheses starting with the innermost set & proceeding outward.
BHAVANI M, ECE DEPT. SCET

MATLAB DESKTOP WINDOWS


Window Command Command History Description Issue commands to MATLAB for processing Running history of prior commands issued in command window

Launch Pad
Current Directory Help Workspace Array Editor

Tree layout for access to tools, demos, and documentation


GUI for directory and file manipulation in MATLAB GUI for finding documentation and viewing on-line

GUI for viewing, loading, and saving MATLAB variables GUI for modifying the content of MATLAB variables
BHAVANI M, ECE DEPT. SCET

Editor/Debugger Text editor and debugger for MATLAB text files

BHAVANI M, ECE DEPT. SCET

BHAVANI M, ECE DEPT. SCET

BHAVANI M, ECE DEPT. SCET

BHAVANI M, ECE DEPT. SCET

BHAVANI M, ECE DEPT. SCET

THE MATLAB WORKSPACE Workspace is the place where commands and variables are said to reside. >> who Your variables are: abc who command gives the list only but not their values. to recall commands up arrow recalls the most recent command to the MATLAB prompt. down arrow scrolls forward through commands. right and left arrows moves within the command.

delete, backspace , home & end perform commonly

assigned tasks. Enter key processes the instruction. Esc erases current command at the prompt. VARIABLES: Rules: variable names are case sensitive maximum length is 31 and length beyond 31 is ignored The variable should start with a letter, followed by letters, digits or underscores. Punctuation characters cant be used. Keywords or reserved word lists cant be used.

RESERVED WORD LIST: for end if while return else switch continue function break case otherwise global etc. SPECIAL VARIABLES: ans beep pi eps inf nan i or j nargin nargout realmin realmax bitmax etc. Reserved word list cant be used for variables. Special variables can be used for variable naming. If you want to restore the value, use clear command. Eg. >>pi ans =3.1416

>> pi=1.15 pi=1.15 >> clear pi >> pi ans = 3.1416 Comments, punctuation & aborting execution: ; -- suppresses printing result % -- all text after % is taken as a comment statement , -- displays results -- statement continuation variable names cant be split between 2 lines. Three periods should appear between variable names and math operations. Cntrl+c -- interrupts MATLAB processing
BHAVANI M, ECE DEPT. SCET

COMPLEX NUMBERS MATLAB doesnt need any special handling for complex numbers >>a=1-2j a=1.000-2.000j >>a=1-2i; >> a=sqrt(-2) a=0.0000+1.4142j >>b=real(a); % gives real part of a >>c=imag(a); % gives imaginary part of a >> abs(a) % gives magnitude of a >> angle(a) % gives angle of a in radians MATLAB doesnt perform trigonometric operations using units of degrees.

FLOATING POINT ARITHMETIC


Numerical values in MATLAB are represented in double-

precision arithmetic using a binary (base 2) representation internally.


This representation is the most common representation

used by computers and is a native format for numerical coprocessors.


Because of this representation, not all numbers can be

represented exactly, there are limiting values that can be represented, and there is a recognizable lower limit for addition.

MATHEMATICAL FUNCTIONS: Trigonometric functions sin, cos, tan, sinh, cosh, tanh, asin, acos, atan, atanh
Exponential functions - ^ (power operation), exp, log,

log10,log2,sqrt
Rounding & Remainder functions:

Fix round towards zero Floor round towards negative infinity Ceil round towards positive infinity Round round towards nearest integer Rem returns remainder Sign signum function
BHAVANI M, ECE DEPT. SCET

TRIGONOMETRIC FUNCTIONS
Trigonometric Function acos acosh acot acoth acsc Description Inverse cosine Inverse hyperbolic cosine Inverse cotangent Inverse hyperbolic cotangent Inverse cosecant

acsch
asec asech asin asinh atan atanh cos

Inverse hyperbolic cosecant


Inverse secant Inverse hyperbolic secant Inverse sine Inverse hyperbolic sine Inverse tangent Inverse hyperbolic tangent Cosine
BHAVANI M, ECE DEPT. SCET

cosh cot coth csc csch sec sech sin sinh tan tanh

Hyperbolic cosine Cotangent Hyperbolic cotangent Cosecant Hyperbolic cosecant Secant Hyperbolic secant Sine Hyperbolic sine Tangent Hyperbolic tangent

BHAVANI M, ECE DEPT. SCET

EXPONENTIAL FUNCTIONS
Exponential Description Function ^ Power

exp
log log10 log2

Exponential
Natural logarithm Base 10 logarithm Base 2 logarithm and floating point Number dissection Square root

sqrt

BHAVANI M, ECE DEPT. SCET

COMPLEX FUNCTIONS
Complex Function abs angle conj imag real complex Description

Absolute value or magnitude Phase angle in radians Complex conjugate Imaginary part Real part Form complex number from real and Imaginary parts

BHAVANI M, ECE DEPT. SCET

ROUNDING AND REMAINDER FUNCTIONS


Rounding and Description Remainder functions fix floor ceil round mod rem Round toward zero Round infinity Round infinity Round integer Modulus remainder
BHAVANI M, ECE DEPT. SCET

toward toward toward or

negative positive nearest signed

Remainder after division

M-FILE MATLAB commands can be placed in a simple text file. This file can be opened and the commands can be evaluated exactly as it would be if typed at the MATLAB prompt. These files are called script files or simply M-files.

BHAVANI M, ECE DEPT. SCET

MEMORY MANAGEMENT
MATLAB allocates memory for variables as they are created

and for M-file functions as they are used.


Depending on the computer you are using, it is possible for

MATLAB to run out of memory making it impossible to do any further work.


When variables are eliminated using the clear command,

MATLAB frees up the memory used by the variables cleared.

BHAVANI M, ECE DEPT. SCET

NUMBER DISPLAY FORMATS


When MATLAB displays numerical results, it follows

several rules. By default, if a result is an integer, MATLAB displays it as an integer.

Likewise, when a result is a real number, MATLAB displays

it approximately four digits to the right of the decimal point. If the significant digits in the result are outside this range, MATLAB displays the result in scientific notation similar to scientific calculators.

BHAVANI M, ECE DEPT. SCET

This default behavior can be overridden by specifying a different numerical format within the command window preferences on the preferences menu item in the file menu or by typing the appropriate MATLAB format command at the prompt. With the special variable pi, the numerical display formats produced by different format selections are as follows:

BHAVANI M, ECE DEPT. SCET

MATLAB COMMAND format short format long

pi 3.1416 3.14159265358979

COMMENTS 5 digits 16 digits

format short e
format long e

3.1416e+000

5 digits plus exponent

3.14159265358979e+ 16 digits plus exponent 000

BHAVANI M, ECE DEPT. SCET

ARRAYS & ARRAY OPERATIONS


>> x=[0.1*pi, 0.2*pi, 0.3*pi, . . . . , pi];

>> y=sin(x);
>>x(3)

% gives 3rd element in x >>y(5) % gives 5th element in y >>x(1:5) % gives 1 to 5 elements >>x(5:end) % displays 5th element to the last element >>y(3:-1:1) % displays y(3), y(2) and y(1) >>y(1:1:end) % displays all the elements in order >>x(2:2:7) % displays x(2), x(4) and x(6) >>y([8 2 9 1]) %displays y(8), y(2), y(9) and y(1)
BHAVANI M, ECE DEPT. SCET

ARRAY CONSTRUCTION
>> x=(0:0.1:1)*pi; the colon notation creates an array thar

starts at 0, increments by 0.1 and ends at 1. Each element in this array is then multiplied by pi to create the desired values in x
>>x=linspace(0,pi,11);

% linspace(first_value, last_value,

number of values)
>>logspace(0,2,11);

%logspace(first_exponent,

last_exponent, no. of values)

BHAVANI M, ECE DEPT. SCET

ARRAYORIENTATION Separating elements by spaces or columns specifies elements rows.


>>a=[1 2 3; 4 5 6; 7 8 9]; >>v=1:5

in

different

columns,

whereas

separating

elements by semicolons specifies elements in different

v=1 2 3 4 5 %creates a row vector. >>x=v` % the transpose operation changes the row vector into column vector x=1 2 3 4 BHAVANI M, ECE DEPT. SCET 5

MATLAB also offers a transpose operator with a preceding

dot. In this case, the dot transpose operator is interpreted as the noncomplex conjugate transpose.

When the array is complex, the transpose gives the

complex conjugate transpose.

The dot transpose transposes the array but does not

conjugate it.
BHAVANI M, ECE DEPT. SCET

STANDARD ARRAYS
MATLAB provides functions for creating a number of

standard arrays. These include arrays containing all ones or all zeros, identity matrices, arrays of random numbers, diagonal arrays, and arrays whose elements are a given constant. >>b= ones(3) >> zeros(2,3) b= 1 1 1 ans = 0 0 0 111 000 111 >> size(ans) ans= 2 3 >> eye(4) ans = 1 0 0 010 001 BHAVANI M, ECE DEPT. SCET

>> rand(3) % rand produces uniformly distributed random

arrays whose elements lie between 0 and 1 ans = 0.9051 0.4860 0.4565 0.2311 0.8913 0.0185 0.6068 0.7621 0.8214 >> rand(1,5); >>randn(2,5); % randn produces arrays whose elements are samples from a zero mean, unit variance normal distribution. >>a=1:4; >>b=diag(a) %place elements of a on the main diagonal. ans = 1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4
BHAVANI M, ECE DEPT. SCET

>>b=diag(a,1) %place elements 1 place up from the

diagonal. b = 0 1 0 0 0 0 0 2 0 0 0 0 0 3 0 0 0 0 4 0 0 0 0 0 0 >>c=diag(a,-2) % place elements of a 2 places down from the diagonal c= 0 0 0 0 0 0 1 0 0 0 0 0 0 2 0 0 0 0 0 0 3 0 0 0 0 0 0 4 0 0


BHAVANI M, ECE DEPT. SCET

ARRAY MANIPULATION >>A=[1 2 3; 4 5 6; 7 8 9]; >>A(3,3)=0; % set element in 3rd row , 3rd column to zero >>A(2,6)=1 % set element in 2nd row, 6th column to one. Since there are only three columns in A, this command will add three more columns with zero elements and the 2nd row, 6th column element will be set to zero. A= 1 2 3 0 0 0 4 5 6 0 0 1 7 8 0 0 0 0 >>A(:,4)=4 %set all the elements in fourth column to four A= 1 2 3 4 0 0 4 5 6 4 0 1 7 8 0 4 0 0
BHAVANI M, ECE DEPT. SCET

>>A=[1 2 3; 4 5 6; 7 8 9]; >>B=A(3:-1:1,1:3)

B= 7 8 9 4 5 6 1 2 3 >>B=A(1:2,2:3) B= 2 3 5 6 >>C=A(1:2,2:end)

BHAVANI M, ECE DEPT. SCET

PLOTTING FUNCTIONS
Plot functions: >>x = linspace(0,2*pi,30); >>y=sin(x); >>plot(x,y) %plots y versus x >>xlabel(independent variable); % names the horizontal axis >>ylabel(dependent variable); % names the vertical axis >>title(sine wave); Other functions: >>grid; % adds grid lines to the current plot >>axis on; %turn on all axis labeling, tick marks, and background
BHAVANI M, ECE DEPT. SCET

>>axis off;

%turn off all axis labeling, tick marks and

background >>axis([x1 x2 y1 y2]) % change axis limits >> clf %erases the contents of a figure window without closing it. >>hold on; %adds new plots to an existing plot using the hold command. >>box off % turns off the axes box

LINE STYLES, MARKERS AND COLOURS

b blue, g green, r red, k black, c- cyan, etc. . point, x-cross, + - plus sign, s - square, d-diamond etc. - - solid line, : - dotted line, -. Dash-dot line, -- dashed line
BHAVANI M, ECE DEPT. SCET

MULTIPLE FIGURES
>>figure(n) %creates new figure window and n is the

number of the window. >>close all; %closes all figure windows. SUBPLOTS >>subplot(2,2,1) %pick the upper left of a 2-by-2 grid of subplots >> subplot(2,2,2) %pick the upper right of the 4 subplots >> subplot(2,2,3) %pick the lower left of the 4 subplots >>subplot(2,2,4) %pick the lower right of the 4 subplots >>y=sin(x); z=cos(x); >>plot(x,y,x,z) %uses the same figure window for two plots
BHAVANI M, ECE DEPT. SCET

SUBPLOTS
>> subplot(2,2,1)

%pick the upper left of a 2-by-2 grid of

subplots >> subplot(2,2,2) %pick the upper right of the 4 subplots >> subplot(2,2,3) %pick the lower left of the 4 subplots >> subplot(2,2,4) %pick the lower right of the 4 subplots >>y=sin(x); z=cos(x); >>plot(x,y,x,z) %uses the same figure window for two plots >>legend(sin(x), cos(x)) The legend command creates a legend box on the plot, keying any text you supply to each line in the plot.

BHAVANI M, ECE DEPT. SCET

GETTING HELP
MATLAB offers help option for all MATLAB commands

with detailed examples


>> help command name %gives the syntax and in depth

explanation for the command mentioned.

BHAVANI M, ECE DEPT. SCET

You might also like