• No results found

Matlab Theory

N/A
N/A
Protected

Academic year: 2021

Share "Matlab Theory"

Copied!
14
0
0

Loading.... (view fulltext now)

Full text

(1)

MATLAB BASICS & PROGRAMMING

MATLAB BASICS & PROGRAMMING

Dr. N. YADAIAH

Dr. N. YADAIAH

Associate professor Associate professor

Dept.

Dept. of Electrical

of Electrical & Electron

& Electronics Engine

ics Engineering

ering

J N T

J N T University, College of Engineering, HYDERA

University, College of Engineering, HYDERABAD

BAD

[email protected]

(2)

MATLAB BASICS

MATLAB BASICS

What Is MATLAB?

What Is MATLAB?

••

MATLAB® is a high-performance language for technical computing. ItMATLAB® is a high-performance language for technical computing. It

integrates computation, visualization, and programming in an easy-to-use integrates computation, visualization, and programming in an easy-to-use environment where problems and solutions are expressed in familiar environment where problems and solutions are expressed in familiar mathematical notation.

mathematical notation.

••

The name The name MATLAMATLAB stands B stands for MATrix LABoratoryfor MATrix LABoratory..

••

Matlab is a case sensitive.Matlab is a case sensitive.

Typical uses include  Typical uses include 

o

o Math and computationMath and computation o

o Algorithm developmentAlgorithm development o

o Data acquisition Modeling, simulation, and prototypingData acquisition Modeling, simulation, and prototyping o

o Data analysis, exploration, and visualizationData analysis, exploration, and visualization o

o Scientific and engineering graphicsScientific and engineering graphics o

o Application development, including graphical user interface buildingApplication development, including graphical user interface building

••

MATLAB is an interactive system whose basic data element is an arrayMATLAB is an interactive system whose basic data element is an array that does not require dimensioning.

that does not require dimensioning.

••

In Academic environment, it is the standard instructional tool forIn Academic environment, it is the standard instructional tool for introductory and advanced courses in mathematics, engineering, introductory and advanced courses in mathematics, engineering, and science.

and science.

••

In Industry, MATLAB is the tool of choice for high-productivityIn Industry, MATLAB is the tool of choice for high-productivity research, development, and analysis.

research, development, and analysis.

••

MATLAMATLAB features a family of add-on B features a family of add-on application-specific solutionsapplication-specific solutions called toolboxes

called toolboxes

..

Very important to most Very important to most users of MATLAB, toolboxesusers of MATLAB, toolboxes allow us to learn and apply specialized technology.

allow us to learn and apply specialized technology.

••

Toolboxes are comprehensive collections of MATLAB functions (M-files)Toolboxes are comprehensive collections of MATLAB functions (M-files) that extend the MATLAB environment to solve particular classes of that extend the MATLAB environment to solve particular classes of problems.

problems.

••

Areas in which toolboxes are available include signal processing, controlAreas in which toolboxes are available include signal processing, control systems, neural networks, fuzzy logic, wavelets, simulation, and many systems, neural networks, fuzzy logic, wavelets, simulation, and many others.

(3)

The MATLAB System

The MATLAB System

The MATLAB system consists of five main parts: The MATLAB system consists of five main parts: Development Environment

Development Environment: : This is the set of tools This is the set of tools and facilities tand facilities that help us hat help us toto use MATLAB functions and files. Many of these tools are graphical user use MATLAB functions and files. Many of these tools are graphical user interfaces. It includes the MATLAB desktop and Command Window, a command interfaces. It includes the MATLAB desktop and Command Window, a command history, an editor and debugger, and browsers for viewing help, the workspace, history, an editor and debugger, and browsers for viewing help, the workspace, files, and the search path.

files, and the search path.

The MATLAB Mathematical Function Library

The MATLAB Mathematical Function Library: : This This is is a a vast vast collection collection ofof computational algorithms ranging from elementary functions like sum, sine, computational algorithms ranging from elementary functions like sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix cosine, and complex arithmetic, to more sophisticated functions like matrix inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms.

inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms. The MATLAB Language

