Vous êtes sur la page 1sur 99

Introduction to MATLAB

Dr. Mi Sa Nguyen University of Technical Education HCM city dalat1984@yahoo.com

1 Introduction to MATLAB

What is MATLAB?

MATLAB is an abbreviation for "MATrix LABoratory" MATLAB provides a language and environment for numerical computation, data analysis, visualisation and algorithm development MATLAB provides functions that operate on

Integer, real and complex numbers Vectors and matrices Structures

1 Introduction to MATLAB

What is MATLAB?

The basic building block in MATLAB is the matrix. The fundamental data type is the array. In mathematical computations, especially those that utilize vectors and matrices, MATLAB is better in terms of ease of use, availability of built-in functions, ease of programming, and speed. There are numerous prepared commands for 2D and 3D graphics as well as for animation.

2 History of MATLAB

Cleve Moler, the chairman of the computer science department at the University of New Mexico, started developing MATLAB in the late 1970s (Fortran). Jack Little, an engineer, was exposed to it during a visit Moler made to Stanford University in 1983. He wrote MATLAB in C and founded MathWorks in 1984 to continue its development. In 2000, MATLAB was rewritten to use a newer set of libraries for matrix manipulation.
4

2 History of MATLAB
Version MATLAB 1.0 MATLAB 2 MATLAB 3 Release name Number
1984 1986 1987

Year

Release Date

Notes C for MS-DOS

MATLAB 3.5

1990

Ran on MSDOS but required at least a 386 processor . Version 3.5m required math coprocessor

MATLAB 4 MATLAB 4.2c

1992 1994
Ran on Windows 3.1. Required a math coprocessor

2 History of MATLAB
Version Release name Number 1996 Year Release Date December, 1996 May, 1997 March, 1998 January, 1999 November, 1999 November, 2000 June, 2001 MATLAB 5.0 Volume 8 MATLAB 5.1 Volume 9 MATLAB 5.1.1 R9.1 MATLAB 5.2 R10 MATLAB 5.2.1 R10.1 MATLAB 5.3 R11 MATLAB 5.3.1 R11.1 MATLAB 6.0 R12 MATLAB 6.1 R12.1 Notes Unified releases across all platforms.

1997

1998

1999

12

2000 2001

2 History of MATLAB
Version Release name Number MATLAB 6.5 R13 MATLAB 6.5.1 R13SP1 13 MATLAB 6.5.2 R13SP2 MATLAB 7 R14 MATLAB 7.0.1 R14SP1 14 MATLAB 7.0.4 R14SP2 MATLAB 7.1 R14SP3 MATLAB 7.2 R2006a 15 Year 2002 2003 Release Date July, 2002 Notes

2004

2005

MATLAB 7.3 R2006b

16

2006

June, 2004 October, 2004 March 7, 2005 September 1, 2005 March 1, 2006 September 1, 2006

2 History of MATLAB
Version Release name Number MATLAB 7.4 R2007a 17 Year Release Date March 1, 2007 Notes
Last release for Windows 2000 and Power September 1, PC Mac. 2007 License Server support for Windows Vista New ClassMarch 1, 2008 Definition Syntax. October 9, 2008

MATLAB 7.5 R2007b

18

2007

MATLAB 7.6 R2008a

19 2008

MATLAB 7.7 R2008b

20

2 History of MATLAB
Version Release name Number Year MATLAB 7.8 R2009a 21 Notes First release for 32-bit & 64-bit March 6, 2009 Microsoft Windows 7.
First release for Intel 64-bit Mac, and last for Solaris SPA RC.

Release Date

2009

MATLAB 7.9 R2009b

22

September 4, 2009

MATLAB 7.9.1 R2009bSP1 2010

April 1, 2010 Last release March 5, 2010 for Intel 32-bit Mac.

MATLAB 7.10 R2010a

23

2 History of MATLAB
Version Release name Number 2010 24 Year MATLAB 7.11 R2010b Release Date September 3, 2010 March 17, 2011 25 26 27 2012 2011 April 8, 2011 September 1, 2011 March 1, 2012 Notes

MATLAB R2010bSP1 7.11.1 MATLAB 7.12 R2011a


MATLAB 7.13 R2011b MATLAB 7.14 R2012a

10

