Sie sind auf Seite 1von 167

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( ), 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

More: Grid (on/off), box (on/off), hold (on/off), subplot.... Polar(t,r) Semilogx(x,y), semilogy(x,y), loglog(x,y).

62

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

Ex.: Sin(2t), t=[0:2pi] Archimeder curve: r=2, =[0:4pi] Log(ex)

63

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

More:

Plot3(x, y, z) displays a three-dimensional plot of a set of data points. Mesh(z), surf(z) create a three-dimensional shaded surface from the z components in matrix Z.

64

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

Ex.:

x=sin(t), y=cos(t) (plot3) x=e(-0.005t)sin(t), y=e(-0.005t)cos(t) (plot3) z=x2+y2 (mesh, surf)

65

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.

66

EXERCISES

Problem 1: Draw z surface in

67

EXERCISES

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

68

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.

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

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

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]

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

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

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

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

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

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.

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

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

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

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, ].

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

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

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

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.

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

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.
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 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.

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

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.

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

When we want to divide an interval into a number of sub-intervals 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.

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

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.

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

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 9 A(:,2:3) is a sub-matrix with the last two columns of A.

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

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 9

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

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

86

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 9

87

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 9
88

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,

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


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

89

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

90

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.

91

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 9]] A= 1 2 3 4 5 6 7 8 9 Matrix A is now restored to its original form.

92

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)

93

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.

94

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 9 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

95

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

96

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
97

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.

98

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

99

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

100

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

101

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 addition (+), 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.

102

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
103

EXERCISES
Problem 1: Enter A=[1 6 3 2 1 3;5 1 0 1 1 8;9 6 7 1 2 5;4 1 5 1 4 1]. Finding: sizeA First row of A. B= two last rows of A. sum(A(:,1)) sum(A(1,:))

104

EXERCISES

Problem 2: Enter A=[2 7 9 7; 3 1 5 6; 8 1 2 5], explain the results of:


A A(:,[1 4]) A([2 3],[3 1]) reshape(A,2,6) A(:) [A A(end,:)]

A(1:3,:) [A ; A(1:2,:)] sum(A) sum(A) [[A;sum(A)][sum(A2);sum(A(:))]]

105

16 Array operations
MATLAB has two different types of arithmetic operations: matrix arithmetic operations and array arithmetic operations. Matrix arithmetic operations Array arithmetic operations

A+B or B+A is valid if A and B are of The matrix and array operations are the the same size same for addition (+) and subtraction (), A*B is valid if As number of column the character pairs equals Bs number of rows (.+) and (.) are not used. A^2 is valid if A is square and equals A*A *A or A* multiplies each element of A by

106

16 Array operations
Summary of matrix and array operations.

107

17 Solving linear equations


One of the problems encountered most frequently in scientific computation is the solution of systems of simultaneous linear equations. With matrix notation, a system of simultaneous linear equations is written Ax = b where there are as many equations as unknown. A is a given square matrix of order n, b is a given column vector of n components, and x is an unknown column vector of n components. In linear algebra we learn that the solution to Ax = b can be written as x = A1b, where A1 is the inverse of A.

108

17 Solving linear equations


For example, consider the following system of linear equations

The coefficient matrix A is

With matrix notation, a system of simultaneous linear equations is written Ax = b This equation can be solved for x using linear algebra. The result is x = A1b.

109

17 Solving linear equations

There are typically two ways to solve for x in MATLAB:


1. The first one is to use the matrix inverse, inv. >> A = [1 2 3; 4 5 6; 7 8 0]; >> b = [1; 1; 1]; >> x = inv(A)*b x = -1.0000

1.0000
-0.0000

110

17 Solving linear equations

There are typically two ways to solve for x in MATLAB:


2. The second one is to use the backslash (\)operator. The numerical algorithm behind this operator is computationally efficient. This is a numerically reliable way of solving system of linear equations by using a well-known process of Gaussian elimination. >> A = [1 2 3; 4 5 6; 7 8 0]; >> b = [1; 1; 1]; >> x = A\b x = -1.0000 1.0000 -0.0000

111

17 Solving linear equations


Matrix inverse Matrix functions

112

17 Solving linear equations


Matrix inverse Matrix functions

Lets consider the same matrix A.

Calculating the inverse of A manually is probably not a pleasant work. Here the handcalculation of A1 gives as a final result:

113