The MATLAB Language: This is a high-level matrix/array language with control: This is a high-level matrix/array language with control flow statements, functions, data structures, input/output, and object-oriented flow statements, functions, data structures, input/output, and object-oriented programming features.

programming features. Graphics:

Graphics: MATLAB has extensive facilities for displaying vectors and matricesMATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as annotating and printing these graphs. It includes high-level as graphs, as well as annotating and printing these graphs. It includes high-level functions for two-dimensional and three-dimensional data visualization, image functions for two-dimensional and three-dimensional data visualization, image processing, animation, and presentation graphics. It also includes low-level processing, animation, and presentation graphics. It also includes low-level functions that allow you to fully customize the appearance of graphics as well as functions that allow you to fully customize the appearance of graphics as well as to build complete graphical user interfaces on your MATLAB applications.

to build complete graphical user interfaces on your MATLAB applications. The MATLAB Application Program Interface (API)

The MATLAB Application Program Interface (API). . This This is is a a library library thatthat allows us to write C and Fortran programs that interact with MATLAB. It includes allows us to write C and Fortran programs that interact with MATLAB. It includes facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a computational engine, and for reading and writing MAT-files.

(4)
(5)

General

General Commands

Commands one

one should

should remember

remember

Help Commands Help Commands help 

help  lists topics on which help is available.lists topics on which help is available. helpwin 

helpwin  opens the interactive help window.opens the interactive help window. helpdesk 

helpdesk  opens the web browser based help facility.opens the web browser based help facility. help 

help topic topic  provides help onprovides help on topic.topic. lookfor 

lookfor string string  lists help topics lists help topics containingcontaining string.string. demo 

demo  runs the demo runs the demo program.program. Info 

Info  Info about MATALBInfo about MATALB ver 

ver  MATLAB version info.MATLAB version info. Start & Exit

Start & Exit matlabrc 

matlabrc  Master startup fileMaster startup file startup 

startup  M-file executed at startupM-file executed at startup quit 

quit  Quit MATLABQuit MATLAB exit 

exit  Same as quit.Same as quit. Variable and Workspace information Variable and Workspace information who 

who  lists variables currently in the workspace.lists variables currently in the workspace. whos 

whos  lists variables currently in the workspace with their size.lists variables currently in the workspace with their size. what 

what  lists m-, mat-, and mex-files on the disk./List files in the directory.lists m-, mat-, and mex-files on the disk./List files in the directory. whatsnew 

whatsnew  Display ReadMe files.Display ReadMe files. which 

which  Locate a fileLocate a file clear 

clear  clears the workspace, all variables are removed.clears the workspace, all variables are removed. clear x y z 

clear x y z  clears only variablesclears only variables x,x, y andy and z.z. clear all 

clear all  clears all variables and functions from workspace.clears all variables and functions from workspace. mlock 

mlock fun fun  locks functionlocks function fun fun so that clear cannot remove it.so that clear cannot remove it. munlock fun 

munlock fun  unlocks functionunlocks function fun fun so that clear can remove it.so that clear can remove it. clc 

clc  clears command window, command history is lost.clears command window, command history is lost. home 

home  same as clc.same as clc. clf 

clf  clears figure window.clears figure window. echo 

echo  Echo commands in script file.Echo commands in script file. load 

load  Load variables from file.Load variables from file. save 

save  Save variables in MAT – file.Save variables in MAT – file. length 

length  Length of a vector.Length of a vector. size 

size  size of a matrix.size of a matrix. pack 

pack  Consolidate memory spaceConsolidate memory space disp 

(6)

Directory information Directory information pwd 

pwd  shows the current working directory.shows the current working directory. cd 

cd  changes the current working directory.changes the current working directory. dir 

dir  lists contents of the current directory.lists contents of the current directory. ls 

ls  lists contents of the current directory, same as air.lists contents of the current directory, same as air. path 

path  gets or sets MATLAB se~rch path.gets or sets MATLAB se~rch path. editpath 

editpath  modifies MATLAB search path.modifies MATLAB search path. copyfile 

copyfile  copies a file.copies a file. mkdir 

mkdir  creates a directory.creates a directory.

↑ ↓