2 History of MATLAB
Version Release name Number Year Notes First release with Toolstrip i nterface MATLAB September 11, Apps. 2012
Redesigned documentation system. New unit March 7, 2013 testing framew ork.

Release Date

MATLAB 8

R2012b

28

2012

MATLAB 8.1 R2013a

29

2013

11

3 MATLAB Functionality

Built-in Functionality includes


Matrix manipulation and linear algebra Data analysis Graphics and visualisation and hundreds of other functions

Add-on toolboxes provide*


Image processing Signal Processing Optimization Genetic Algorithms * but we have to pay for these extras

MATLAB Nowadays

Contemporary Communication Systems using Matlab-Proakis and Cc H thng thng tin hin nay trnh by thng qua s dng Matlab-TS nguyen Quoc Binh

MATLAB Nowadays

Practical MATLAB Applications for Engineers-Misza Kalechma

Prerequisite

Electric Circuit 1, 2 Power System Power Supply

References

Gio trnh ng dng Matlab trong K thut in-Nguyn Vinh Quan Matlab 7-Nguyn Vinh Quan Introduction to Matlab: Application to Electrical Engineering-Houssem Rafik El Hana Bouchekara-Umm El Qura University Practical MATLAB Applications for Engineers-Misza Kalechma

References

Gio trnh ng dng Matlab trong K thut in-Nguyn Vinh Quan Matlab 7-Nguyn Vinh Quan Introduction to Matlab: Application to Electrical Engineering-Houssem Rafik El Hana Bouchekara-Umm El Qura University Practical MATLAB Applications for Engineers-Misza Kalechma and ...

Skills achieved after course

Using Matlab software to solve the problems in:


Electrical circuits Laplace transform Distribution system Circuit analysis (Simulink) Modeling and simulation and ....

4 Starting and stopping

To Start

On Windows XP platform select


Start->Programs->Maths and Stats-> MATLAB->MATLAB_local->R2009a->MATLAB R2009a

To stop (nicely)

Select File -> Exit MATLAB


Or type quit in the MATLAB command window

5 The MATLAB interfaces


Menus change depending on the tool you are currently using Use tab to go to Workspace browser Get help View or change current directory

Move Command Window outside of desktop (unlock)

Click Start button for quick access to tools and more

View or execute previously run functions from the Command History Window

Drag the separator bar to resize windows

Enter MATLAB functions at command line prompt

20

5 The MATLAB interfaces

Command Prompt MATLAB commands are entered here. Command History - Lists all commands previously entered. Workspace Displays any variables created (Matrices, Vectors, Singles, etc.)

Double clicking on a variable in

the Workspace will open an Array Editor. This will give you an Excel-like view of your data.

21

5 The MATLAB interfaces

Pressing the up arrow in the command window will bring up the last command entered

This saves you time when things go wrong

If you want to bring up a command from some time in the past type the first letter and press the up arrow. The current working directory should be set to a directory of your own

22

5 The MATLAB interfaces

You can specify certain characteristics for the desktop tools by selecting Preferences from the File menu.

23

5 The MATLAB interfaces

Desktop Tools?

The tools are: Command Window. Command History. Help Browser. Current Directory Browser. Workspace Browser.

24

5 The MATLAB interfaces

Desktop Tools?
The tools are: Command Window.

25

5 The MATLAB interfaces

Desktop Tools?
The tools are: Command Window.

Use the Command Window to enter variables and run functions and M-files.
26

5 The MATLAB interfaces

Desktop Tools?

The tools are: Command Window. Command History. Help Browser. Current Directory Browser. Workspace Browser.

27

5 The MATLAB interfaces

Desktop Tools?

The tools are: Command Window. Command History. Help Lines you Browser. enter in the Command Window logged in the Current are Directory Browser. Command History window. Workspace Browser. In the Command History, you can view previously used functions, and copy and execute selected lines.
28

5 The MATLAB interfaces

Desktop Tools?

The tools are: Command Window. Command History. Help Browser. Current Directory Browser. Workspace Browser.

29

5 The MATLAB interfaces

Desktop Tools?

The tools are: Command Window. Command History. Help Browser. Current Directory Browser. Workspace Browser. To open the Help browser, click the help button in the toolbar, or type helpbrowser in the Command Window.
30