17 Solving linear equations


Matrix inverse Matrix functions

In MATLAB, however, it becomes as simple as the following commands:

>> A = [1 2 3; 4 5 6; 7 8 0];
>> inv(A) ans = -1.7778 0.8889 -0.1111 1.5556 -0.7778 0.2222

-0.1111 0.2222 -0.1111


which is similar to:
114

17 Solving linear equations


Matrix inverse Matrix functions

And the determinant of A is

>> det(A)
ans = 27

115

17 Solving linear equations


Matrix inverse Matrix functions

MATLAB provides many matrix functions for various matrix/vector manipulations; see Table below for some of these functions. Use the online help of MATLAB to find how to use these functions.

116

EXERCISES
Problem 1: Solve the equation Ax=b, in which:

117

EXERCISES
Problem 2: Enter x=[3 1 5 7 9 2 6], finding the results of x(3) x(1:7) x(1:end) x(1:end-1) x(6:-2:1) x([1 6 2 1 1]) sum(x)

118

EXERCISES

Problem 3: Draw y1=sinx.cos2x and y2=sinx2, x=[0-2]

119

EXERCISES

Problem 4: Solve the equations below: 2x1+4x2+6x3 2x4 =0 x1+2x2+x3 +2x4=1 2x2+4x3 +2x4=2 3x1- x2+10x4=10

120

18 Introduction

to programming in MATLAB

The commands entered in the Command Window cannot be saved and executed again for several times. Therefore, a different way of executing repeatedly commands with MATLAB is: 1. to create a file with a list of commands, 2. save the file, and 3. run the file. If needed, corrections or changes can be made to the commands in the file. The files that are used for this purpose are called script files or scripts for short. This section covers the following topics: 1. M-File Scripts 2. M-File Functions

121

18 Introduction

to programming in MATLAB
M-File functions

M-File Scripts

122

18 Introduction

to programming in MATLAB
M-File functions

M-File Scripts

A script file is an external file that contains a sequence of MATLAB statements. Script files have a filename extension .m and are often called M-files. M-files can be scripts that simply execute a series of MATLAB statements, or they can be functions that can accept arguments and can produce one or more outputs.

123

18 Introduction

to programming in MATLAB
M-File functions

M-File Scripts

A script file is an external file that As mentioned earlier, functions contains a sequence of MATLAB are programs (or routines ) that statements. accept input arguments and return output arguments. Script files have a filename extension .m and are often called Each M-file function (or function M-files. or M-file for short) has its own area of workspace, separated from M-files can be scripts that simply the MATLAB base workspace. execute a series of MATLAB statements, or they can be functions that can accept arguments and can produce one or more outputs.

124

18 Introduction

to programming in MATLAB
M-File functions

M-File Scripts

function [ output_args ] = untitled5( input_args ) % UNTITLED5 Summary of this function goes here % Detailed explanation goes here end

125

18 Introduction

to programming in MATLAB
M-File functions

M-File Scripts

Example 1: Consider the system of equations:

Find the solution x to the system of equations. Solution:

Use the MATLAB editor to create a file: File New M-file.


Enter the following statements in the file: A = [1 2 3; 3 3 4; 2 3 3];

b = [1; 1; 2];
x = A\b
126

18 Introduction

to programming in MATLAB
M-File functions

M-File Scripts

Example 1: Consider the system of equations:

Save the file, for example, example1.m. Run the file, in the command line, by typing:

>> example1
x = -0.5000

1.5000
-0.5000
127

18 Introduction

to programming in MATLAB
M-File functions

M-File Scripts

Example 1: Consider the system of equations:

Save the file, for example, example1.m. Run the file, in the command line, by typing:

>> example1
x = -0.5000

1.5000
-0.5000
128

18 Introduction

to programming in MATLAB
M-File functions

M-File Scripts

Example 2: Plot the following cosine functions, y1 = 2 cos(x), y2 = cos(x), and y3 = 0.5 cos(x), in the interval 0 x 2. This example has been presented in previous Chapter. Here we put the commands in a file.

Create a file, say example2.m, which contains the following commands:


x = 0:pi/100:2*pi; y1 = 2*cos(x); xlabel(0 \leq x \leq 2\pi) ylabel(Cosine functions)

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

legend(2*cos(x),cos(x),0.5*cos(x))
title(Typical example of multiple plots) axis([0 2*pi -3 3])

129