Recall previous commands.Recall previous commands.

delete 

delete  Delete fileDelete file dairy 

dairy  Save text of MATLAB sessionSave text of MATLAB session type 

type  Show contents of fileShow contents of file !

! Access Access operating operating systemsystem General information

General information computer 

computer  tells you the computer type you are usingtells you the computer type you are using clock 

clock  gives you wall clock time and date as a vector.gives you wall clock time and date as a vector. date 

date  tells you the date as a string.tells you the date as a string. more 

more  controls the paged output according to the screen size.controls the paged output according to the screen size. ver 

ver  gives the license and the version information about MATLABgives the license and the version information about MATLAB installed on your computer.

installed on your computer. bench 

bench  benchmarks your computer on running MATLAB.benchmarks your computer on running MATLAB. compared 

compared  to other computers.to other computers. cputime 

cputime  Elapsed CPU time.Elapsed CPU time. etime 

etime  Elapsed time functionElapsed time function tic 

tic  Start stopwatch timerStart stopwatch timer toc 

toc  Read stopwatch timerRead stopwatch timer

Punctuation Marks and Other Symbols Punctuation Marks and Other Symbols , Comma

, Comma: A comma is used to:: A comma is used to:

••

separate variaseparate variables in the input and output bles in the input and output list of a flist of a function,unction, Example: 

Example: [t ,x] = ode23 ( 'pend' ,to ,tf ,x0),[t ,x] = ode23 ( 'pend' ,to ,tf ,x0),

••

separate the row and column indices in a matrix,separate the row and column indices in a matrix,

Example: 

Example: A(m,n), A(m,n), A(l: A(l: 10,3) 10,3) etc.,etc.,

••

separate different commands on the same line.separate different commands on the same line.

Example: 

Example: plot(x, y) , grid, xlabel('x') etc.plot(x, y) , grid, xlabel('x') etc. ; Semicolon

; Semicolon: A semicolon is used to:: A semicolon is used to:

••

suppress the MATLAB' output of a command,suppress the MATLAB' output of a command, Example: x=1:10 ; 

(7)

••

separate rows in the input list of a matrix.separate rows in the input list of a matrix.

Example: 

Example: A= A= [1 [1 2; 2; 4 4 9].9]. : Colon

: Colon: A colon is used to specify range:: A colon is used to specify range:

••

in creating vectors,in creating vectors, Example: 

Example:  x=l: 10; y=.l:2: 100; etc.x=l: 10; y=.l:2: 100; etc.

••

for matrix and vector indices,for matrix and vector indices,

••

in for loops.in for loops.

Example: 

Example: for i=l: 20, x=x+i; end.for i=l: 20, x=x+i; end. ` Right Quote

` Right Quote: A single right quote is used to transpose a vector or a matrix.: A single right quote is used to transpose a vector or a matrix. Example: 

Example: symA = (A' +A) /2.symA = (A' +A) /2. ` ‘ Single Quotes

` ‘ Single Quotes: A pair of single right quote characters is used to enclose a: A pair of single right quote characters is used to enclose a character string.

character string. .Example: 

.Example: xlabel('time'), title('My plot') etc.xlabel('time'), title('My plot') etc. . Period:

. Period: A period is used:A period is used:

••

as a decimal point, i,as a decimal point, i,

••

in array operations.in array operations.

Example: 

Example: Asq = A.^ 2Asq = A.^ 2 . . Two periods

. . Two periods: : Two Two periods are periods are used in used in cd cd . . . . command to command to access parentaccess parent directory.

directory. ... Ellipsis:

... Ellipsis: Ellipsis (three periods) at the end of aEllipsis (three periods) at the end of a command denotes continuation command denotes continuation  to the next line.

to the next line. Exampte: 

Exampte: x x = = [log(1:100) sin(v+a.*[log(1:100) sin(v+a.*b) 22.3 b) 22.3 23.0 23.0 . . . . .. 34.0

34.0 33.0 33.0 40:50 40:50 80];80]; ! Exclamation

! Exclamation: An exclamation preceding a: An exclamation preceding a command command is used to send the is used to send the locallocal operating system command