5 The MATLAB interfaces

Desktop Tools?
The tools are: Command Window. Command History. Help Browser. Current Directory Browser. A Workspace quick way to view or change the Browser. current directory is by using the Current Directory field in the desktop toolbar as shown below.

31

5 The MATLAB interfaces

Desktop Tools?

The tools are: Command Window. Command History. Help Browser. Current Directory Browser. Workspace Browser.

The MATLAB workspace consists of the set of variables (named arrays) built up during a MATLAB session and stored in memory.

32

5 The MATLAB interfaces

Desktop Tools?

The tools are: Command Window. Command History. Help Browser. Current Directory Browser. Workspace Browser.

You add variables to the workspace by using functions, running M-files, and loading saved workspaces.

33

5 The MATLAB interfaces

To view the workspace and information about each variable, use the Workspace browser, or use the functions who and whos.

Double click a variable to see and change its contents in the Variable Editor

34

6 Using MATLAB as a calculator

Table below gives the partial list of commonly used MATLAB operators and special characters used to solve many engineering and science problems.

35

7 Creating MATLAB variables

MATLAB variables are created with an assignment statement. The syntax of variable assignment is variable name = a value (or an expression) For example, >> x = expression where expression is a combination of numerical values, mathematical operators, variables, and function calls.

36

8 Overwriting variable

Once a variable has been created, it can be reassigned. In addition, if you do not wish to see the intermediate results, you can suppress the numerical output by putting a semicolon (;) at the end of the line. Then the sequence of commands looks like this: >> t = 5; >> t = t+1 t = 6

37

9 Error messages

If we enter an expression incorrectly, MATLAB will return an error message. For example, in the following, we left out the multiplication sign, *, in the following expression >> x = 10; >> 5x ??? 5x | Error: Unexpected MATLAB expression.

38

10 Making corrections

To make corrections, we can, of course retype the expressions. But if the expression is lengthy, we make more mistakes by typing a second time. A previously typed command can be recalled with the uparrow key . When the command is displayed at the command prompt, it can be modified if needed and executed.

39

11 Controlling the hierarchy of operations or precedence

The Table shown the hierarchy of arithmetic operations is given as follows:

40

12 Controlling the appearance of floating point number

Use the format function to control the output format of numeric values displayed in the Command Window. MATLAB by default displays only 4 decimals in the result of the calculations, for example 163.6667.

41

12 Controlling the appearance of floating point number

However, MATLAB has different formats together with the resulting outputs.

42

13 Mathematical functions

MATLAB offers many predefined mathematical functions for technical computing which contains a large set of mathematical functions. There is a long list of mathematical functions that are built into MATLAB. These functions are called built-ins. Many standard mathematical functions, such as sin(x), cos(x), tan(x), ex, ln(x), are evaluated by the functions sin, cos, tan, exp, and log respectively in MATLAB.

43

13 Mathematical functions

44

13 Mathematical functions

In addition to the elementary functions, MATLAB includes a number of predefined constant values.

45

13 Mathematical functions
Notes: Only use built-in functions on the right hand side of an expression. Reassigning the value to a built-in function can create problems. There are some exceptions. For example, i and j are preassigned to sqrt(-1). However one or both of i or j are often used as loop indices. To avoid any possible confusion, it is suggested to use instead ii or jj as loop indices.

46

14 Basic plotting
Overview Creating simple plots Adding titles, labels, and annotations Multiple data sets in one plot Specifying line styles and colors Copy/Paste Figures Saving Figures

47

14 Basic plotting
Overview Creating simple plots Adding titles, labels, and annotations Multiple data sets in one plot Specifying line styles and colors Copy/Paste Figures Saving Figures

MATLAB has an excellent set of graphic tools.


Plotting a given data set or the results of computation is possible with very few commands. You are highly encouraged to plot mathematical functions and results of analysis as often as possible. Trying to understand mathematical equations with graphics is an enjoyable and very efficient way of learning mathematics. Being able to plot mathematical functions and data freely is the most important step, and this section is written to assist you to do just that.
48

14 Basic plotting
Overview Creating simple plots Adding titles, labels, and annotations Multiple data sets in one plot Specifying line styles and colors Copy/Paste Figures Saving Figures

