Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Matlab-Theory, Study notes of Advanced Computer Programming

matlab - matlab

Typology: Study notes

2013/2014

Uploaded on 03/05/2014

kshitij.gaur.11
kshitij.gaur.11 🇮🇳

4.7

(3)

7 documents

1 / 70

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad, yadaiahn@hotmail.com 1
MATLAB BASICS & PROGRAMMING
Dr. N. YADAIAH
Associate professor
Dept. of Electrical & Electronics Engineering
J N T University, College of Engineering, HYDERABAD
Yadaiahn@hotmail.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46

Partial preview of the text

Download Matlab-Theory and more Study notes Advanced Computer Programming in PDF only on Docsity!

MATLAB BASICS & PROGRAMMING

Dr. N. YADAIAH

Associate professor

Dept. of Electrical & Electronics Engineering

J N T University, College of Engineering, HYDERABAD

Yadaiahn@hotmail.com

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.
  • The name MATLAB stands for MATrix LABoratory.
  • Matlab is a case sensitive.

Typical uses include

o Math and computation o Algorithm development o Data acquisition Modeling, simulation, and prototyping o Data analysis, exploration, and visualization o Scientific and engineering graphics o 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 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.

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 provides help on topic. lookfor string lists help topics containing string. demo runs the demo program. Info Info about MATALB ver MATLAB version info.

Start & Exit matlabrc Master startup file startup M-file executed at startup quit Quit MATLAB exit Same as quit.

Variable and Workspace information

