MATLAB BASICS & PROGRAMMING
Dr. N. YADAIAH Associate professor
Dept. of Electrical & Electronics Electronics Engineering Engineering J N T University, College of Engineering, HYDERABAD HYDERABAD
[email protected]
Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] Hyderabad,
[email protected]
1
MATLAB BASICS What Is MATLAB? • MATLAB® is a high-performance language for technical computing. It integrates computation, visualization, and programming in an easy-to-use environment where problems and solutions are expressed in familiar mathematical notation.
MATLAB stands for MATrix LABoratory. LABoratory. • The name MATLAB
• Matlab is a case sensitive. Typical uses include o o o o o o
Math and computation Algorithm development Data acquisition Modeling, simulation, and prototyping Data analysis, exploration, and visualization Scientific and engineering graphics Application development, including graphical user interface building
• MATLAB is an interactive system whose basic data element is an array that does not require dimensioning.
• In Academic environment, it is the standard instructional tool for introductory and advanced courses in mathematics, engineering, and science.
• In Industry, MATLAB is the tool of choice for high-productivity research, development, and analysis.
• MATLAB MATLAB features a family of add-on application-specific solutions called toolboxes. Very important to most users of MATLAB, toolboxes allow us to learn and apply specialized technology.
• Toolboxes are comprehensive collections of MATLAB functions (M-files) that extend the MATLAB environment to solve particular classes of problems.
• Areas in which toolboxes are available include signal processing, control systems, neural networks, fuzzy logic, wavelets, simulation, and many others.
Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] Hyderabad,
[email protected]
2
The MATLAB System The MATLAB system consists of five main parts: that help us to Development Environment: This is the set of tools and facilities that use MATLAB functions and files. Many of these tools are graphical user interfaces. It includes the MATLAB desktop and Command Window, a command history, an editor and debugger, and browsers for viewing help, the workspace, files, and the search path.
The MATLAB Mathematical Function Library: This is a vast collection of computational algorithms ranging from elementary functions like sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms. The MATLAB Language: This is a high-level matrix/array language with control flow statements, functions, data structures, input/output, and object-oriented programming features. Graphics: MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as annotating and printing these graphs. It includes high-level functions for two-dimensional and three-dimensional data visualization, image processing, animation, and presentation graphics. It also includes low-level functions that allow you to fully customize the appearance of graphics as well as to build complete graphical user interfaces on your MATLAB applications. The MATLAB Application Program Interface (API). This is a library that 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 a computational engine, and for reading and writing MAT-files.
Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] Hyderabad,
[email protected]
3
Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] Hyderabad,
[email protected]
4
General Commands one should remember Help Commands help lists topics on which help is available. helpwin opens the interactive help window. helpdesk opens the web browser based help facility. help topic help topic provides help on topic. lookfor string lookfor string lists help topics containing string. demo runs the demo program. Info Info about MATALB ver MATLAB version info.
Start & Exit matlabrc startup quit exit
Master startup file M-file executed at startup Quit MATLAB Same as quit.
Variable and Workspace information who whos what whatsnew which clear clear x y z clear all mlock fun mlock fun munlock fun clc home clf echo load save length size pack disp
lists variables currently in the workspace. lists variables currently in the workspace with their size. lists m-, mat-, and mex-files on the disk./List files in the directory. Display ReadMe files. Locate a file clears the workspace, all variables are removed. clears only variables x, y and z. clears all variables and functions from workspace. locks function fun so fun so that clear cannot remove it. unlocks function fun so fun so that clear can remove it. clears command window, command history is lost. same as clc. clears figure window. Echo commands in script file. Load variables from file. Save variables in MAT – file. Length of a vector. size of a matrix. Consolidate memory space Display text or matrix.
Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] Hyderabad,
[email protected]
5
Directory information pwd cd dir ls path editpath copyfile mkdir
↑↓ delete dairy type !
shows the current working directory. changes the current working directory. lists contents of the current directory. lists contents of the current directory, same as air. gets or sets MATLAB se~rch path. modifies MATLAB search path. copies a file. creates a directory. Recall previous commands. Delete file Save text of MATLAB session Show contents of file Access operating system
General information tells you the computer type you are using gives you wall clock time and date as a vector. tells you the date as a string. controls the paged output according to the screen size. gives the license and the version information about MATLAB installed on your computer. bench benchmarks your computer on running MATLAB. compared to other computers. cputime Elapsed CPU time. etime Elapsed time function tic Start stopwatch timer toc Read stopwatch timer Punctuation Marks and Other Symbols
computer clock date more ver
, Comma: A comma is used to:
• separate variables variables in the input and output list of a function, f unction, Example: [t Example: [t ,x] = ode23 ( 'pend' ,to ,tf ,x0),
• separate the row and column indices in a matrix, Example: A(m,n), Example: A(m,n), A(l: 10,3) etc.,
• separate different commands on the same line. Example: plot(x, Example: plot(x, y) , grid, xlabel('x') etc.
; Semicolon: A semicolon is used to:
• suppress the MATLAB' output of a command, Example: x=1:10 ; y= A*x; etc.,
Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] Hyderabad,
[email protected]
6
• separate rows in the input list of a matrix. Example: A= Example: A= [1 2; 4 9].
: Colon: A colon is used to specify range:
• in creating vectors, Example: x=l: 10; y=.l:2: 100; etc.
• for matrix and vector indices, • in for loops. Example: for Example: for i=l: 20, x=x+i; end.
` Right Quote: A single right quote is used to transpose a vector or a matrix. Example: symA Example: symA = (A' +A) /2.
` ‘ Single Quotes: A pair of single right quote characters is used to enclose a character string. .Example: xlabel('time'), .Example: xlabel('time'), title('My plot') etc.
. Period: A period is used:
• as a decimal point, i, • in array operations. Example: Asq Example: Asq = A.^ 2
. . Two periods: Two periods are used in cd . . command to access parent directory.
... Ellipsis: Ellipsis (three periods) at the end of a command denotes continuation to the next line. Exampte: x Exampte: x = [log(1:100) sin(v+a.*b) sin(v+a.* b) 22.3 23.0 34.0 33.0
...
40:50 80];
! Exclamation: An exclamation preceding a command is command is used to send the local operating system command command to command to the system. This command is not applicable to Macs. Example: ! Example: ! emacs newfile .m invokes the local emacs editor.
% Percent: A percent character is used to:
• used to mark the beginning of a comment, except when used in character strings. Example: % This % This is a comment, but rate = ‘8.5%’ is a string.
Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] Hyderabad,
[email protected]
7
• .to denote formats in standard I/O functions sprintf and fprintf. Example: sprintf('R Example: sprintf('R = %6.4f', r).
( ) Parentheses: Parentheses are used to:
• .specify precedence in arithmetic operations, Example: a Example: a = 5/ (2+x* (3-i)); etc.
• .enclose matrix and vector indices, Example: A(1:5, Example: A(1:5, 2) = 5; v = x(1: n-5); etc.
• enclose the list of input variables of a function. f unction. Example: [t,x]=ode2 Example: [t,x]=ode23('pend', 3('pend', to, tf, x0). .,
[ ] Square brackets : Square brackets are used to:
• form and concatenate vectors and matrices, Example: v Example: v = [1 2 3:9]; X = [v; log(v)]; etc.
• enclose the list of output variables of a function. Example: [V,D] Example: [V,D] = eig(A); etc.
Special Variables and Constants Constants pi
π (= 3.14159...)
inf
∞ (infinity)
NaN
Not-a-Number
i, j
Imaginary unit ( − 1 )
eps
Machine precision.
realmax
Largest real number.
realmin
Smallest real number.
Variables ans nargin nargout
Default output variable. Number of input arguments. Number of output arguments.
Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] Hyderabad,
[email protected]
8
Working with Files and Directories MATLAB WINDOWS: Once the program starts, the window that opens, shown below, contains three smaller windows, which are: the Command Window, the Workspace Window, and the Command History Window.
• The above three windows contains eight different windows in MATLAB. S.No. 1 2 3 4 5
Name of Window Command Window Win dow Figure Window Win dow Editor Window Help Window Launch Pad Window
6
Command History Window Workspace Window
7 8
Current Directory Window
Purpose Main window, enters variables, runs programs. Contains output from graphic commands. Creates and debugs script and function files. Provides help information. Provides Provides access to tools, demos, and documentation. Logs commands entered in the command window. Provides Provides information about the variables variables that are used. Shows the files in the current directory.
Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] Hyderabad,
[email protected]
9
Where are you ? This information is available in three ways: 1. Look at the command window toolbar. There is small window window that show 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. 2. We can get the same information information from the command command line by typing pwd (Present Working Directory). Directory). 3. The current directory is also displayed in a separate subwindow to the left of the command window. If it is not visible, click on the Current Directory tab.
Fig 1. Which directory are you in ?
Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] Hyderabad,
[email protected]
10
• The required window can be selected by choosing appropriate name of the window in VIEW as below:
How to change the current directory? The current directory can be changed with the cd DirectoryName command DirectoryName command on the command line.
Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] Hyderabad,
[email protected]
11
What are the contents of the current directory? The contents of the current directory in the current directory subwindow (below figure) or by typing dir or ls on ls on the command line.
Fig. 2. Current directory information from the MATLAB desktop.
Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] Hyderabad,
[email protected]
12
What is the MATLAB MATLAB path? MATLAB path is a variable, stored under the name path that contains the 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 path. The user path can be set by the following procedure: Step 1:
Step 2:
Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] Hyderabad,
[email protected]
13
or Also it can be set in command window by using addpath function: addpath(‘D:\presentation\matlab_presentation’); 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. • As we know that, in any programming language is consists of: (i) (ii) (iii) (iv) (v) (vi)
Data types Algebraic and logical operators. Mathematical relations. Control statements Input and output accessing Functions and subprograms.
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.
Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] Hyderabad,
[email protected]
14