The basic MATLAB graphing procedure, for example in 2D, is to take a vector of xcoordinates, x = (x1, . . . , xN ), and a vector of y-coordinates, y = (y1, . . . , yN ), locate the points (xi, yi), with i = 1, 2, . . . , n and then join them by straight lines. You need to prepare x and y in an identical array form; namely, x and y are both row arrays or column arrays of the same length.
The MATLAB command to plot a graph is plot(x,y). The vectors x = (1, 2, 3, 4, 5, 6) and y = (3, 1, 2, 4, 5, 1) produce the picture shown in Figure below. >> x = [1 2 3 4 5 6]; >> y = [3 -1 2 4 5 1];

>> plot(x,y)
49

14 Basic plotting
Overview Creating simple plots Adding titles, labels, and annotations Multiple data sets in one plot Specifying line styles and colors Copy/Paste Figures Saving Figures

The MATLAB command to plot a graph is plot(x,y). The vectors x = (1, 2, 3, 4, 5, 6) and y = (3, 1, 2, 4, 5, 1) produce the picture shown in Figure below.
>> x = [1 2 3 4 5 6]; >> y = [3 -1 2 4 5 1]; >> plot(x,y)

50

14 Basic plotting
Overview Creating simple plots Adding titles, labels, and annotations Multiple data sets in one plot Specifying line styles and colors Copy/Paste Figures Saving Figures

Note:
The plot functions has different forms depending on the input arguments. If y is a vector, plot(y) produces a piecewise linear graph of the elements of y versus the index of the elements of y.

If we specify two vectors, as mentioned above, plot(x,y) produces a graph of y versus x.

51

14 Basic plotting
Overview Creating simple plots Adding titles, labels, and annotations Multiple data sets in one plot Specifying line styles and colors Copy/Paste Figures Saving Figures

For example, to plot the function sin (x) on the interval [0, 2], we first create a vector of x values ranging from 0 to 2, then compute the sine of these values, and finally plot the result:
>> x = 0:pi/100:2*pi; >> y = sin(x); >> plot(x,y)

52

14 Basic plotting
Overview Creating simple plots Adding titles, labels, and annotations Multiple data sets in one plot Specifying line styles and colors Copy/Paste Figures Saving Figures

Notes:
0:pi/100:2*pi yields a vector that starts at 0, takes steps (or increments) of /100, stops when 2 is reached. If you omit the increment, MATLAB automatically increments by 1.

53

14 Basic plotting
Overview Creating simple plots Adding titles, labels, and annotations Multiple data sets in one plot Specifying line styles and colors Copy/Paste Figures Saving Figures

MATLAB enables you to add axis labels and titles.


For example, using the graph from the previous example, add an x- and y-axis labels. Now label the axes and add a title. The character \pi creates the symbol .

54

14 Basic plotting
Overview Creating simple plots Adding titles, labels, and annotations Multiple data sets in one plot Specifying line styles and colors Copy/Paste Figures Saving Figures

>> xlabel(x = 0:2\pi)


>> ylabel(Sine of x) >> title(Plot of the Sine function) The color of a single curve is, by default, blue, but other colors are possible. The desired color is indicated by a third argument. For example, red is selected by plot(x,y,r ). Note the single quotes, , around r. More: text(x,y,z, ), legend(x,y), gtext( )

55

14 Basic plotting
Overview Creating simple plots Adding titles, labels, and annotations Multiple data sets in one plot Specifying line styles and colors Copy/Paste Figures Saving Figures

Multiple (x, y) pairs arguments create multiple graphs with a single call to plot.
For example, these statements plot three related functions of x: y1 = 2cos(x), y2 = cos(x), and y3 = 0.5*cos(x), in the interval 0 x 2.

56

14 Basic plotting
Overview Creating simple plots Adding titles, labels, and annotations Multiple data sets in one plot Specifying line styles and colors Copy/Paste Figures Saving Figures

>> x = 0:pi/100:2*pi;

>> y1 = 2*cos(x);
>> y2 = cos(x); >> y3 = 0.5*cos(x); >> plot(x,y1,'--',x,y2,'-',x,y3,':')

>> xlabel('0 \leq x \leq 2\pi')


>> ylabel('Cosine functions') >> legend('2*cos(x)','cos(x)','0.5*cos(x)') >> title('Typical example of multiple plots')

