99
MATLAB introduction We cannot teach people anything. We can only help them discover it within themselves. Galileo Galilei

Matlab Course Session1 Introduction CUR

Embed Size (px)

DESCRIPTION

Parte 1 del curso de Matlab en la universidad de Lovaina (Bélgica). Introducción.

Citation preview

Page 1: Matlab Course Session1 Introduction CUR

MATLABintroduction

We cannot teach people anything. We can only help them discover it within themselves.

Galileo Galilei

Page 2: Matlab Course Session1 Introduction CUR

CourseIntroduction_3

Why this Course?The computer:

indispensable tool used in all aspects of the sciences.perform time consuming tasks quickly.the single most important instrument you need to

Visualize, explore, and analyze your dataDevelop models to explain your dataSimulate phenomena...

CourseIntroduction_4

Matlab is a Marketable Skill

Check Job Tiobe index

Page 3: Matlab Course Session1 Introduction CUR

CourseIntroduction_5

Goals

Aim: getting to know the basics MatlabIntroduce Matlab to the noviceIllustrate key features and capabilities of MatlabUnderstand basic Matlab codeDemonstrate to write efficient Matlab code

Matlab programming and CSyntax is similarlanguage structure is similar to C:

Matlab supports variables, arrays, structures, subroutines, filesMatlab does not support pointers and does not require variable declarations

CourseIntroduction_6

Goals

Matlab is an extensive package, you will not be able to know all functions

Matlab documentation: more than 5000 pagesMore than 300 built-in functionsMore than 1000 M-files contained in the base product of Matlab...

Matlab is the SWISS ARMY KNIFE for numerical problems

Page 4: Matlab Course Session1 Introduction CUR

CourseIntroduction_7

www.mathworks.com

StatisticsOptimizationSignal processingImage processingCurve fitting Bioinformatics toolboxFinancial toolbox....

Application development tools:

Matlab compilerMatlab Excel builderMatlab Com builder

Data acquisition and access tools

Excel linkData acquisition toolbox....Database toolbox

CourseIntroduction_8

Fortran and Scientific Computing

Engineering and scientific applications involve a lot of "number crunching".For many years, the main language for this was FORTRAN Here's a Fortran code to solve a x2 + b x + c = 0:

C Solve a quadratic equation (this is a comment).

DESC = B*B - 4*A*C

IF ( DESC .LT. 0.0 ) GOTO 10

DESC = SQRT(DESC)

X1 = (-B + DESC)/(2.0*A)

X2 = (-B - DESC)/(2.0*A)

WRITE(6,*) "SOLUTIONS ARE ",X1," AND ", X2

RETURN

10 WRITE(6,*) "EQUATION HAS COMPLEX ROOTS"

RETURN

Page 5: Matlab Course Session1 Introduction CUR

CourseIntroduction_9

Solving a Linear System in FortranHere's a Fortran code to solve a linear system A.x=b, solve for x.

C Solve B = A*X for X. C N is dimension of vectors and matrixC Does not use row interchange, scaling.

SUBROUTINE LINSYS(N, A, X, B, TMP)INTEGER NDOUBLE PRECISION A(N,N), X(N), B(N)DOUBLE PRECISION TMP(N), RATIO

C... Forward eliminationDO 13 J=1,N-1

DO 12 I=J+1,NRATIO = -A(I,J)/A(J,J)A(I,*) = A(I,*) +RATIO*ROW(J,*)DO 11 K=J+1,N

11 A(I,K) = A(I,K) + RATIO*A(J,K)A(I,J) = 0.0X(I) = X(I) + RATIO*X(J)

12 CONTINUE11 CONTINUE

Continued...

C... Backwards substitutionX(N) = X(N)/A(N,N)DO 21 I=N-1,1,-1

TMP = X(I)DO 20 J=I+1,N

20 TMP = TMP - A(I,J)*X(J)X(I) = TMP/A(I,I)

21 CONTINUERETURNEND

This is just a small example.

A full program may be 1000's of lines long.

CourseIntroduction_10

Need for Numerical Libraries

The U.S. government recognized these problems, and the inefficiency of many engineers all writing the samealgorithms... again and again.So, they commissioned numerical analysts to write good quality algorithms for common tasks.Make the results freely available as "libraries" of subroutines than anyone can use in their programs.Libraries are available at: www.netlib.org

Page 6: Matlab Course Session1 Introduction CUR

CourseIntroduction_11

HistoryLINPACK, EISPACK.