operating system command command command to the system.to the system. This command is not applicable to Macs.

This command is not applicable to Macs. Example: 

Example: ! emacs newfile .m invokes the local emacs editor.! emacs newfile .m invokes the local emacs editor. % Percent

% Percent: A percent character is used to:: A percent character is used to:

••

used to mark the beginning of a used to mark the beginning of a comment, except when used incomment, except when used in

character strings. character strings. Example: % 

(8)

••

.to denote formats in standard I/O functions sprintf and fprintf..to denote formats in standard I/O functions sprintf and fprintf.

Example: 

Example: sprintf('R = %6.4f', r).sprintf('R = %6.4f', r). ( ) Parentheses

( ) Parentheses: Parentheses are used to:: Parentheses are used to:

••

.specify precedence in arithmetic operations,.specify precedence in arithmetic operations, Example: 

Example: a = 5/ (2+x* (3-i)); etc.a = 5/ (2+x* (3-i)); etc.

••

.enclose matrix and vector indices,.enclose matrix and vector indices,

Example: 

Example: A(1:5, 2) = 5; v = x(1: n-5); etc.A(1:5, 2) = 5; v = x(1: n-5); etc.

••

enclose the list of input variables of a fenclose the list of input variables of a function.unction. Example: 

Example: [t,x]=ode2[t,x]=ode23('pend', to, tf, 3('pend', to, tf, x0). .,x0). ., [ ] Square brackets

[ ] Square brackets: Square brackets are used to:: Square brackets are used to:

••

form and concatenate vectors and matrices,form and concatenate vectors and matrices, Example: 

Example: v v = = [1 [1 2 2 3:9]; X 3:9]; X = = [v; log(v)]; [v; log(v)]; etc.etc.

••

enclose the list of output variables of a function.enclose the list of output variables of a function. Example: 

Example: [V,D] = eig(A); etc.[V,D] = eig(A); etc. Special Variables and Constants Special Variables and Constants Constants

Constants pi

pi

π

π

(= 3.14159...)(= 3.14159...) inf

inf

(infinity)(infinity) NaN 

NaN  Not-a-NumberNot-a-Number i, j 

i, j  Imaginary unit (Imaginary unit (

11)) eps 

eps  Machine precision.Machine precision. realmax 

realmax  Largest real number.Largest real number. realmin 

realmin  Smallest real number.Smallest real number. Variables

Variables ans 

ans  Default output variable.Default output variable. nargin 

nargin  Number of input arguments.Number of input arguments. nargout 

(9)

Working with Files and Directories

Working with Files and Directories

MATLAB WINDOWS: MATLAB WINDOWS:

Once the program starts, the window that opens, shown below, contains three Once the program starts, the window that opens, shown below, contains three smaller windows, which are:

smaller windows, which are: the Command Window, the Command Window,

the Workspace Window, and the Workspace Window, and the Command History Window. the Command History Window.

••

The above three windows contains eight different windows in MATLAB.The above three windows contains eight different windows in MATLAB.

S.No.

S.No. Name Name of of Window Window PurposePurpose 1

1 Command Command WinWindow dow Main Main window, window, enters enters variables, variables, runs runs programs.programs. 2

2 Figure Figure WinWindow dow Contains Contains output output from from graphic graphic commands.commands. 3

3 Editor Editor Window Window Creates Creates and and debugs debugs script script and and function function files.files. 4

4 Help Help Window Window Provides Provides help help information.information. 5

5 Launch Launch Pad Pad Window Window ProvideProvides s access access to to tools, tools, demos, demos, andand documentation.

documentation. 6

6 Command Command HistoryHistory Window

Window

Logs commands entered in the

Logs commands entered in the commandcommand window.

window. 7

7 Workspace Workspace Window Window ProvideProvides s information information about about the the variablvariables es that that areare used.

used. 8

8 Current Current DirectoryDirectory Window

Window

Shows the files in the current directory. Shows the files in the current directory.

(10)

Where are you ? Where are you ?

This information is available in three ways: This information is available in three ways: 1.