18 Introduction
function f = factorial(n)

to programming in MATLAB
M-File functions

M-File Scripts

This simple function shows the basic parts of an M-file.

% FACTORIAL(N) returns the factorial of N.


% Compute a factorial value. f = prod(1:n);

130

18 Introduction

to programming in MATLAB
M-File functions

M-File Scripts

The first line of a function M-file starts with the keyword function. It gives the function name and order of arguments.

In the case of function factorial, there are up to one output argument and one input argument.
function f = factorial(n) % FACTORIAL(N) returns the factorial of N. % Compute a factorial value. f = prod(1:n);

131

18 Introduction

to programming in MATLAB
M-File functions

M-File Scripts

In addition, it is important to note that function name must begin with a letter, and must be no longer than the maximum of 63 characters. Furthermore, the name of the text file that you save will consist of the function name with the extension .m. Thus, the above example file would be factorial.m. function f = factorial(n) % FACTORIAL(N) returns the factorial of N.

% Compute a factorial value.


f = prod(1:n);

132

18 Introduction

to programming in MATLAB
M-File functions

M-File Scripts

In addition, it is important to note that function name must begin with a letter, and must be no longer than the maximum of 63 characters. Furthermore, the name of the text file that you save will consist of the function name with the extension .m. Thus, the above example file would be factorial.m. function f = factorial(n) % FACTORIAL(N) returns the factorial of N.

% Compute a factorial value.


f = prod(1:n);

133

18 Introduction
Ex:

to programming in MATLAB
M-File functions

M-File Scripts

Write a function that can calculate the area S of a triangle whose sides have lengths a, b and c.

134

18 Introduction
Ex:

to programming in MATLAB
M-File functions

M-File Scripts

Write a function that can calculate the average value of all elements.

135

19 Control flow
MATLAB is also a programming language. Like other computer programming languages, MATLAB has some decision making structures for control of command execution. These decision making or control flow structures include for loops, while loops, and if-else-end constructions. Control flow structures are often used in script M-files and function Mfiles. By creating a file with the extension .m, we can easily write and run programs. We do not need to compile the program since MATLAB is an interpretative (not compiled) language. MATLAB has thousand of functions, and you can add your own using m-files.

136

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

137

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

MATLAB supports the variants of if construct. if ... end if ... else ... end if ... elseif ... else ... end The simplest form of the if statement is if expression statements end

138

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

Here are some examples based on the familiar quadratic formula. Example 1 discr = b*b - 4*a*c; if discr < 0 disp(Warning: discriminant is negative, roots are imaginary); end

139

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

Here are some examples based on the familiar quadratic formula. Example 2 discr = b*b - 4*a*c; if discr < 0 disp(Warning: discriminant is negative, roots are imaginary); else disp(Roots are real, but may be repeated) end
140

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

Here are some examples based on the familiar quadratic formula. Example 3 discr = b*b - 4*a*c; if discr < 0 disp(Warning: discriminant is negative, roots are imaginary) elseif discr == 0 disp(Discriminant is zero, roots are repeated) else disp(Roots are real) end
141

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

It should be noted that: elseif has no space between else and if (one word) no semicolon (;) is needed at the end of lines containing if, else, end indentation of if block is not required, but facilitate the reading. the end statement is required

142

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

It should be noted that: elseif has no space between else and if (one word) no semicolon (;) is needed at the end of lines containing if, else, end indentation of if block is not required, but facilitate the reading. the end statement is required

143

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

In each of the following questions, evaluate the given MATLAB code fragments for each of the cases indicated. Use MATLAB to check your answers. 1. if n > 1 a. n = 7 m = ? m = n+1 b. n = 0 m = ? else c. n = -10 m = ? m=n-1 end ans.

144

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

In each of the following questions, evaluate the given MATLAB code fragments for each of the cases indicated. Use MATLAB to check your answers.
2. if z < 5 w = 2*z elseif z < 10 w=9-z elseif z < 100 w = sqrt(z) else w=z end ans. a. z = 1 w = ? b. z = 9 w = ? c. z = 60 w = ? d. z = 200 w = ?

145

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

In each of the following questions, evaluate the given MATLAB code fragments for each of the cases indicated. Use MATLAB to check your answers. 3. if T < 10 a. T = 50 h = ? h = 2*T + 1 b. T = 15 h = ? elseif T < 30 c. T = 0 h = ? h=T-2 else h=0 end ans.
146

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