(1970In the mid-1970s, Cleve Moler and several colleagues developed the FORTRAN subroutine libraries called LINPACK and EISPACK under a grant from the National Science Foundation. LINPACK was a collection of FORTRAN subroutines for solving linear equations, while EISPACK contained subroutines for solving eigenvalue problems. Together, LINPACK and EISPACK represented state of the art software for matrix computation.

Jack Dongarra, Cleve Moler, Pete Stewart, and Jim Bunch in 1978

C.... factor the A matrixCALL SGEFA(A, N, N, IPVT, INFO)

C.... copy B vector into X vectorCALL SCOPY(N, B, 1, X, 1)

C.... solve the system of equationsCALL SGESL(A, N, N, IPVT, X, 0)

CourseIntroduction_12

HistoryMatlab 0 (1978)

Cleve Moler designed (as a "hobby" on his own time ) it to give his students interactive access to LINPACK and EISPACK without having to learn FORTRAN Moler named his program Matlab, for MATrix LABoratory.Over the next several years, when he would visit another university to give a talk, or as a visiting professor, he would end up by leaving a copy of his Matlab on the university machines. Within a year or two, Matlab started to catch on by word of mouth within the applied math community as a "cult" phenomena

Page 7: Matlab Course Session1 Introduction CUR

CourseIntroduction_13

HistoryMatlab 1. (1984)

reprogrammed in Ccommercial potential => Mathworks1983, John Little was exposed to Matlab because of a visit Cleve made to Stanford. Little, an engineer, recognized the potential application of Matlab to engineering applications. Little teamed up with Cleve Moler and Steve Bangert to develop a second generation, professional version of Matlab written in C and integrated with graphics. The MathWorks, Inc. was founded in 1984 to market and continue development of Matlab.

CourseIntroduction_14

History

Software has evolved into an interactive system and programming language for general scientific and technical computation and visualizationThe MathWorks has become a commercial success.

In the period 1984 1991 the number of employees has doubled every year, from 2^0 people in 1984 to 2^7 people in 1991. In the following years, the staff has increased roughly 20% per year, from 2^7 people in 1991, to 2^9 people in 1999, and 2^10 people in 2002.

Matlab 7 (2004) Release 14

Matlab 2009a/b (2009)

Page 8: Matlab Course Session1 Introduction CUR

CourseIntroduction_15

Matlab: pro

Ease of use: interpreter and integrated environmenteasy and fast codingsimple, compact, and procedural language with moderate learning curve

Strong graphical and numerical capabilitiesPlatform independentPredefined functions (toolbox - Spectral Analysis, Image Processing, Signal Processing, Financial, Symbolic Math ...)Extra functions can be created in M-files.Large user base with much user-contributed softwareGUI: user can construct its own guiLots of code and information available on te web

CourseIntroduction_16

Matlab: contra

Interpreter can be slow (compiler)Few data types/structures supported

options is difficult to use.well written FORTRAN / C code can be fasternot (yet) suitable for parallel programming

1999

began as a simple way to do powerful things,and it has become a not-so-simple way to do

cost

Page 9: Matlab Course Session1 Introduction CUR

CourseIntroduction_17

Why not C, FORTRAN, ...?

No built-in graphics; problem to visualize data and modelsMore bookkeeping needed to do thingspro: Open-source versions exist, some better suited for specific applications

CourseIntroduction_18

What about Excel?

Spreadsheet programs are very good at dealing with table data in simple ways, and has graphics built-inMore advanced calculations require programming in Visual BasicAdvanced mathematics?Proprietary, binary file formatNot available on all platforms

Page 10: Matlab Course Session1 Introduction CUR

CourseIntroduction_19

Free Matlab AlternativesGNU Octave (www.octave.org) is a high-level language, that is mostly compatible with Matlab; it is freely redistributable.

Scilab (www.scilab.org) is a scientific software package for numerical computations providing a powerful open computing environment for engineering and scientific applications

dictionary: http://www.scilab.org/product/dic-mat-sci/SCI2M.htm

CourseIntroduction_20

Using vs Programming Matlab

Some problems can be solved using a software tool (e.g., a spreadsheet program, Excel). It is usually faster to solve a problem with an existing tool.Many problems cannot be solved with such tools, or a tool is not available. We must then program our own

Matlab blurs the line between computer tool and computer language since it is both.

Page 11: Matlab Course Session1 Introduction CUR

CourseIntroduction_21

References

Engineering Computation withMATLAB David Smith Pearson 2008Mastering Matlab 7Duane Hanselman& Bruce LittlefieldPrentice Hall, 2004

References

use the mathworks website:Matlab getting startedhttp://www.mathworks.com/access/helpdesk/help/pdf_doc/matlab/getstart.pdfMatlab reference (3 volumes)http://www.mathworks.com/access/helpdesk/help/pdf_doc/matlab/refbook.pdfhttp://www.mathworks.com/nn_bookshttp://www.mathworks.com/company/newsletters/

Page 12: Matlab Course Session1 Introduction CUR

CourseIntroduction_23

Google is your friend

MATLABdesktop

Page 13: Matlab Course Session1 Introduction CUR

Desktop_2

Introduction to Matlab

Discover how Matlab is designed and what the basic components doTopics

Matlab DesktopHELPBasic language syntax

Matlab Desktop 7.8

Page 14: Matlab Course Session1 Introduction CUR

Desktop_6

Current Directory

Location of the folder that contains scripts that you have written and any data files you want to analyze

Matlab Path and Search Order

Matlab finds the functions you call by searching the Matlab Path in the order in which the directories on the path are specified. If multiple functions with the same name exist on the path, the version associated with the end of the pathlistis used. The easiest way to add new directories or view the existing path is to use the graphical pathtool available via file->set path or by typing pathtool at the command prompt.

Page 15: Matlab Course Session1 Introduction CUR

Desktop_8

Workspace/Array editor

Lists variables from code and experiments you have run

double-click the variable opens a window showing the valuesvalues can be changed interactively

Desktop_9

Command Window

main working areacan run lines of codedisplays values if code is not concluded with ;pushing up arrow cycles through previous entries

Page 16: Matlab Course Session1 Introduction CUR

Desktop_10

Command History

displays a log of the statements most recently run in the Command Windowuser can copy from this list one or more lines of code and paste it into the command windowsaves history (up to 20k)

Desktop_11

Desktop layout

Layout can be changed Different windows can be shown (or not)Windows can be docked/undocked

Page 17: Matlab Course Session1 Introduction CUR

Desktop_12

HELP

Click on Help-icoonhelpdeskhelp + command name: online help in Command Windowhelpwin + command name: online help in Help Windowdoc + command name: online documentation lookfor + search string: search for search string in Matlab path

Desktop_13

HELP

Page 18: Matlab Course Session1 Introduction CUR

Desktop_14

HELP>> helpHELP topics

matlab\general - General purpose commands.matlab\ops - Operators and special characters.matlab\lang - Programming language constructs.matlab\elmat - Elementary matrices and matrix manipulation.matlab\elfun - Elementary math functions.matlab\specfun - Specialized math functions.matlab\matfun - Matrix functions - numerical linear algebra.matlab\datafun - Data analysis and Fourier transforms.matlab\polyfun - Interpolation and polynomials.matlab\funfun - Function functions and ODE solvers.matlab\sparfun - Sparse matrices.matlab\scribe - Annotation and Plot Editing.matlab\graph2d - Two dimensional graphs.matlab\graph3d - Three dimensional graphs.matlab\specgraph - Specialized graphs.matlab\graphics - Handle Graphics.matlab\uitools - Graphical user interface tools.matlab\strfun - Character strings.matlab\imagesci - Image and scientific data input/output.matlab\iofun - File input and output.matlab\audiovideo - Audio and Video support.matlab\timefun - Time and dates.matlab\datatypes - Data types and structures.matlab\verctrl - Version control.matlab\codetools - Commands for creating and debugging code.matlab\helptools - Help commands.matlab\winfun - Windows Operating System Interface Files (COM/DDE)matlab\demos - Examples and demonstrations.

Desktop_15

The Matlab Environment

Matlab is an interpreted languageCommands are typed into the COMMAND Windowand executed immediatelyVariables are allocated in memory as soon as they are first used in an expressionCommands must be re-entered to be re-executed

All variables created in the Command Window are in what is called the Base Workspace

Variables can be reassigned new values as neededVariables can be selectively cleared from the workspace

Page 19: Matlab Course Session1 Introduction CUR

Desktop_17

Commands, Statements & VariablesAt the prompt in the Command Window, you can enter either

a:Command: save mydata (saves workspace in mydata.mat)whos (displays list of workspace variables)

Assignment Statement: A = width * length;B = 267;Assignment statements can have only a single variable on the left side of the assignment operator (=)The RHS is evaluated using current values for all variables and the resulting value is assigned to the variable on the LHS.Values can be numbers or characters

assignment is made (warning: powerful but can lead to

Variablesup to 63 characters (more are ignored); Case SensitiveCheck with namelengthmax

Desktop_18

Editing keys

Key Function Browse backward through the

commands Browse forward through the

commands Scroll backward through a

single command Scroll forward through a

single command ctrl Scroll backward through a

single command by word ctrl Scroll forward through a

single command by word home Jump to the beginning of the

command line end Jump to the end of the

command line esc Clear line del Discard character under cursor backspace Discard character in front of

the cursor tab Complete a command (select

from the list)

Page 20: Matlab Course Session1 Introduction CUR

Desktop_19

Variables and Names

A variable is a placeholder in memoryVariables contain valuesVariable names:

Are case sensitive: Cost, cost, COST are differentMay contain up to 63 characters (more are ignored)Must start with a letter,May contain numbers and letters

How do I view the contents of a variable?

Desktop_20

Reserved WordsMatlab has some special (reserved) words that you may

Use the iskeyword to list all reserved words.

forendifwhilefunctionreturnelsifcaseotherwise

switchcontinueelsetrycatchglobalpersistentbreak

Page 21: Matlab Course Session1 Introduction CUR

Desktop_21

Case Sensitivity

Matlab is case sensitiveFile names

Matlab running on Windows now gives preference to an exact (case sensitive) name match, but falls back to an inexact (case insensitive) match when no exact match can be found.Whenever Matlab 7 detects a potential naming conflict related to case sensitivity, it issues a warning.

Desktop_22

Matlab as a calculator

Always see what is being calculatedCan use variables

previously executed commandsBy typing the beginning of command and then using up arrow can recall commands that start from the typed symbolsCan copy and paste into documentsCan easily plot graphs

Page 22: Matlab Course Session1 Introduction CUR

Desktop_23

Built-in functions

Matlab offers a wealth of built-in math functions that can be quite helpful for many computational problems

Elementary Matlab functions (help elfun)Trigonometric functionsExponential functionsComplex functionsRounding and remainder functions

Specialized Matlab functions (help specfun)Specialized math functionsNumber theoretic functionsCoordinate transformations

Desktop_24

Elementary math functionsTrigonometric.

sin - Sine.sind - Sine of argument in degrees.sinh - Hyperbolic sine.asin - Inverse sine.asind - Inverse sine, result in degrees.asinh - Inverse hyperbolic sine.cos - Cosine.cosd - Cosine of argument in degrees.cosh - Hyperbolic cosine.acos - Inverse cosine.acosd - Inverse cosine, result in degrees.acosh - Inverse hyperbolic cosine.tan - Tangent.tand - Tangent of argument in degrees.tanh - Hyperbolic tangent.atan - Inverse tangent.atand - Inverse tangent, result in degrees.atan2 - Four quadrant inverse tangent.atanh - Inverse hyperbolic tangent.

sec - Secant.secd - Secant of argument in degrees.sech - Hyperbolic secant.asec - Inverse secant.asecd - Inverse secant, result in degrees.asech - Inverse hyperbolic secant.csc - Cosecant.cscd - Cosecant of argument in degrees.csch - Hyperbolic cosecant.acsc - Inverse cosecant.acscd - Inverse cosecant, result in degrees.acsch - Inverse hyperbolic cosecant.cot - Cotangent.cotd - Cotangent of argument in degrees.coth - Hyperbolic cotangent.acot - Inverse cotangent.acotd - Inverse cotangent, result in degrees.acoth - Inverse hyperbolic cotangent.

Page 23: Matlab Course Session1 Introduction CUR

Desktop_25

Elementary math functionsExponential.

exp - Exponential.expm1 - Compute exp(x)-1 accurately.log - Natural logarithm.log1p - Compute log(1+x) accurately.log10 - Common (base 10) logarithm.log2 - Base 2 logarithm and dissect

floating point number.pow2 - Base 2 power and scale

floating point number.realpow - Power that will error out on

complex result.

reallog - Natural logarithm of real number.

realsqrt - Square root of number greater than or equal to zero.

sqrt - Square root.nthroot - Real n-th root of real numbers.nextpow2 - Next higher power of 2.

Complex.abs - Absolute value.angle - Phase angle.complex - Construct complex data from real

and imaginary parts.conj - Complex conjugate.imag - Complex imaginary part.real - Complex real part.unwrap - Unwrap phase angle.isreal - True for real array.cplxpair - Sort numbers into complex conjugate

pairs.

Rounding and remainder.fix - Round towards zero.floor - Round towards minus infinity.ceil - Round towards plus infinity.round - Round towards nearest integer.mod - Modulus (signed remainder after

division).rem - Remainder after division.sign - Signum.

Desktop_26

Specialized math functionsSpecialized math functions.

airy - Airy functions.besselj - Bessel function of the first kind.bessely - Bessel function of the second kind.besselh - Bessel functions of the third kind

(Hankel function).besseli - Modified Bessel function of the first

kind.besselk - Modified Bessel function of the

second kind.beta - Beta function.betainc - Incomplete beta function.betaln - Logarithm of beta function.ellipj - Jacobi elliptic functions.ellipke - Complete elliptic integral.erf - Error function.erfc - Complementary error function.erfcx - Scaled complementary error function.erfinv - Inverse error function.expint - Exponential integral function.gamma - Gamma function.gammainc - Incomplete gamma function.gammaln - Logarithm of gamma function.psi - Psi (polygamma) function.legendre - Associated Legendre function.cross - Vector cross product.dot - Vector dot product.

Number theoretic functions.factor - Prime factors.isprime - True for prime numbers.primes - Generate list of prime numbers.gcd - Greatest common divisor.lcm - Least common multiple.rat - Rational approximation.rats - Rational output.perms - All possible permutations.nchoosek - All combinations of N elements

taken K at a time.factorial - Factorial function.

Coordinate transforms.cart2sph - Transform Cartesian to spherical

coordinates.cart2pol - Transform Cartesian to polar

coordinates.pol2cart - Transform polar to Cartesian

coordinates.sph2cart - Transform spherical to Cartesian

coordinates.hsv2rgb - Convert hue-saturation-value colors

to red- green-blue.rgb2hsv - Convert red-green-blue colors to

hue- saturation-value.

Page 24: Matlab Course Session1 Introduction CUR

Desktop_27

Some Special Variables

ans : default variable name for resultsbeep: make soundpi: pieps: smallest number that can be subtracted from 0 to make a negative numberinf: infinity (or Inf)NaN: not a number (or nan)realmin: smallest positive real numberrealmax: largest positive real number

Desktop_28

Format

Format controls display of output in the command window

format short

format long

format rat

format hex

Page 25: Matlab Course Session1 Introduction CUR

Desktop_29

Matlab Programs

Programs in Matlab are:Scripts: Matlab statements that are fed from a file into the Command Window and executed immediatelyFunctions: Program modules that are passed data (arguments) and return a result (i.e., sin(x))These can be created in any text editor (but Matlab supplies a nice built-in editor)

Desktop_30

Editor

Color keyed text with auto indents

tabbed sheets for other files being edited

Access to commands

Page 26: Matlab Course Session1 Introduction CUR

Desktop_31

Summary

desktop environmenttry to use help as much as possiblebesides Matlab Help there is also googleuse Matlab interactively as a calculator

MATLABnumeric data types

Page 27: Matlab Course Session1 Introduction CUR

Basic Data Structure

array: most basic data structure in Matlaba two-dimensional, rectangularly shaped data structurecan contain numbers, characters, logical states

Matlab uses these two-dimensional arrays to store single numbers and linear series of numbers as well. In these cases, the dimensions are 1-by-1 and 1-by-n respectively, where n is the length of the numeric series. Matlab also supports data structures that have more than two dimensions.

data types

Matlab is different from C and other common languages in some important ways:

basic data structure in Matlab is array.variables do not have to be declared beforehand.

Page 28: Matlab Course Session1 Introduction CUR

overview

MATLAB Data Types

double precision(real and complex)

single precision(real and complex)

integer and unsignedinteger data types

logical data character strings

cell arrays structures objects

double single logical char

cell structureuser

classes

int8, unit8int16, uint16int32, unit32int64, unint64

functionhandles

function handles

overview

Page 29: Matlab Course Session1 Introduction CUR

Numeric Data Types

Numeric data types in Matlab include: signed and unsigned integers, single- and double-precision floating-point numbers. Integer and single- precision arrays offer more memory efficient storage than double precision.

All numeric types support basic array operations, such as subscripting and reshaping.

All numeric types except for int64 and uint64 can be used in mathematical operations.

integer

4 signed and 4 unsigned integer data types. Signed types:

enable negative integers as well as positive, represent smaller range of numbers as the unsigned types

Unsigned typeswider range of numbers zero or positive.

Matlab supports 1-, 2-, 4-, and 8-byte storage for integer data.

save memory and execution time for your programs if you use the smallest integer type that accommodates your data. no need for a 32-bit integer to store the value 100.

Page 30: Matlab Course Session1 Introduction CUR

integer

integer

Creating Integer DataMatlab stores numeric data as double-precision floating point by default. Store data as an integer: use one of the conversion functions x = int16(32501);Use the whos function to show the dimensions, byte count, and data type of an array represented by a variable.ex. PAY ATTENTION!x=int8(60);y=int8(70);z=x+y; ex. demo_integer

Page 31: Matlab Course Session1 Introduction CUR

floating point: double

Matlab represents floating-point numbers in: double-precision (default)single-precision format.

single precision with a conversion function (single)according to IEEE Standard 754 for double precision. 64 bits, formatted as: Bits Usage63 sign (0 = positive, 1 = negative)62 to 52 Exponent, biased by 102351 to 0 Fraction f of the number 1.f

Maximum and Minimum Double-Precision Values:realmax and realmin return the maximum and minimum values that you can represent with the double data typeconversion function: double

ex. demo_float

floating point: single

Matlab constructs the single data type according to IEEE Standard 754 for single precision. Any value stored as a single requires 32 bits: Bits Usage31 sign (0 = positive, 1 = negative)30 to 23 Exponent, biased by 12722 to 0 Fraction f of the number 1.f

Maximum and Minimum Double-Precision Values:

and return the maximum and minimum values that you can represent with the double data typeconversion function: single

Page 32: Matlab Course Session1 Introduction CUR

complex

Complex numbers consist of two separate parts: a real part and an imaginary part. The basic imaginary unit is equal to the square root of -1. represented by: i or jx = 2 + 3i;Another way use the complex function.x = rand(3) * 5;y = rand(3) * -8;z = complex(x, y)

Separate a complex number into its real and imaginary parts using the real and imag functions:zr = real(z);zi = imag(z);

Infinity and NaNInfinity

special value inf. results from operations like division by zero and overflow.Use the isinf function to verify that x is positive or negative infinity:

NaNvalues that are not real or complex numbersNaN: Not a Number. 0/0 and inf/inf result in NaNUse the isnan function to verify that x is NaN:Logical Operations on NaN. Because two NaNs are not equal to each other, logical operations involving NaN always return false, except for a test for inequality

x = 1/0x =

Infx = 1.e1000x =

Infx = exp(1000)x =

Infx = log(0)x =

-Inf

x = log(0); isinf(x) ans = 1

x = 7i/0 x = NaN + Infi

x = log(0); isnan(x) ans = 1

Page 33: Matlab Course Session1 Introduction CUR

MATLABarrays: creation

Topics

Creatinghow to build an array in a fast waymanual entering the elements:linspace, logspacespecial functions, special matrices

IndexingHow to select elements

ArraysCreation_2

Page 34: Matlab Course Session1 Introduction CUR

Search for Creating and Concatenating MatricesMatrices and ArraysMatrix IndexingElementary matrices

Help

ArraysCreation_4

Matlab Arrays

fundamental data structure is the arrayMatlab considers each variable to be a matrix and "knows" how big it is.

are programmed to deal with matrices when required. The Matlab environment handles much of the bothersome housekeeping that makes all this possible.

Page 35: Matlab Course Session1 Introduction CUR

ArraysCreation_5

Basic Concepts

Scalars: magnitude only

Vectors: magnitude AND direction

Arrays: can be 2D or higher dimension

x, mass, color, 13.451

1 1 2 2 3 3 4 4

12.74 5.234

n n

force i jH a i a i a i a i a i

r rr r r r r r

L

11 12 13 14

21 22 23 24

31 32 33 34

ijk

a a a aA a a a a

a a a a

R r

ArraysCreation_6

Creating Arrays

Different ways:

specify each element explicitly, use the colon : operator, use the commands linspace or logspace

elementary (built-in) arraysThe Matlab arrays are indexed as: A(row,column)

Page 36: Matlab Course Session1 Introduction CUR

Creating Arrays

Create an array: use the square brackets [ ]Specify each element explicitlyNumbers (or variables) inside the brackets can be separated by blanks, commas or semicolons

blank or comma separator: separate elements in a rowsemicolon: separate rows

» a = [1 2 3]a =

1 2 3» b = [11, 2, 3]b =

11 2 3» c = [1;2;3]c =

123

ArraysCreation_7

always refer to rows first and columns second. 4-by-3>> A = [1 3 5 ; 2 4 1 ; 3 3 3 ; 2 1 9]

A =

1 3 5

2 4 1

3 3 3

2 1 9

create an empty matrix.>> D = []

D =

[]

Creating Arrays

Page 37: Matlab Course Session1 Introduction CUR

ArraysCreation_9

Creating Arrays: Colon Operator

Create vectors, array subscripting, and for iterationsThe colon (:) is one of the most useful operators in Matlab. from_, to _, in increments of_The colon operator uses the following rules to create regularly spaced vectors:

j:k is the same as [j,j+1,...,k]j:k is empty if j > kj:i:k is the same as [j,j+i,j+2i, ...,k]j:i:k is empty if i > 0 and j > k or if i < 0 and j < k

ArraysCreation_10

Example» D = 1:4D =

1 2 3 4» E = 1:0.3:2E =

1.0000 1.3000 1.6000 1.9000

» dd =

1 2 311 2 31 2 3

» d(2,:)ans =

11 2 3» d(:,1)ans =

1111

» d(:)ans =

1111222333

» d(2:3)ans =

11 1» d(8:9)ans =

3 3» d(end:-1:6)ans =

3 3 3 2

Page 38: Matlab Course Session1 Introduction CUR

ArraysCreation_11

Creating Arrays

linspacesyntax: x = linspace(first, last, n)creates linearly spaced row vector starting with first, ending at last , having n elements

logspacesyntax: x = linspace(first, last, n)creates logarithmically spaced row vector starting with 10first, ending at 10last , having n elements

ArraysCreation_12

Creating Arrays

Matlab provides functions for creating standard arrays.

>> help elmatElementary matrices and matrix manipulation.

Elementary matrices.zeros - Zeros array.ones - Ones array.eye - Identity matrix.repmat - Replicate and tile array.rand - Uniformly distributed random numbers.randn - Normally distributed random numbers.linspace - Linearly spaced vector.logspace - Logarithmically spaced vector.freqspace - Frequency spacing for frequency response.meshgrid - X and Y arrays for 3-D plots.accumarray - Construct an array with accumulation.: - Regularly spaced vector and index into matrix.

Page 39: Matlab Course Session1 Introduction CUR

ArraysCreation_13

Examples>> ones(3)

ans =

1 1 11 1 11 1 1

>> zeros(2,5)

ans =

0 0 0 0 00 0 0 0 0

>> eye(3)

ans =

1 0 00 1 00 0 1

>> rand(1,5)

ans =

0.9501 0.2311 0.6068 0.4860 0.8913

>> randn(3,2)ans =

-0.4326 0.2877-1.6656 -1.14650.1253 1.1909

>> a=1:4a =

1 2 3 4>> diag(a)ans =

1 0 0 00 2 0 00 0 3 00 0 0 4

>> diag(a,-2)ans =

0 0 0 0 0 00 0 0 0 0 01 0 0 0 0 00 2 0 0 0 00 0 3 0 0 00 0 0 4 0 0

determine the size of a matrix by using the size()command

>> A = rand(3)

A =

0.8147 0.9134 0.2785

0.9058 0.6324 0.5469

0.1270 0.0975 0.9575

>> size(A)

ans =

3 3

>> [nrows,ncols] = size(A)

nrows =

3

ncols =

3

Size of a Matrix

Page 40: Matlab Course Session1 Introduction CUR

numel() command. >> n = numel(A)

n =

9

length() command (vector)the statement length(X) is equivalent to max(size(X))

>> length(A)

ans =

3

Number of Elements

A m-by-n matrix can be transposed into a n-by-m matrix by using the transpose operator '.

>> A = [1 2 3 4 ; 5 6 7 9]

A =

1 2 3 4

5 6 7 9

B =

1 5

2 6

3 7

4 9

Transposing a Matrix

Page 41: Matlab Course Session1 Introduction CUR

Matrices can be concatenated by enclosing them inside of square brackets and using either a space or semicolon to specify the dimension. Care must be taken that the matrices are of the right size.

>> A = [[1 2 3],rand(1,3)]

A =

1.0000 2.0000 3.0000 0.9649 0.1576 0.9706

>> B = [A;A]

B =

1.0000 2.0000 3.0000 0.9649 0.1576 0.9706

1.0000 2.0000 3.0000 0.9649 0.1576 0.9706

Concatenating Matrices

ArraysCreation_18

Repeating Arrays

reshapesyntax: B = reshape(A,m,n)returns the m-by-n matrix B whose elements are taken columnwise from A. An error results if A does not have m*n elements.

repmatsyntax B = repmat(A,m,n) creates a large matrix B consisting of an m-by-n tiling of copies of A. repmat(A,n) creates an n-by-n tiling.

Page 42: Matlab Course Session1 Introduction CUR

ReshapingreshapeB = reshape(A,m,n)returns the m-by-n matrix B whose elements are taken columnwise from A. An error results if A does not have m*n elements.

>> x = 1:9

x =

1 2 3 4 5 6 7 8 9

>> reshape(x,3,3)

ans =

1 4 72 5 83 6 9

ArraysCreation_20

More functionsFunction Description

[a,b] or [a;b]

Create a matrix from specified elements, or concatenate matrices together.

accumarray Construct a matrix using accumulation. blkdiag Construct a block diagonal matrix. cat Concatenate matrices along the specified dimension. diag Create a diagonal matrix from a vector. horzcat Concatenate matrices horizontally. magic Create a square matrix with rows, columns, and diagonals that add up to the same

number. ones Create a matrix of all ones. rand Create a matrix of uniformly distributed random numbers. repmat Create a new matrix by replicating or tiling another. vertcat Concatenate two or more matrices vertically. zeros Create a matrix of all zeros.

Page 43: Matlab Course Session1 Introduction CUR

Concatenate

catConcatenate arrays Syntax

C = cat(dim,A,B)C = cat(dim,A1,A2,A3,A4...)

C = cat(dim,A,B) concatenates the arrays A and B along dim. C = cat(dim,A1,A2,A3,A4,...)concatenates all the input arrays (A1, A2, A3, A4, and so on) along dim. cat(2,A,B) is the same as [A,B]cat(1,A,B) is the same as [A;B]

Extract individual entries by specifying the indices inside round brackets (). extract several entries at once by specifying

a matrix, use the : operator to extract all entries along a certain dimension.

Indexing

Page 44: Matlab Course Session1 Introduction CUR

A = rand(5)

A =

0.9572 0.9157 0.8491 0.3922 0.2769

0.4854 0.7922 0.9340 0.6555 0.0462

0.8003 0.9595 0.6787 0.1712 0.0971

0.1419 0.6557 0.7577 0.7060 0.8235

0.4218 0.0357 0.7431 0.0318 0.6948

>> A1=A(3,5)

A1 =

0.0971

>> A2 = A([1, 3], 5)

A2 =

0.2769

0.0971

>> A3 = A(:,1)

A3 =

0.9572

0.4854

0.8003

0.1419

0.4218

Indexing: example

Assignment operations follows the same rules as indexing and then specify the new values on the right hand side. The right must be either a scalar value, or a matrix with the same dimensions as the resulting indexed matrix on the left. Matlab automatically expands scalar values on the right to the correct size

Assignment of elements

Page 45: Matlab Course Session1 Introduction CUR

>> A = ones(3,5)

A =

1 1 1 1 1

1 1 1 1 1

1 1 1 1 1

>> A(3,2) = 5

A =

1 1 1 1 1

1 1 1 1 1

1 5 1 1 1

>> A(:,1:3:end) = 8

A =

8 1 1 8 1

8 1 1 8 1

8 5 1 8 1

Assigning [] deletes the corresponding entries from the matrix. Only deletions that result in a rectangular matrix are allowed.

A =

8 1 1 8 1

8 1 1 8 1

8 5 1 8 1

>> A(2,1)=[]

??? Subscripted assignment dimension mismatch.

>> A(2,:)=[]

A =

8 1 1 8 1

8 5 1 8 1

Deletion

Page 46: Matlab Course Session1 Introduction CUR

When the indices in an assignment operation exceed the size of the matrix, the matrix will be expandedNo error message!Be careful!

>> A = magic(3)

A =

8 1 6

3 5 7

4 9 2

>> A(5,7) = 99

A =

8 1 6 0 0 0 0

3 5 7 0 0 0 0

4 9 2 0 0 0 0

0 0 0 0 0 0 0

0 0 0 0 0 0 99

Expansion

ArraysCreation_28

Summary

manual entering the elements:linspace, logspacespecial functions, special matrices

ex.: demo_array_creation

Page 47: Matlab Course Session1 Introduction CUR

MATLABarray operations

ArraysOperations_2

Topics

Mathematical operationsManipulationSorting and searchingMore built-in manipulationMultidimensional arrays

Page 48: Matlab Course Session1 Introduction CUR

Help

Search forArithmetic operatorsArray operators

ArraysOperations_4

Basic Matrix Operations

Page 49: Matlab Course Session1 Introduction CUR

ArraysOperations_5

Dot (Array) Operations

ArraysOperations_6

Scalar-Array Mathematics

Addition, subtraction, multiplication, and division of an arrayby a scalar applies the operation to all elements of the array.

>> g = [1 2 3 4; 5 6 7 8]

g =

1 2 3 45 6 7 8

>> g-2

ans =

-1 0 1 23 4 5 6

>> 2*g-1

ans =

1 3 5 79 11 13 15

>> 3*g/5+4

ans =

4.6000 5.2000 5.8000 6.40007.0000 7.6000 8.2000 8.8000

Page 50: Matlab Course Session1 Introduction CUR

ArraysOperations_7

Array-Array Mathematics

Mathematical operations between arrays are not so simple as those between scalars and arrays

Addition/subtraction: C=A+Bwhere cij = aij+bij

Multiplication/division: C=A .* Bwhere cij = aij*bij

Exponentiation: C=A .^ xwhere cij = aij

x

Same order of precedence rules as under basic scalar operations

ArraysOperations_8

Array-Array Mathematics

Arithmetic operations on arrays are just like the same operations for scalars but they are carried out on an element-by-element basis.

the dot (.) before the operator indicates an array operator; it is needed only if the meaning cannot be automatically inferred.when combining arrays, make sure they all have the same dimensionsapplies to vectors, 2D arrays, multi-dimensional arrays

Page 51: Matlab Course Session1 Introduction CUR

ArraysOperations_9

Example>> g

g =

1 2 3 45 6 7 89 10 11 12

>> h

h =

1 1 1 12 2 2 23 3 3 3

>>

>> g + h

ans =

2 3 4 57 8 9 1012 13 14 15

>> 2*g-h

ans =

1 3 5 78 10 12 1415 17 19 21

ArraysOperations_10

Example>> g*h??? Error using ==> mtimesInner matrix dimensions

must agree.

>> g.*h

ans =

1 2 3 410 12 14 1627 30 33 36

» g * h'

ans =

10 20 3026 52 7842 84 126

» g' * h

ans =

38 38 38 3844 44 44 4450 50 50 5056 56 56 56

Page 52: Matlab Course Session1 Introduction CUR

ArraysOperations_11

More on Array Operations

Most Matlab functions will work equally well with both scalars and arrays (of any dimension)

>> A=[1 2 3 4 5];>> sin(A)ans =

0.8415 0.9093 0.1411 -0.7568 -0.9589

>> sqrt(A)ans =1.0000 1.4142 1.7321 2.0000 2.2361

ArraysOperations_12

>> A = [1:3;4:6;7:9]A =

1 2 34 5 67 8 9

>> mean(A)ans =

4 5 6

>> sum(A)ans =

12 15 18

Most common functions operate on columns by default

Page 53: Matlab Course Session1 Introduction CUR

ArraysOperations_13

Reversing

reversing rows and columns

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

a =

1 2 34 5 67 8 9

>> b = a(end:-1:1)

b =

9 6 3 8 5 2 7 4 1

>> b = a(end:-1:1,1:3)

b =

7 8 94 5 61 2 3

ArraysOperations_14

SortingSort array elements in ascending or descending order Syntax

B = sort(A)B = sort(A,dim)B = sort(...,mode)[B,IX] = sort(...)

B = sort(A) sorts the elements along different dimensions of an array, and arranges those elements in ascending order. If A is a ...sort(A) ...

Vector: Sorts the elements of A.Matrix: Sorts each column of A.

>> a = randperm(8)a =

8 2 7 4 3 6 5 1

>> b = sort(a)b =

1 2 3 4 5 6 7 8

>> AA =

3 7 50 4 2

>> sort(A)ans =

0 4 23 7 5

>> sort(A,1)ans =

0 4 23 7 5

>> sort(A,2)ans =

3 5 70 2 4

Page 54: Matlab Course Session1 Introduction CUR

ArraysOperations_15

Sorting

B = sort(A,dim) sorts the elements along the dimension of A specified by a scalar dim. If dim is a vector, sort works iteratively on the specified dimensions. Thus, sort(A,[1 2]) is equivalent to sort(sort(A,2),1). B = sort(...,mode)sorts the elements in the specified direction, depending on the value of mode.

Ascending order (default)

Descending order

a =

7 8 2 3 6 4 1 5

>> [xs indx] = sort(a, 'descend')

xs =

8 7 6 5 4 3 2 1

indx =

2 1 5 8 6 4 3 7

ArraysOperations_16

Searching

The find members of an array that meet a criteria. The result of the command is a list of element numbers.

>> grades = -5: 10: 105grades =

-5 5 15 25 35 45 55 65 75 85 95 105

>> set1 = find(grades>100 | grades <0)

set1 =1 12

>> set2 = find(grades>=0 & grades <=100)

set2 =2 3 4 5 6

7 8 9 10 11>> grades(set1)ans =

-5 105>> grades(set2)ans =

5 15 25 35 45 55 65 75 85 95

Page 55: Matlab Course Session1 Introduction CUR

ArraysOperations_17

SearchingThe find works also in 2 dimensionsmore specificfind(X, n):start at the first element returns up to n indices where X is true

start at the last element returns up to n indices where X is true

>> a = 1:9a =

1 2 3 4 5 6 7 8 9

>> a = reshape(a,3,3)'a =

1 2 34 5 67 8 9

>> [ii,ij]=find(a>5)ii =

3323

ij =1233

>> k = find(a>5)k =

3689

>> l = find(a>5, 2, 'last')l =

89

ArraysOperations_18

Built-in functions

help elmat: Matrix manipulation.fliplr: Flip matrix in left/right direction.flipud: Flip matrix in up/down direction.rot90: Rotate matrix 90 degrees.rot90(a,n): Rotate n-timescircshift(A,shiftsize)circularly shifts the values in the array, A, by shiftsize elements.

shiftsize is a vector of integer scalars where the n-th element specifies the shift amount for the n-th dimension of array A. positive shiftsize: shift down (or to the right). negative shiftsize: shift up (or to the left). 0: no shift

a =1 2 34 5 67 8 9

>> flipud(a)ans =

7 8 94 5 61 2 3

>> fliplr(a)ans =

3 2 16 5 49 8 7

>> rot90(a)ans =

3 6 92 5 81 4 7

>> rot90(a,2)ans =

9 8 76 5 43 2 1

>> circshift(a,[-1 1])ans =

6 4 59 7 83 1 2

Page 56: Matlab Course Session1 Introduction CUR

ArraysOperations_19

Built-in functions

diag - Diagonal matrices and diagonals of matrix.tril - Extract lower triangular part.triu - Extract upper triangular part.

a =1 2 34 5 67 8 9

>> diag(a)ans =

159

>> diag(ans)ans =

1 0 00 5 00 0 9

>> triu(a)ans =

1 2 30 5 60 0 9

>> tril(a)ans =

1 0 04 5 07 8 9

Multidimensional Arrays

arrays with more than 2 subscripts Examples:

3D physical data sequence of matrices samples of a time-dependent 2D or 3D data

To make multidimensional array:>> a = [2 4 6; 7 8 9; 1 2 3]>> a(:,:,2)= [1 11 12; 0 1 2; 4 5 6]When you add elements and expand the sizeUnspecified elements are set to zero>> a(:,:,4) = [ 1 1 1; 2 2 2; 3 3 3]

Page 57: Matlab Course Session1 Introduction CUR

ArraysOperations_21

Summary

mathematics: matrix versus arrayssorting and searching functionsmultidimensional arrays

ArraysOperations_22

Functions & Arrays

Page 58: Matlab Course Session1 Introduction CUR

ArraysOperations_23

Functions & Arrays

ArraysOperations_24

Functions & Arrays

Page 59: Matlab Course Session1 Introduction CUR

ArraysOperations_25

Functions on matrix

MATLABrelational and logicaloperators

Page 60: Matlab Course Session1 Introduction CUR

LogicalRelational_2

Topics

Use relational operators to test two valuesWork with values of true and falseCompare relationships using logical operatorsAnalyze the precedence of operators

Help

Search forLogical operatorRelational operator

Page 61: Matlab Course Session1 Introduction CUR

LogicalRelational_4

Logical Expressions

Why?What if you want to choose between two (or more) possible programming paths?Use a logical condition to decide what to do nextRequires logical operators

LogicalRelational_5

Recall: double data type

Contains numeric data.Arithmetic operators:

+, - , *, .*, / , ./, ^, .^Rules of precedence for arithmetic operators:

1. Parentheses2. Exponents3. Multiplication / Division4. Addition/Subtraction

combine arithmetic operators with parentheses as

Page 62: Matlab Course Session1 Introduction CUR

LogicalRelational_6

Relational OperatorsUsed to compare two numeric valuesReturns a value of trueor false. In Matlab,

1 = true (any non-zero number);0 = false;Logical data type

Relational Operators:< less than<= less than or equal to> greater than>= greater than or equal to== equals to~ = not equal to

Operator Precedence

1. Parentheses ()2. Transpose (.'), power (.^), complex conjugate transpose ('), matrix

power (^)3. Unary plus (+), unary minus (-), logical negation (~)4. Multiplication (.*), right division (./), left division (.\), matrix

multiplication (*), matrix right division (/), matrix left division (\)5. Addition (+), subtraction (-)6. Colon operator (:)7. Less than (<), less than or equal to (<=), greater than (>), greater

than or equal to (>=), equal to (==), not equal to (~=)8. Element-wise AND (&)9. Element-wise OR (|)10. Short-circuit AND (&&)11. Short-circuit OR (||)

Page 63: Matlab Course Session1 Introduction CUR

LogicalRelational_8

Operator Precedence

When relational operators are present:All arithmetic operations are performed first (in their particular order)Then the relational operators are evaluated.

Example 1(2*3) > (4+1);

- The multiplication and addition are first: 6 > 5

- The relational operator is evaluated:6 is greater than 5, so this returns 1 (true)

- Result is the numeric value, 1, is returned

Relational Operators: array

The Matlab relational operators compare corresponding elements of arrays with equal dimensions. Relational operators always operate element-by-element. exampleA = [2 7 6;9 0 5;3 0.5 6];B = [8 7 0;3 2 5;4 -1 7];A == Bans =0 1 00 0 10 0 0

Page 64: Matlab Course Session1 Introduction CUR

LogicalRelational_10

Relational Operators

vectors and rectangular arrays, both operands must be the same size unless one is a scalar. one operand is a scalar and the other is not, Matlab tests the scalar against every element of the other operand.result:

relation is true receive logical 1relation is false receive logical 0.on array manipulations: result is a logical array

LogicalRelational_11

Logical OperatorsLogical Operators:

Provide a way to combine results from Relational Expressions or between logical valuesReturns a value of true or false.

Evaluated after all other operators have been performed.

Logical Operators& AND| OR~ NOTxor XOR

Page 65: Matlab Course Session1 Introduction CUR

LogicalRelational_12

Logical Operators

AND: &Returns true if two expressions being compared are true.Returns false if any of the two is false.

OR: |Returns true if any of the two expressions is true.Returns false only if the two are both false.

NOT: ~Returns true if the single expression is false.Returns false if the single expression is true.

Examples:

Assume: a=7; b=4; c=3;~(a==3*b)

Evaluates: 3*b = 12Evaluates: (a==12) and result is falseEvaluates ~(false) and result is trueReturns ans = 1 (true)

a > 5 & b > 5Evaluates (a>5) and (b>5) separately. One returns true, the other returns false.Since both are not true, the expression returns false.

a == 7 | b ==1Evaluates (a==7) and (b==1) separatelyOne returns true and the other returns falseSince at least one is true, the expression returns true

Page 66: Matlab Course Session1 Introduction CUR

LogicalRelational_14

Logical Operators: more

3 types of logical operators and functions:Element-wise operate on corresponding elements of logical arrays.Bit-wise operate on corresponding bits of integer values or arrays.Short-circuit operate on scalar, logical expressions.

logical operators work also on arrays

LogicalRelational_15

Element-Wise Operators and Functions

The following logical operators and functions perform element-wise logical operations on their inputs to produce a like-sized output array.

examplesA = [0 1 1 0 1];

B = [1 1 0 0 1];

Logical Operators: more

Page 67: Matlab Course Session1 Introduction CUR

LogicalRelational_16

Logical Operators: more

Bit-Wise Functionsbit-wise logical operations on nonnegative integer inputs. inputs may be scalar or in arrays. examplesA = 28; % binary 11100B = 21; % binary 10101

LogicalRelational_17

Logical Operators: more

Short-Circuit OperatorsThe following operators perform AND and OR operations on logical expressions containing scalar values. They are short-circuit operators in that they evaluatetheir second operand only when the result is not fully determined by the first operand.

Page 68: Matlab Course Session1 Introduction CUR

LogicalRelational_18

Example

example: logical_ex_1.mx=5;

y=10;

disp(x <y)

disp(x<=y)

disp(x==y)

disp((x>10) & (y<30))

disp((x>2) | (y > 89))

A Common Mistake

You will not get into trouble if you make sure that Logical Operators are always used with logical values. A > B & C (where A=10, B=5, C=0)

This looks like a relational expression asking if A is greater than both B and C which should be true for these values.Here is what really happens:

A>B is evaluated as trueresult (true) is logically ANDed with CSince Matlab treats any zero numeric as false, it will mistakenly treat C as a logical and the result will be false

The CORRECT form is: (A > B) & (A > C)and this returns atrue result.NOTE: subtle problems can arise because Matlab uses numerics to represent logical values. Other languages are stricter in this area

Page 69: Matlab Course Session1 Introduction CUR

Logical Values in Assignments

True/False values can be assigned to variables

The variables will be assigned the value that is returned from relational and/or logical operators.The variables will thus have a value of 1 or 0.Example: a=7; b=4; c=3;

x = a > 2;Then x = 1;

y = b==5;Y will be equal to 0.

This can be very useful in Matlab but it is actually quite DANGEROUS

LogicalRelational_21

More Examples

a=6; b=10; c=-2;

Try the following examples without the use of Matlab:X1 = abs(c)>3 & c<(b-a) & b+a > 3

X2 = (b==10) | (a< 4)

X3 = a.*5 >= b.*3 & c < a

Advice: use parentheses to make expression more readable (see example for X2).

Page 70: Matlab Course Session1 Introduction CUR

LogicalRelational_22

Practice

Evaluate the following:

a = 4; b = 20; c = 12; d = 5;

One = a>4 & b==20

Two = b<40 | c>10

Three = d.*c > a.*b

Four = b.*3<= 100 & d<10 & a.*d==b

LogicalRelational_23

More Practice

When comparing vectors, the operator (>, <=, ~, AND, etc.) is applied element-by-element:

a = [0,2,4,2]; b = [4,1,-2,3];

What is:C = a .* b;

C = b.^2-a.*b

C = a >= b;

Advice: be careful when comparing floating point numbers because the finite precision may cause values to be slightly off

Page 71: Matlab Course Session1 Introduction CUR

LogicalRelational_24

>> B=[2:-1:-2]B = 2 1 0 -1 -2>> numerator=ones(size(B))numerator = 1 1 1 1 1>> numerator./BWarning: Divide by zero.ans = 5.0000e-001 1.0000e+000 Inf -1.0000e+000 -5.0000e-001>> B=B+(B==0)*epsB = 2.0000e+000 1.0000e+000 2.2204e-016 -1.0000e+000 -2.0000e+000>> numerator./Bans = 5.0000e-001 1.0000e+000 4.5036e+015 -1.0000e+000 -5.0000e-001

An Interesting ExampleSometimes if you have to do an array division, you may want to avoid getting inf when a value in the divisor is

Using numeric values to represent logicals can have some

Never try to use NaN in a relational or logical expression because NaN has no value and therefore could be considered to have all values!

>> nan==nanans =

0>> inf==infans =

1

aa = [ 10 16 16 16 17 9 11]>> aa > 15ans = 0 1 1 1 1 0 0>> aaa = ans>> aa(aaa)ans =

16 16 16 17>> aaai = uint16(aaa)aaai =

0 1 1 1 1 0 0>> aa(aaai)??? Subscript indices must either be real positive integers or logicals.

Page 72: Matlab Course Session1 Introduction CUR

LogicalRelational_26

Logical Functions

Matlab includes a large number of logical functions (functions that return a true or false result)

functions see also functions:

any( )all( )find( )

LogicalRelational_27

ages = [10 62 18 27]anyKids = any(ages <= 12)anySeniors = any(ages >=

65)anyKids =

1

anySeniors =

0

allAdults = all(ages >= 18)

noSeniors = all(ages <= 65)

allAdults =

0

noSeniors =

1

Page 73: Matlab Course Session1 Introduction CUR

Summary

Matlab can store and manipulate much more than simply numbers logical expressions on arrays

Relational Operators:< less than<= less than or equal to> greater than>= greater than or equal

to== equals to~ = not equal to

Logical Operators& AND| OR~ NOTxor XOR

MATLABinteractive plotting

Page 74: Matlab Course Session1 Introduction CUR

GraphicsInteractive_2

Topics

Create various types of graphsSelect variables to plot directly from a workspace browserEasily create and manipulate subplots in the figureAdd annotations such as arrows, lines, and textSet properties on graphics objects

GraphicsInteractive_3

plotting your dataSteps in plotting your dataIf only previewing or exploring data, steps 1 and 2 may be all you need.If creating presentation graphics, you may want to finetune your graph by positioning it on the page, setting line styles and colors, adding annotations, etc.

Prepare your data

Call elementary plottingfunction

Select line and marker Characteristics

Set axis limits, tickmarks, and grid lines marks, and grid lines

Annotate the graphwith axis labels, legend and text

Page 75: Matlab Course Session1 Introduction CUR

GraphicsInteractive_4

interactive plot editing

Matlab supports two ways to edit the plots you create:Using the mouse to select and edit objects interactively Using Matlab functions at the command line or in an M-file

Interactive mode: perform point-and-click editing of graphsmodify the appearance of a graphics object by double-clicking on the object and changing the values of its propertiesaccess the properties through a gui

GraphicsInteractive_6

Plotting Tools

Start:use the plottoolscommand.from the figure toolbar -Show Plot Tools icon .

3 basic plotting toolsFigure Palette, Plot Browser, Property Editor.

Page 76: Matlab Course Session1 Introduction CUR

GraphicsInteractive_7

basic plotting tools

Figure Palette: create and arrange subplot axes, view and plot workspace variables, and add annotations. Plot Browser:

select and control the visibility of the axes or graphic objects plotted in the figure. add data to any selected axes by clicking the Add Data button.

Property Editor: set common properties of the selected object.

GraphicsInteractive_8

Figure Palette / subplots

New Subplots Add 2-D or 3-D axes to the figure.

create a grid of either 2-D or 3-D axes.click the grid icon next to the axes type. move the cursor, squares darken to indicate the layout of axes

Page 77: Matlab Course Session1 Introduction CUR

GraphicsInteractive_9

Figure Palette / variablesdisplays current workspace variables. double-clicking a variable opens that variable select a variable and right-click to display the context menu, select a graphics function to plot the variable.If the desired plotting function is not available from the context menu, you can select More Plots to display the Plot Catalog tool.

GraphicsInteractive_10

Figure Palette / annotationsAdd text, lines and arrows, rectangles, ellipses, and other annotation objects anywhere on the figureAnchor annotations to locations in data spaceAdd a legend and colorbarAdd axis labels and titlesEdit the properties of graphics objects

basic annotations in Figure Palette

Page 78: Matlab Course Session1 Introduction CUR

GraphicsInteractive_11

Figure Palette / annotationsAnnotation features are available from the Insert menu.

Select Plot Edit Toolbar from the View menu to display the toolbar.

GraphicsInteractive_12

Plot Browser

provides a legend of all the graphs in the figure. It lists each axes and the objects (lines, surfaces, etc.) used to create the graph.

Page 79: Matlab Course Session1 Introduction CUR

GraphicsInteractive_13

Plot Browser

Controlling Object Visibilitycheck box next to each item in the Plot Browser controls

want to display. Deleting Objectsdelete any selected item in the Plot Browser by selecting Delete from the right-click context menu.Adding Data to Axesmechanism to add data to axes:

Select a 2-D or 3-D axes from the New Subplots subpanel.After creating the axes, select it in the Plot Browser panel to enable the Add Data button at the bottom of the panel.Click the Add Data button to display the Add Data to Axes dialog.

GraphicsInteractive_14

Property Editor

properties. when no object is selected, the Property Editor displays

Ways to Display the Property EditorDouble-click an object when plot edit mode is enabled.Select an object and right-click to display its context menu, then select Properties.Select Property Editor from the View menu.

Page 80: Matlab Course Session1 Introduction CUR

GraphicsInteractive_15

Property EditorProperty Editor enables you to change the most commonly used objectselect an object, the property editor changes accordinglyto access all object properties, use the Property Inspector.

GraphicsInteractive_16

Exporting using menus

in a format that can be opened during another Matlab session

Select Save from the figure window File menu or click the Save button on the toolbar. If this is the first time you are saving the file, the Save As dialog box appears.Make sure that the Save as type is Fig-File.Specify the name you want assigned to the figure file.Click OK.

Page 81: Matlab Course Session1 Introduction CUR

GraphicsInteractive_17

Saving Your Work

in a format that can be used by other applications

Select the format from the list of formats in the Save as type drop-down menu. This selects the format of the exported file and adds the standard filename extension given to files of that type.Enter the name you want to give the file, less the extension.Click Save.

GraphicsInteractive_18

Generate codegenerate code to reproduce this graph by selecting Generate M-File from the Figure menu. Matlab creates a function that recreates the graph and opens the generated M-File in the editor.This feature is particularly useful for capturing property settings and other modifications made using the plot tools GUI.Data ArgumentsGenerated functions do not store the data necessary to recreate the graph. You must supply the data argumentsLimitationsAttempting to generate code for graphs containing a large number of graphics objects (e.g., greater than 20 plotted lines) might be impractical.

Page 82: Matlab Course Session1 Introduction CUR

MATLABbasic mathematical applictions

basicMath_2

Topics

basic data analysismean, standard deviation, ....

interpolationcurve fittingpolynomialssolving linear equationsfunction optimisation

Page 83: Matlab Course Session1 Introduction CUR

Import Wizard for data importFile-

File input with loadB =

File output with savedataout -ascii

basicMath_4

Data Analysis functions

help datafun

Search for:Data analysis

Minimum of in a Data Set >> min(v)Maximum of in a Data Set >> max(v)Sum of a Data Set >> sum(v)Standard Deviation >> std(v)Mean of a Data Set >> mean(v)Sort a Data Set in ascending order>> sort(v)

remark:MATLAB considers data sets stored in column-oriented arrays

Page 84: Matlab Course Session1 Introduction CUR

basicMath_5

mean>> temp3city =

12 8 1815 9 2212 5 1914 8 2312 6 2211 9 1915 9 158 10 20

19 7 1812 7 1814 10 1911 8 179 7 238 8 19

15 8 188 9 20

10 7 1712 7 229 8 19

12 8 2112 8 2010 9 1713 12 189 10 20

10 6 2214 7 2112 5 2213 7 1815 10 2313 11 2412 12 22

vectors: mean(X) is the mean value of the elements in X. matrices, mean(X) is a row vector containing the mean value of each column. mean(X,DIM) takes the mean along the dimension DIM of X.

>> mean(temp3city, 1)

ans =

11.9677 8.2258 19.8710

>> mean(temp3city, 2)

ans =

12.6667

15.3333

12.0000

15.0000

13.3333

13.0000

13.0000

12.6667

14.6667

12.3333

14.3333

12.0000

13.0000

11.6667

13.6667

12.3333

11.3333

13.6667

12.0000

13.6667

13.3333

12.0000

14.3333

13.0000

basicMath_6

median

median(x) same as mean(x), only returns the median value.

>> X = [0 1 2; 3 4 5]

X =

0 1 23 4 5

>> median(X,1)

ans =

1.5000 2.5000 3.5000

>> median(X,2)

ans =

14

Page 85: Matlab Course Session1 Introduction CUR

basicMath_7

stdStandard deviation

There are two common textbook definitions for the standard deviation s of a data vector X. Def_1

Def_2

s = std(X)X is a vector, returns the standard deviation using (1) above. X is a matrix, std(X) returns a row vector containing the standard deviation of the elements of each column of X. s = std(X,flag) flag = 0, is the same as std(X). flag = 1, std(X,1) returns the standard deviation using (2) s = std(X,flag,dim) computes the standard deviations along the dimension of X specified by scalar dim. Set flag to 0 to normalize Y by n-1; set flag to 1 to normalize by n

122

1

11

n

ii

s x xn

122

1

1 n

ii

s x xn

>> dat =

12 8 1815 9 2212 5 1914 8 2312 6 2211 9 1915 9 158 10 20

19 7 1812 7 1814 10 1911 8 179 7 238 8 19

15 8 188 9 20

10 7 1712 7 229 8 19

12 8 2112 8 2010 9 1713 12 189 10 20

10 6 2214 7 2112 5 2213 7 1815 10 2313 11 2412 12 22

>> std(dat)

ans =

2.5098 1.7646 2.2322

>> std(dat,1)

ans =

2.4690 1.7360 2.1959

>> std(dat,0,2)

ans =

5.0332

6.5064

7.0000

7.5498

8.0829

5.2915

3.4641

6.4291

6.6583

5.5076

4.5092

4.5826

8.7178

6.3509

5.1316

6.6583

5.1316

7.6376

4.3589

...

max (min)

max Largest component.vectors: MAX(X) is the largest element in X. matrices: MAX(X) is a row vector containing the maximum element from each column. [Y,I] = max(X) returns the indices of the maximum values in vector I.max(X,Y) returns an array the same size as X and Y with the largest elements taken from X or Y. Either one can be a scalar.[Y,I] = max(X,[],DIM) operates along the dimension DIM.

>> dat =

12 8 1815 9 2212 5 1914 8 2312 6 2211 9 1915 9 158 10 20

19 7 1812 7 1814 10 1911 8 179 7 238 8 19

15 8 188 9 20

10 7 1712 7 229 8 19

12 8 2112 8 2010 9 1713 12 189 10 20

10 6 2214 7 2112 5 2213 7 1815 10 2313 11 2412 12 22

>> max(dat)

ans =

19 12 24

>> max(max(dat))

ans =

24

>> max(dat(:))

ans =

24

>> [Y, I] = max(dat)

Y =

19 12 24

I =

9 23 30

Page 86: Matlab Course Session1 Introduction CUR

basicMath_9

diffY = diff(X) calculates differences between adjacent elements of X. vector: returns a vector, 1 element shorter than X, of differences between adjacent elements: [X(2)-X(1) X(3)-X(2) ... X(n)-X(n-1)]matrix, then diff(X) returns a matrix of row differences: [X(2:m,:)-X(1:m-1,:)]Y = diff(X,n) applies diff recursively n times, diff(X,2) is same as diff(diff(X)). Y = diff(X,n,dim) is the nth difference function calculated along the dimension specified by scalar dim. If order n equals or exceeds the length of dimension dim, diff returns an empty array.

>> YY =

19 12 24>> diff(Y)ans =

-7 12>> diff(Y,2)ans =

19>> diff(dat)ans =

3 1 4-3 -4 -32 3 4-2 -2 -1-1 3 -34 0 -4-7 1 511 -3 -2-7 0 02 3 1-3 -2 -2-2 -1 6-1 1 -47 0 -1-7 1 22 -2 -32 0 5-3 1 -33 0 20 0 -1-2 1 -33 3 1

-4 -2 21 -4 24 1 -1-2 -2 11 2 -42 3 5-2 1 1-1 1 -2

>> dat =

12 8 1815 9 2212 5 1914 8 2312 6 2211 9 1915 9 158 10 20

19 7 1812 7 1814 10 1911 8 179 7 238 8 19

15 8 188 9 20

10 7 1712 7 229 8 19

12 8 2112 8 2010 9 1713 12 189 10 20

10 6 2214 7 2112 5 2213 7 1815 10 2313 11 2412 12 22

filter

filters a data sequence using a digital filter y = filter(b,a,X) filters the data in vector X with the filter described by numerator coefficient vector b and denominator coefficient vector a. If X is a matrix, filter operates on the columns of X. Algorithm: y(n) = b(1)*x(n) + b(2)*x(n-1) + ... + b(nb+1)*x(n-nb)

- a(2)*y(n-1) - ... - a(na+1)*y(n-na)more detail in help filter

Page 87: Matlab Course Session1 Introduction CUR

basicMath_11

filter>> time_series = [12 17 10 22 15 11 18 27 14]

time_series =

12 17 10 22 15 11 18 27 14

>> a = [.25 .50 .25]

a =

0.2500 0.5000 0.2500

>> filter(a,1,time_series)

ans =

Columns 1 through 8

3.0000 10.2500 14.0000 14.7500 17.2500 15.7500 13.7500 18.5000

Column 9

21.5000

basicMath_12

more functions

corrcoef: correlation coeeficientscov: covariance matrixcumprod: cumulative product of elementscumsum: cumulative sum of elementshistc(x, edges): histogram count and bin locations using bins marked by edgesprod: product of elementssort: sorts in ascending or descending ordersortrows: sort rows in ascending ordersum: sum of elementsdemo_basic_DataAnalysis

Page 88: Matlab Course Session1 Introduction CUR

Fitting/interpolation

Tips:Check Cleve website

www.mathworks.com/moler

Help Search in helpdesk data analysisInterpolationfitting

BasicDataAnalysis_13

Interpolation

When you take data, how do you predict what other data points might be?Two techniques are :

Linear Interpolation

Cubic Spline Interpolation

Extrapolation

Page 89: Matlab Course Session1 Introduction CUR

BasicDataAnalysis_15

Interpolation

YI = interp1(X,Y,XI) interpolates to find YI, the values of the underlying function Y at the points in the vector or array XI

Finding values between data points linear interpolation (default)cubic splines...yi = interp1 ( x, y, xi )Yi = interp1 ( x, y, xi, 'spline' )

demo_interp1demo_interp2demo_interp3

basicMath_16

Fitting

There is scatter in all collected dataWe can estimate what equation represents the

But there will be points that do not fall on the line we estimatemethod

method of least squaresminimize the residuals

Page 90: Matlab Course Session1 Introduction CUR

Linear regression

Linear equation that is the best fir to a set of data pointsMinimize the sum of squared distances between the line and the data pointsdemo_linreg1.m

basicMath_18

Polynomial Fit

polyfit finds the coefficients of a polynomial representing the data

squares sense) of a specified order for a given set of data. used to generate the n + 1 coefficients aj of the nth-degree polynomial used for fitting the data.

polyval: uses those coefficients to find new values of y, that correspond to the known values of x

11 0( ) n n

n n n np x a x a x a x aK

Page 91: Matlab Course Session1 Introduction CUR

basicMath_19

polyfit>> x = [0 .1 .2 .3 .4 .5 .6 .7

.8 .9 1];>> y = [-.447 1.978 3.28 6.16

7.08 7.34 7.66 9.56 9.48 9.30 11.2];

>> n = 2;>> p = polyfit(x,y,n);>> p =-9.8108 20.1293 -0.0317

xi = linspace(0,1,100);yi = polyval(p,xi);pp = polyfit(x,y,10);y10 = polyval(pp,xi); plot(x,y,'o',xi,yi,'--

',xi,y10) % plot dataxlabel('x'), ylabel('y=f(x)')title('2nd and 10th Order

Curve Fitting')

demo_polyfit

basicMath_20

built-in tool

Page 92: Matlab Course Session1 Introduction CUR

basicMath_21

polynomials

Polynomials are described by using a row vector of the coefficients of the polynomial beginning with the highest power of x and inserting zeros for

f=[9 5 3 7];g=[6 1 2];

add and subtract polynomial functions in MATLAB. To do this we must

same length:h=f+[0 g];

multiply and divide polynomials by using the conv and deconv functions y=conv(f,g)[q r]=deconv(y,f)

evaluate a polynomial at any value of x:p=[1 3 -4];x=[-5:.1:5];px=polyval(p,x);

polynomials

roots finds polynomial roots.roots( [ 1 6 11 6 ] )

ans = -3.0000

-2.0000

-1.0000

polyder(P) returns the derivative of the polynomial whose coefficients are the elements of vector P.>> polyder( [ 1 6 11 6 ] )

ans = [ 3 12 11 ]

Page 93: Matlab Course Session1 Introduction CUR

Solution?

A = [2 3; 5 4]b = [8;13]x = A\b

LinearEquations_23

1 2

1 2

2 3 85 4 13x xx x

Solution?

A = [2 3; 4 6]b = [4;7]x = A\b

LinearEquations_24

1 2

1 2

2 3 44 6 7x xx x

Page 94: Matlab Course Session1 Introduction CUR

LinearEquations_25

Simultaneous Linear EquationsBasic form:

a11x1 + a12x2 + a13x3 1nxn = b1

a21x1 + a22x2 + a23x3 2nxn = b2

an1xn + an2x2 + an3x2 nnxn = bn

Where:aij are known coefficientsxi are unknownsbi are known right hand side values

bAxor

b

bb

x

xx

aaa

aaaaaa

nnnnnn

n

n

2

1

2

1

21

22221

11211

basicMath_26

Solution of equations

2x1 +4x2-2x3=44 x1+9x2-2x3=6-2 x1-3x2+7x3=10

What is the solution?

demo_lineq3

Page 95: Matlab Course Session1 Introduction CUR

basicMath_27

The coefficient matrix A need not be square. If A is m*n, there are three cases.

m = n Square system. Seek an exact solution.

m > n Over determined system. Find a least squares solution.

m < n Underdetermined system. Find a basic solution with at most m nonzero components.

basicMath_28

Linear Equations

Set of linear equations Ax = b can be solved using the Inverse operation on A

x=inv(A)*b

Advice:Do not use this methodInefficient

Page 96: Matlab Course Session1 Introduction CUR

backslash \

MATLAB has a bunch of methods available to solve a system of linear equationsIf you desire the solution of Ax = b, then the simplest method using Matlab to find x is to set x = A\bA = [ 1 5 6; 7 9 6; 2 3 4]b = [29; 43; 20]x=A\b

Use backslash operator \ (LU decumposition + pivoting)If A is an n by m matrix and b is an p by q matrix then A\b is defined (and is calculated by Matlab) if m=p. For non-square and singular systems, the operation A\b gives the solution in the least squares sense. No error message

\ -slash operator uses a combination of numerical methods including LU decomposition.

Steps in A\bStop if successful

If A is upper or lower triangular, solve by back/forward substitution If A is permutation of triangular matrix, solve by permuted back substitution (useful for [L,U]=lu(A) since L is permuted) If A is symmetric/hermitian

Check if all diagonal elements are positive Try Cholesky, if successful solve by back substitutions

If A is Hessenberg (upper triangular plus one subdiagonal), reduce to upper triangular then solve by back substitution If A is square, factorize PA = LU and solve by back substitutions If A is not square, run Householder QR, solve least squares problem

Page 97: Matlab Course Session1 Introduction CUR

basicMath_31

Basic optimization

optimization means here: determine where a function y = f(x) takes on either specfic or extreme valuesZero findingMinimization in 1 dimension

Zero finding

fzero: Find zero of a function of one variablefind x satisfying f(x) = 0

Combination ofSecant method / quadratic fit extension of Secant methodBisection

While not universally effective, combining techniques can improve the reliability and speed of convergencefzero uses bisection to avoid large steps, other methods for fast convergencesyntax:x = fzero(fun,x0)

fun user supplied function specifying f(x)x0 is an initial guess of an x

Page 98: Matlab Course Session1 Introduction CUR

Challenges

Finding good initial valuesFor 1D functions, graphing can be an aidGraphing not always possible for some multi-D functions, or even time-consuming 1D functions

Analytic methods, if feasible, are always a better choice than numeric algorithms!demo_fzero_1

Minimization in 1 dimension

X = fminbnd(FUN,x1,x2) attempts to find a local minimizer X of the function FUN in the interval x1 < X < x2. FUN accepts scalar input X and returns a scalar function value F evaluated at X.demo_fminbnddemo_fminbnd_2

Page 99: Matlab Course Session1 Introduction CUR

Maximum?

Find maximum of:

demo_fminbnd_3

2 31 1 5

( 0.4) 0.01 ( 0.7) 0.04y

x x

Minimization in n dimensions

X = fminsearch(FUN,X0) starts at X0 and attempts to find a local minimizer X of the function FUN. FUN accepts input X and returns a scalar function value F evaluated at X. X0 can be a scalar, vector or matrix.Multidimensional unconstrained nonlinear minimization (Nelder-Mead).