>> axis([0 2*pi -3 3])


57

14 Basic plotting
Overview Creating simple plots Adding titles, labels, and annotations Multiple data sets in one plot Specifying line styles and colors Copy/Paste Figures Saving Figures

It is possible to specify line styles, colors, and markers (e.g., circles, plus signs, . . . ) using the plot command: plot(x,y,style_color_marker ), where style_color_marker is a triplet of values from Table below.
To find additional information, type help plot or doc plot.

58

14 Basic plotting
Overview Creating simple plots Adding titles, labels, and annotations Multiple data sets in one plot Specifying line styles and colors Copy/Paste Figures Saving Figures

Specifying the Color and Size of Markers You can also specify other line characteristics using graphics properties (see line for a description of these properties):
LineWidth Specifies the width (in points) of the line. MarkerEdgeColor Specifies the color of the marker or the edge color for filled markers (circle,square, diamond, pentagram, hexagram, and the four triangles). MarkerFaceColor Specifies the color of the face of filled markers. MarkerSize Specifies the size of the marker in units of points.
59

14 Basic plotting
Overview Creating simple plots Adding titles, labels, and annotations Multiple data sets in one plot Specifying line styles and colors Copy/Paste Figures Saving Figures

For example, these statements, produce the graph of x = -pi:pi/10:pi;

y = tan(sin(x)) - sin(tan(x));
plot(x,y,'--rs','LineWidth',2,... 'MarkerEdgeColor','k',...

'MarkerFaceColor','g',...
'MarkerSize',10)

60

14 Basic plotting
Overview Creating simple plots Adding titles, labels, and annotations Multiple data sets in one plot Specifying line styles and colors Copy/Paste Figures Saving Figures

Figures can be pasted into other apps (word, ppt, etc) Editcopy optionsfigure copy templateChange font sizes, line properties; presets for word and ppt. Editcopy figure to copy figure. Paste into document of interest.

61

14 Basic plotting
Overview Creating simple plots Adding titles, labels, and annotations Multiple data sets in one plot Specifying line styles and colors Copy/Paste Figures Saving Figures

Figures can be saved in many formats. The common ones are given the following figure.

62

EXERCISES

Problem 1: Draw z surface in

63

EXERCISES

Problem 2: Draw the cylinder z, using mesh and surf function

64

15 Working with Matrices


Matrices are the basic elements of the MATLAB environment. A matrix is a two-dimensional array consisting of m rows and n columns. Special cases are column vectors (n = 1) and row vectors (m = 1). The following topics are discussed: vectors and matrices in MATLAB, the inverse of a matrix, determinants, and matrix manipulation. MATLAB supports two types of operations, known as matrix operations and array operations. Matrix operations will be discussed first.

65

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

66

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

A vector is a special case of a matrix. An array of dimension 1 n is called a row vector, whereas an array of dimension m 1 is called a column vector. The elements of vectors in MATLAB are enclosed by square brackets and are separated by spaces or by commas. For example, to enter a row vector, v, type >> v = 1 4 7 10 13 [1 4 v= 7 10 13]

67

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

Column vectors are created in a similar way, however, semicolon (;) must separate the components of a column vector,

>> w = [1;4;7;10;13] w= 1 4 7 10 13

68

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

On the other hand, a row vector is converted to a column vector using the transpose operator. The transpose operation is denoted by an apostrophe or a single quote ().

>> w = v w= 1 4 7 10 13

69

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

Thus, v(1) is the first element of vector v, v(2) its second element, and so forth. Furthermore, to access blocks of elements, we use MATLABs colon notation (:).

For example, to access the first three elements of v, we write,


Or, all elements from the third through the last elements, >> v(1:3) ans = 1 4 7 >> v(3,end) ans =7 10 13 where end signifies the last element in the vector.

70

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

If v is a vector, writing >> v(:) produces a column vector, whereas writing >> v(1:end) produces a row vector.

71

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

A matrix is an array of numbers. To type a matrix into MATLAB you must begin with a square bracket, [ separate elements in a row with spaces or commas (,) use a semicolon (;) to separate rows end the matrix with another square bracket, ].

72

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