who lists variables currently in the workspace. whos lists variables currently in the workspace with their size. what lists m-, mat-, and mex-files on the disk./List files in the directory. whatsnew Display ReadMe files. which Locate a file clear clears the workspace, all variables are removed. clear x y z clears only variables x, y and z. clear all clears all variables and functions from workspace. mlock fun locks function fun so that clear cannot remove it. munlock fun unlocks function fun so that clear can remove it. clc clears command window, command history is lost. home same as clc. clf clears figure window. echo Echo commands in script file. load Load variables from file. save Save variables in MAT – file. length Length of a vector. size size of a matrix. pack Consolidate memory space disp Display text or matrix.

  • separate rows in the input list of a matrix. 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 i=l: 20, x=x+i; end. ` Right Quote : A single right quote is used to transpose a vector or a matrix. Example: symA = (A' +A) /2.

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

character string.

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

. Period: A period is used: - as a decimal point, i, - in array operations.

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 = [log(1:100) sin(v+a.*b) 22.3 23....

34.0 33.0 40:50 80];

! Exclamation : An exclamation preceding a command is used to send the local

operating system command command to the system.

This command is not applicable to Macs.

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 is a comment, but rate = ‘8.5%’ is a string.
  • .to denote formats in standard I/O functions sprintf and fprintf. Example: sprintf('R = %6.4f', r).

( ) Parentheses : Parentheses are used to:

  • .specify precedence in arithmetic operations, Example: a = 5/ (2+x* (3-i)); etc.
  • .enclose matrix and vector indices, Example: A(1:5, 2) = 5; v = x(1: n-5); etc.
  • enclose the list of input variables of a function. Example: [t,x]=ode23('pend', to, tf, x0). .,

[ ] Square brackets : Square brackets are used to:

  • form and concatenate vectors and matrices, Example: v = [1 2 3:9]; X = [v; log(v)]; etc.
  • enclose the list of output variables of a function. 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 Default output variable.

nargin Number of input arguments.

nargout Number of output arguments.

Where are you? This information is available in three ways:

  1. Look at the command window toolbar. There is small 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 from the command line by typing pwd (Present Working 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?

  • 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 on the command line.

What is the 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:

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) Data types (ii) Algebraic and logical operators. (iii) Mathematical relations. (iv) Control statements (v) Input and output accessing (vi) 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.

Data Types

There are 14 fundamental data types (or classes) in MATLAB. Each of these data types is in the form of an array. This array is a minimum of 0-by-0 in size and can grow to an n-dimensional array of any size. Two-dimensional versions of these arrays are called matrices.

The char data type holds characters in Unicode representation. A character string is merely a 1-by-n array of characters. To hold an array of strings of unequal length, use a cell array.

Numeric data types include signed and unsigned integers, single- and double- precision floating point, and sparse matrices of double-precision. The following hold true for numeric data types in MATLAB:

All MATLAB computations are done in double-precision. Integer and single precision arrays offer more memory efficient storage than double-precision. All data types support basic array operations, such as subscripting and reshaping. To perform mathematical operations on integer or single precision arrays, it must convert them to double precision using the double function.

A cell array provides a storage mechanism for dissimilar kinds of data. For example , you can store a 1-by-50 char array, a 7-by-13 double array, and a 1-by- 1 uint32 in cells of the same cell array.

The MATLAB structure data type is similar to the cell array in that it also stores dissimilar kinds of data. But, in this case, it stores the data in named fields rather than in cells.

MATLAB data types are implemented as classes. We can also create MATLAB classes of our own.

MATLAB provides an interface to the Java programming language that enables us to create objects from Java classes and call Java methods on these objects. A Java class is a MATLAB data type. A function handle holds information to be used in referencing a function. When you create a function handle, MATLAB captures all the information about the function that it needs to locate and execute, or evaluate, it later on.

The following table describes the data types in more detail. Data Type Example Description single 310^38 Single-precision numeric array. Single precision requires less storage than double precision, but has less precision and a smaller range. This data type cannot be used in mathematical operations. double 310^ 5+6i

Double-precision numeric array. This is the most common MATLAB variable type. sparse speye(5) Sparse double-precision matrix (2-D only). The sparse matrix stores matrices with only a few nonzero elements in a fraction of the space required for an equivalent full matrix. Sparse matrices invoke special methods especially tailored to solve sparse problems. int8, uint8, int16,uint16, int32,uint

uint8(magic(3)) Signed and unsigned integer arrays that are 8, 16, and 32 bits in length. Enables you to manipulate integer quantities in a memory efficient manner. These data types cannot be used in mathematical operations. char 'Hello' Character array (each character is 16 bits long). This array is also referred to as a string. cell {17 'hello' eye(2)}

Cell array. Elements of cell arrays contain other arrays. Cell arrays collect related data and information of a dissimilar size together. structure a.day = 12; a.color = 'Red'; a.mat = magic(3);

Structure array. Structure arrays have field names. The fields contain other arrays. Like cell arrays, structures collect related data and information together. user class inline('sin(x)') MATLAB class. This user-defined class is created using MATLAB functions. java class java.awt.Frame Java class. You can use classes already defined in the Java API or by a third party, or create your own classes in the Java language. functionhandle @humps Handle to a MATLAB function. A function handle can be passed in an argument list and evaluated using feval. Examples:

format long

pi

ans = 3.

format short

pi

Syntax

A+B A-B

AB A.B

A/B A./B

A\B A.\B

A^B A.^B

A' A.'

Relational Operators Operator Description < Less than <= Less than or equal to

Greater than = Greater than or equal to == Equal to ~= Not Equal to

MATLAB provides the following logical operators.

Operator Description & AND | OR ~ NOT

Logical operations Syntax A & B A | B ~A Description : The symbols &, |, and ~ are the logical operators and, or, and not respectively. They work element-wise on arrays, with 0 representing logical false (F), and anything nonzero representing logical true (T). The & operator does a logical and , The | operator does a logical or , and ~ A complements the elements of A. The function xor(A,B) implements the exclusive or operation.

Operator Precedence

It can build expressions that use any combination of arithmetic, relational, and logical operators. Precedence levels determine the order in which MATLAB evaluates an expression. The precedence rules for MATLAB operators from highest precedence level to lowest precedence level:

**1. Parentheses ()

  1. Transpose(.'), power(.^), complex conjugate transpose('), matrix** **power(^)
  2. Unary plus (+), unary minus (-), logical negation (~)
  3. Multiplication (.), right division (./), left division(.), matrix multiplication* (),* **matrix right division (/), matrix left division ()
  4. Addition (+), subtraction (-)
  5. Colon operator (:)
  6. Less than (<), less than or equal to (<=), greater than (>), greater than or** equal **to (>=), equal to (==), not equal to (~=)
  7. Logical AND (&)
  8. Logical OR (|)**