In each of the following questions, evaluate the given MATLAB code fragments for each of the cases indicated. Use MATLAB to check your answers. 4. if I == J a. I = 1, J=2 A = ? A(I,J) = 2; b. I = 3, J=5 A = ? elseif abs(I-J) == 1 A(I,J) = -1; c. I = 5, J=2 A = ? else A(I,J) = 0; d. I = 3, J=2 A = ? end ans.
147

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

Write brief scripts to evaluate the following functions. If you start each script with a request for input (using input), you'll be able to test that your code provides the correct results. 5. h(T) = T - 10 = 0.45 T + 900 Test cases: when 0 < T < 100 when T > 100

a. T = 5, h = -5 b. T = 110, h = 949.5

148

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

Write brief scripts to evaluate the following functions. If you start each script with a request for input (using input), you'll be able to test that your code provides the correct results. 6. f(x) = -1 =0 =1 if x < 0 if x = 0 if x > 0

Compare your results to the MATLAB function sign.

149

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

Write brief scripts to evaluate the following functions. If you start each script with a request for input (using input), you'll be able to test that your code provides the correct results.
7. t(y) = 200 = 200 + 0.1 (y - 10,000) = 1,200 + 0.15 (y - 20,000) = 5,700 + 0.25 (y - 50,000) when y is below 10,000 when y is between 10,000 and 20,000 when y is between 20,000 and 50,000 when y is above 50,000

Test cases:

a. y = 5,000 t = 200 b. y = 17,000 t = 900 c. y = 25,000 t = 1,950 d y = 75,000 t = 11,950


150

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

A relational operator compares two numbers by determining whether a comparison is true or false. Relational operators are shown in Table below:

151

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

In the for ... end loop, the execution of a command is repeated at a fixed and predetermined number of times. The syntax is for variable = expression statements

end

152

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

Usually, expression is a vector of the form i:s:j. A simple example of for loop is for ii=1:5 x=ii*ii

end

153

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

The following statements form the 5-by-5 symmetric matrix A with (i, j) element i/j for j i: n = 5; A = eye(n); for j=2:n for i=1:j-1 A(i,j)=i/j; A(j,i)=i/j; end end
154

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

Ex: Plot the curve y=sin(n. .x) with -1 x

1 and n = 1, 2, ...8.

155

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

While...end loop is used when the number of passes is not specified. The looping continues until a stated condition is satisfied. The while loop has the form: while expression

statements
end

156

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

The statements are executed as long as expression is true. x=1 while x <= 10 x = 3*x end

157

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

It is important to note that if the condition inside the looping is not well defined, the looping will continue indefinitely. If this happens, we can stop the execution by pressing Ctrl-C.

158

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

Ex1: Finding the largest value of n such that the sum (12 n2 ) below 100?

22

32

...

159

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

Ex2: Finding the sum of A=1+1/2+1/3+..+1/n, n is the number you enter

160

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

The break statement. A while loop can be terminated with the break statement, which passes control to the first statement after the

corresponding end. The break statement can also be used to exit a for loop. Ex: Lets suppose now you are asked to calculate value of k^2-50 for all integers in [-10,10] domain but only until k^2-50 becomes negative.
161

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

The continue statement can also be used to exit a for loop to pass immediately to the next iteration of the loop, skipping the remaining statements in the loop. Ex: Lets suppose now you are asked to calculate and print value of k^250 for all integers in [-10,10] domain but only if (k^2-50) is positive.

162

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

Other control statements include return, switch, disp, error,

keyboard, etc.

For more detail about these commands, consul

MATLAB documentation.

163

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

Exercise 1: Write a program in which you can enter n (n>=0) so that it can include these cases as follows: a) If n<0 it will inform that you enter a wrong number b) If n>0 and odd number export the sum s1=1+3+5+...+n c) If n>0 and even number export the sum s2=2+4+6+...+n d) If n=0 stop the program.

164

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

Exercise 2: Write a program in which you can enter 2 number and then, it can compare them.

165

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

We can build expressions that use any combination of arithmetic, relational, and logical operators. Precedence rules determine the order in which MATLAB evaluates an expression.

166

19 Control flow
The if...end structure Relational and logical operators The for...end loop The while...end loop Other flow structures Operator precedence

Precedence rules determine the order in which MATLAB evaluates an expression.

167