1. Look at the Look at the command window toolbar. There command window toolbar. There is small wis small window that showindow that show the name of the current directory along with its path. For example, the the name of the current directory along with its path. For example, the below Fig.1 shows that the current directory is D:\Matlab6\work.

below Fig.1 shows that the current directory is D:\Matlab6\work. 2.

2. We can get the same inforWe can get the same information from the commamation from the command line by nd line by typingtyping pwdpwd (Present Working

(Present Working Directory)Directory).. 3.

3. The current directory is The current directory is also displayed in also displayed in a separate subwindow a separate subwindow to the leftto the left of the command window. If it is not visible, click on the

of the command window. If it is not visible, click on the Current DirectoryCurrent Directory tab.

tab.

Fig 1. Which directory are you in ? Fig 1. Which directory are you in ?

(11)

••

The required window can be selected by choosing appropriateThe required window can be selected by choosing appropriate

name of the window in

name of the window in VIEWVIEW as below:as below:

How to change the current directory? How to change the current directory?

The current directory can be changed with the

The current directory can be changed with the cd DirectoryName cd DirectoryName command oncommand on the command line.

(12)

What are the contents of the current directory? What are the contents of the current directory?

The contents of the current directory in the current directory subwindow (below The contents of the current directory in the current directory subwindow (below figure)

figure) or or by by typingtyping dir or ls dir or ls on the command line.on the command line.

Fig. 2. Current directory information from the MATLAB desktop. Fig. 2. Current directory information from the MATLAB desktop.

(13)

What is the

What is the MATLAMATLAB path?B path?

MATLAB path is a variable, stored under the name path that

MATLAB path is a variable, stored under the name path that contains thecontains the paths of all directories that are automatically included in MATLAB’s search path. paths of all directories that are automatically included in MATLAB’s search path.

But default, all directories that are installed by the MATLAB installer are included in this But default, all directories that are installed by the MATLAB installer are included in this path.

path.

The user path can be set by the following procedure: The user path can be set by the following procedure: Step 1:

Step 1:

Step 2: Step 2:

(14)

or Also it can be set in command window by using

or Also it can be set in command window by using addpathaddpathfunction:function:

addpath(‘D:\presentation\matlab_presentation’); addpath(‘D:\presentation\matlab_presentation’);

This can be verified in current directory of matlab toolbar as: This can be verified in current directory of matlab toolbar as:

••

So far we have talked about how to access the MATLAB and its features.So far we have talked about how to access the MATLAB and its features.

••

As we know that, in any programming language is consists of:As we know that, in any programming language is consists of:

(i)

(i) Data Data typestypes (ii)

(ii) Algebraic and Algebraic and logical logical operators.operators. (iii)

(iii) Mathematical Mathematical relations.relations. (iv)

(iv) Control Control statementsstatements (v)

(v) Input and Input and output output accessingaccessing (vi)

(vi) Functions Functions and and subprograms.subprograms.

The MATLAB is very big package and but, it is almost equal to a language. We now The MATLAB is very big package and but, it is almost equal to a language. We now discuss the major features of programming language with MATLAB.

References

Related documents

people of Quebec proposed a complete break away from Canada. E) With the referendum of 20 May 1980 the movement to separate Quebec from Canada finally came to an end.

Section 17 of the LGC went on to devolved certain forest management functions to LGUs, such as enforcement of forestry laws in community based forestry projects, integrated

The two campaigns I have chosen to study represent a shift in style from tactical interventions to strategic organizing both with the goal of sharing information in a

(the “Owner”) hereby acknowledges and agrees with ENMAX Energy Corporation (“ENMAX Energy”) that in the event there is a vacancy in the premises located at or in any of the

The result shows an impossibility of Nash implementation in all economies except pure public goods economies, in the sense that it indicates that in all economies except pure

What’s the difference between an architectural pattern, such as those described in this chapter and in the Pattern-Oriented Software Architecture series of books, and design

On January 1, 2000, Flax Company purchased a machine for P528,000 and depreciated it by the straight-line method using an estimated useful life of eight years with no salvage

The online sample is more likely to report that their work is taxing and stressful (24 percent agree with the statement fully by giving a 1 score, while 29 percent give it a 2