Here is a typical example. To enter a matrix A, such as, type, >> A = [1 2 3; 4 5 6; 7 8 9] MATLAB then displays the 3 3 matrix as follows, A = 1 2 3 4 5 6 7 8 9

73

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

Note that the use of semicolons (;) here is different from their use mentioned earlier to suppress output or to write multiple commands in a single line.

Once we have entered the matrix, it is automatically stored and remembered in the Workspace.
We can refer to it simply as matrix A. We can then view a particular element in a matrix by specifying its location. We write,

>> A(2,1)
ans = 4 A(2,1) is an element located in the second row and first column. Its value is 4.

74

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

We select elements in a matrix just as we did for vectors, but now we need two indices.

The element of row i and column j of the matrix A is denoted by A(i,j). Thus, A(i,j) in MATLAB refers to the element Aij of matrix A. The first index is the row number and the second index is the column number.
For example, A(1,3) is an element of first row and third column. Here, A(1,3)=3. Correcting any entry is easy through indexing. Here we substitute A(3,3)=9 by A(3,3)=0. The result is >> A(3,3) = 0 Single elements of a matrix are accessed as A(i,j), where i 1 and j 1. Zero or negative subscripts are not supported in MATLAB.
75

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

The colon operator will prove very useful and understanding how it works is the key to efficient and convenient usage of MATLAB. It occurs in several different forms.

Often we must deal with matrices or vectors that are too large to enter one element at a time.
For example, suppose we want to enter a vector x consisting of points (0, 0.1, 0.2, 0.3, , 5). We can use the command >> x = 0:0.1:5; The row vector has 51 elements.

76

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

On the other hand, there is a command to generate linearly spaced vectors: linspace. It is similar to the colon operator (:), but gives direct control over the number of points. For example, y = linspace(a,b) generates a row vector y of 100 points linearly spaced between and including a and b. y = linspace(a,b,n)

generates a row vector y of n points linearly spaced between and including a and b.

77

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

When we want to divide an interval into a number of subintervals of the same length. For example, >> theta = linspace(0,2*pi,101) divides the interval [0, 2] into 100 equal subintervals, then creating a vector of 101 elements.

78

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

The colon operator can also be used to pick out a certain row or column. For example, the statement A(m:n,k:l specifies rows m to n and column k to l. Subscript expressions refer to portions of a matrix. For example, >> A(2,:) ans = 4 5 6 is the second row elements of A.

79

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

The colon operator can also be used to extract a sub-matrix from a matrix A. >> A(:,2:3) ans = 2 3 5 6 8 0 A(:,2:3) is a sub-matrix with the last two columns of A.

80

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

A row or a column of a matrix can be deleted by setting it to a null vector, [ ]. >> A(:,2)=[] ans = 1 3 4 6 7 0

81

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

To extract a submatrix B consisting of rows 2 and 3 and columns 1 and 2 of the matrix A, do the following

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


B = 4 5 7 8

82

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

To interchange rows 1 and 2 of A, use the vector of row indices together with the colon operator.

>> C = A([2 1 3],:)


C = 4 5 6 1 2 3 7 8 0

83

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

It is important to note that the colon operator (:) stands for all columns or all rows. To create a vector version of matrix A, do the following

>> A(:)
ans = 1 2 3 4 5 6 7 8 0
84

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

The submatrix comprising the intersection of rows p to q and columns r to s is denoted by A(p:q,r:s).

As a special case, a colon (:) as the row or column specifier covers all entries in that row or column; thus
A(:,j) is the jth column of A, while A(i,:) is the ith row, and

A(end,:) picks out the last row of A.


The keyword end, used in A(end,:), denotes the last index in the specified dimension.

85

15 Working with Matrices


Entering a vector Entering a matrix Matrix indexing Colon operator Linear spacing Colon operator in a matrix Creating a sub-matrix

Here are some examples. >> A(2:3,2:3) >> A A= 1 2 3 4 5 6 7 8 9 ans = 5 6 8 9

>> A(end:-1:1,end) ans = 9 6 3

>> A([1 3],[2 3]) ans = 2 3 8 9

86

15 Working with Matrices


Deleting row or column Dimension Continuation Transposing a matrix Concatenating matrices Matrix generators

To delete a row or column of a matrix, use the empty vector operator, [ ]. >> A(3,:) = [] A = 1 2 3 4 5 6 Third row of matrix A is now deleted.

87

15 Working with Matrices


Deleting row or column Dimension Continuation Transposing a matrix Concatenating matrices Matrix generators

To restore the third row, we use a technique for creating a matrix >> A = [A(1,:);A(2,:);[7 8 0]] A= 1 2 3 4 5 6 7 8 9 Matrix A is now restored to its original form.

88

15 Working with Matrices


Deleting row or column Dimension Continuation Transposing a matrix Concatenating matrices Matrix generators

To determine the dimensions of a matrix or vector, use the command size. For example, >> size(A) ans = 3 3 means 3 rows and 3 columns. Or more explicitly with, >> [m,n]=size(A)

89

15 Working with Matrices


Deleting row or column Dimension Continuation Transposing a matrix Concatenating matrices Matrix generators

If it is not possible to type the entire input on the same line, use consecutive periods, called an ellipsis . . ., to signal continuation, then continue the input on the next line. B=[ 4/5 1/x^2 x-7 7.23*tan(x) 0 sqrt(3) sqrt(6); ... 3/(x*log(x)); ... x*sin(x)];

Note that blank spaces around +, , = signs are optional, but they improve readability.

90

15 Working with Matrices


Deleting row or column Dimension Continuation Transposing a matrix Concatenating matrices Matrix generators

The transpose operation is denoted by an apostrophe or a single quote (). It flips a matrix about its main diagonal and it turns a row vector into a column vector. Thus, >> A ans = 1 4 7 2 5 8 3 6 0 By using linear algebra notation, the transpose of m n real matrix A is the n m matrix that results from interchanging the rows and columns of A. The transpose matrix is denoted AT

91

15 Working with Matrices


Deleting row or column Dimension Continuation Transposing a matrix Concatenating matrices Matrix generators

Matrices can be made up of sub-matrices. Here is an example. First, lets recall our previous matrix A.

A =
1 2 3 4 5 6

7 8 9

92

15 Working with Matrices


Deleting row or column Dimension Continuation Transposing a matrix Concatenating matrices Matrix generators

The new matrix B will be, >> B = [A 10*A; -A [1 0 0; 0 1 0; 0 0 1]] B = 1 2 3 10 20 30 4 5 6 40 50 60

7 8 9 70 80 90
-1 -2 -3 1 0 0 -4 -5 -6 0 1 0 -7 -8 -9 0 0 1
93

15 Working with Matrices


Deleting row or column Dimension Continuation Transposing a matrix Concatenating matrices Matrix generators

MATLAB provides functions that generate elementary matrices. The matrix of zeros, the matrix of ones, and the identity matrix are returned by the functions zeros, ones, and eye, respectively.

94

15 Working with Matrices


Deleting row or column Dimension Continuation Transposing a matrix Concatenating matrices Matrix generators

For a complete list of elementary matrices and matrix manipulations, type help elmat or doc elmat. Here are some examples:

>> b=ones(3,1)
b = 1

1
1

95

15 Working with Matrices


Deleting row or column Dimension Continuation Transposing a matrix Concatenating matrices Matrix generators

Equivalently, we can define b as >> b=[1;1;1] >> eye(3) ans = 1 0 0 0 1 0 0 0 1

96

15 Working with Matrices


Deleting row or column Dimension Continuation Transposing a matrix Concatenating matrices Matrix generators

>> c=zeros(2,3) c = 0 0 0 0 0 0

97

15 Working with Matrices


Deleting row or column Dimension Continuation Transposing a matrix Concatenating matrices Matrix generators

In addition, it is important to remember that the three elementary operations of ad- dition (+), subtraction (), and multiplication (*) apply also to matrices whenever the dimensions are compatible. Two other important matrix generation functions are rand and randn, which generate matrices of (pseudo-)random numbers using the same syntax as eye.

98

15 Working with Matrices


Deleting row or column Dimension Continuation Transposing a matrix Concatenating matrices Matrix generators

In addition, matrices can be constructed in a block form. With C defined by C = [1 2; 3 4], we may create a matrix D as follows

>> D = [C zeros(2); ones(2) eye(2)]


D= 1 2 0 0

3 4 0 0
1 1 1 0 1 1 0 1
99

Vous aimerez peut-être aussi