This chapter introduces the general commands, Array Operations and operation functions of MATLAB software, drawing commands, loops and selection structures, and solves some simple problems through instance exercises.

**2.1 Introduction**

MATLAB is MATrix

Engineering computing software developed by MathWorks has released version 7.1 so far. today's mathematical science and technology applications can be divided into two types, one is the numerical computing type, such as MATLAB, Xmath, Gauss, etc., this type of software is good at numerical computing, to deal with a large number of data efficiency; the other type is mathematical analysis software, such as Mathematica and Maple. This type of software is known for symbolic computation and can provide resolution solutions and any precision solutions. Its disadvantage is that it has a high timeliness rate for processing a large amount of data.

Now, MATLAB has developed into a large-scale software suitable for multiple disciplines and powerful functions, and has become a basic teaching tool for advanced courses. For example, MATLAB can do:

Calculus: differential, integral, ultimate, Taylor expansion, sum of series;

Algebra: inverse, feature value, determinant, simplification of Solution of algebraic equations, and specified accuracy of mathematical expressions;

Numerical analysis: Interpolation and fitting, numerical differentiation and integration, function approximation, numerical and symbolic solutions for algebraic and differential equations.

Statistical calculation: Mean, variance, probability, parameter estimation, hypothesis test, correlation and regression analysis, statistical drawing, and random number generator.

Optimization Problem Solving: Linear Programming and nonlinear programming.

Dynamic System Simulation.

It has become a basic skill for college students, graduate students and doctoral students. At the same time, MATLAB has been widely used by research institutions and industrial departments, greatly improving the efficiency of scientific research and solving various specific problems.

The MATLAB integration environment consists of the MATLAB language, the MATLAB working environment, the handle graph, the MATLAB mathematical function library, and the Application Program Interface ).

MATLAB has the following features:

- The operators and library functions are extremely rich, the language is concise, and the programming efficiency is high. In addition to providing the same operators as the C language, MATLAB also provides a wide range of matrix and vector operators.
- Powerful graphics, including 2D and 3D data visualization, image processing, animation production, and other high-level drawing commands.
- Powerful toolbox. the Toolkit can be divided into two categories: Functional toolkit and subject toolkit. the former is mainly used to expand its symbolic computing functions, graphical modeling and simulation, text processing and real-time interaction with hardware. the subject toolbox is highly specialized, such as optimization, statistics, control, wavelet, image processing and communication toolbox.
- Easy to expand. Apart from internal functions, all MATLAB core files and Toolbox files are readable and changeable source files. Users can modify files and add their own files, which can be called like library files.

**2.1.1 Installation**(Windows operating platform)

- Insert the source disc into the optical drive;
- Find the Installation File setup.exe in the directory of the optical disk;
- Double-click the installation file and follow the prompts to complete the installation step by step;
- After installation, the MATLAB option is available in the program bar.

**2.1.2 start**

In "Start Program MATLAB", click MATLAB. The MATLAB Command Window (that is, the Command Window) appears ).

**2.2 MATLAB environment**

MATLAB is both a language and a programming environment.

**2.2.1 command window**

The command window is the main place for users to interact with Matlab. The common form of Matlab statements is:

Variable = expression

For example, enter: x = 4.5 and press Enter.

X =

4.5

Enter y = sin (x * pi) and press Enter:

Y

= 1

:

- The expression is followed by a semicolon ';'. The result is not displayed;
- With ',' or without any symbols, the calculation result of the expression is displayed;
- When a line needs to be changed before an expression is written, enter '...' At the end of the line and press enter to wrap the line. For example:

S = 1-1/2 + 1/3 + 1/4 + sin (3 * x * y)-cos (x )...

-Over 1/8 + 1/10 + 1/20

:

Control keys and direction keys used for command line editing

- Press ''to display the command line you just typed;
- Press the ''key repeatedly to call back all the previously typed command lines;
- ''Key to move the cursor;
- There are also 'home', 'end', 'esc 'keys, and so on. 'esc' to clear a row.

Variable

- It must start with a letter and can be followed by letters, numbers, and short-term characters;
- There are differences between uppercase and lowercase letters, with no more than 31 letters.

Special variable name

Ans: Default variable name used for the result; pi circumference Rate

Minimum number of eps computers; inf infinity; NaN is not quantitative

Start of I or j-1; minimum available real number of realmin; maximum available real number of realmax

Work Zone

The memory area that receives the Matlab command stores the command entered in the Command editing area and all the variable values created.

View or save the workspace variables:

Who or whos show all variables in the current Workspace

Clear all variables in the Workspace

Clear (variable name) clears the variable in the specified workspace

Save (File Name) stores the variables in the current workspace in a MAT-File

Load (File Name) call up a MAT-File

Press ENTER or click ''in the upper-right corner to exit the workspace.

**2.2.2 program editor**

M file: command file and function File

1. Create M Files

1) Go to the program Editor (MATLAB Editor/Debug): Select 'new' and'm-file' from the 'file' menu.

2) Input Program

3) save the program: Click 'save'. In the displayed dialog box, type a file name in the file name box and click 'save '.

2. Command M file and its running

Command M file: A combination of some command lines. No input parameter is provided, and no output parameter is returned. For example:

% File name exl. m

X = 4; y = 6; z = 2;

Items = x + y + z

Cost = x * 25 + y * 22 + z * 99

Average_cost = cost/items

- In the program editing window, enter the m file named exl. M to store the disk.
- In the Matlab command editing window, enter exl to execute the commands in this file in sequence.

3. Function M file and its call

The form of the function M file is:

Fuction [output variable list] = function name (input variable List)

Function body statement;

For example:

Function f = f1 (x)

F = 100 * (x (2)-x (1) ^ 2) ^ 2-(_x (1) ^ 2;

(Note that the file name of function M must be the same as that of function M)

Call format:

X = [2 3];

F = f1 (x)

Result: f =

99

**2.2.3 File Management**

What is the list of M, MAT, and MEX files in the current directory?

Dir: list all files in the current directory

Cd displays the current working directory

Type test displays the content of test. m in the Command window.

Delete test delete M file test. m

Which test displays the object where the M file test. m is located

**2.3 arrays and functions**

**2.3.1 Array Operation**

1) simple structure of Arrays:

Arrays often use the ':' and the function 'linspace' input methods, such:

X = (an equal deviation array with a tolerance of 1 to 5)

X =. (from 0 to 1, the tolerance is 0.1)

X = linspace (0, pi, 11) (11 equal intervals from 0 to pi)

2) array operation

Set a = [a1 a2 a3], B = [b1 b2 b3], c = scalar

Scalar addition a + B = [a1 + c a2 + c a3 + c]

Multiplication a * c = [a1 * c a2 * c a3 * c]

Array addition a + B = [a1 + b1 a2 + b2 a3 + b3]

Multiplication a. * B = [a1 * b1 a2 * b2 a3 * b3]

Right-side division of the array a./B = [a1/b1 a2/b2 a3/b3]

Remove a. \ B = [b1/a1 b2/a2 b3/a3] from the left

Evaluate the array power a. ^ c = [a1 ^ c a2 ^ c a3 ^ c]

C. ^ a = [a1 ^ c a2 ^ c a3 ^ c]

A. ^ B = [a1 ^ b1 a2 ^ b2 a3 ^ b3] sort (v) in ascending order

Max (v) calculates the maximum min (v) and the minimum sum (v) and the mean (v) for the average

**2.3.2 create a Matrix**

1) type the direct definition of the matrix: A = [1 2 3; 4 5 6]

Or type: A = [1 2 3

4 5 6]

2) Special Matrix

Zeros (m, n) ones (m, n) eye (n) rand (m, n) diag (v) triu (x)

3) matrix cropping and splicing

Type: A = [1 2 3; 4 5 6; 7 8 9]; The third line of A (3. :) %

Output: ans = 7 8 9

Type: B = A (, :) the second and third rows of %

Output: B =

4 5 6

7 8 9

Type: the first column of A (:, 1) %.

Output: ans =

1

4

7

Input: C = [B, zeros (2, 1)]

Output: C =

4 5 6 0

7 8 9 0

**2.3.3 matrix operations**

+ Matrix addition-matrix subtraction * multiplication, transpose ^ multiplication power/left Division \ Right Division

For example, if A is A reversible matrix, the solution of AX = B is A left division of B, that is, the solution of X = A \ B; XA = B x = B/. rank (A) Matrix rank inv (A) matrix inverse det (A) determinant orth (A) orthogonal poly (A) feature Polynomial

**2.3.4 mathematical functions**

Sin (x) cos (x) tan (x) cot (x) exp (x) log (x) log10 (x) sqrt (x) Square Root

Take the integer fix (x) in the zero direction and take the whole floor (x) In the direction. Take the integer Ceil (x) rounded to the nearest integer round (X)

**2.4 graphic functions**

**2.4.1 two-dimensional graphics**

1) Basic Drawing command

Plot (X, Y, 'color-linestyle-marker ')

X, Y ------ turning point; color-linestyle-marker ------- line color, line type, data point icon.

Color: y yellow R Red G green B blue W white K black m purple C gray-solid line: dotted line-dotted line

Data point icon:. Small black spots + addition * asterisks o Small circle pentagram

X =; y = sin (x); plot (X, Y, 'K: O ')

Plot (X, Y, 'O ')

X =. * PI; y = sin (x); plot (X, Y, 'r: O ');

Plot (X, Y, 'r :');

2) Coordinate System Control

In axis ([xmin xmax ymin Ymax]) [], the minimum and maximum values of the X and Y axes are given;

The axis equal X axis and Y axis have the same unit length. The axis squrare graph box is square axis off.

3) graphic tagging

X = linspace (0, 2 * Pi, 30); y = [sin (x); cos (x)]; plot (x, y );

GRID; xlabel ('x'); ylabel ('y'); Title ('sine and Cosine curves ');

Text (3 * PI/4, sin (3 * PI/4), '\ leftarrowsinx ');

Text (3 * pi/2, cos (3 * pi/2), 'cosx \ rightarrow ',...

'Horizontalalignment ', 'right ');

(The above command line can form an M file). hold on draws a new image on the original image.

Add the grid xlabel ylabel to X on the grid, and add the title to the entire graph on the Y axis.

Text gtext adds a string to a specific position in the image. if gtext ('sinx') is used instead of the command text, a cross line will appear in the graphic window, and its intersection is the string position. move the mouse to move the intersection point, and click the mouse to fix the string. the output result is as follows:

4) multiple images

How do I create multiple images in different coordinate systems on the same screen?

X = linspace (0, 2 * pi, 30); y = sin (x); z = cos (x); u = 2 * sin (x ). * cos (x); v = sin (x ). /cos (x); subplot (2, 2, 1), plot (x, y), title ('sin (x) '); subplot (2, 2 ), plot (x, z), title ('cos (x )');

Subplot (2, 2, 3), plot (x, u), title ('2sin (x) cos (x) '); subplot (2, 2, 4), plot (x, v), title ('sin (x)/cos (x )');

**2.4.2 3D images**

1) spatial curve

For example, for a spiral, type t = 0: pi/51: 10 * pi; plot3 (sin (t), cos (t), t );

2) Curved Surface with mesh

Composing surface. Type:

X =-7.5: 0.5: 7.5; y = x;

[X, Y] = meshgrid (x, y); % array of X and Y

R = sqrt (X. ^ 2 + Y. ^ 2) + eps; % + eps is to prevent 0/0

Z = sin (R)./R; mesh (x, y, z); % 3D mesh surface

3) contour lines

4) bar chart and Area Chart: The sales profit of a product in the first half of the year is profit, and the output value of the product sold each month is expense.

X =;

Expense = [21 34 89 25 22 90]; profit = [10 20 60 11 9 70]

Sale = [expense; profit]; area (x, sale)

**2.5 M file Compilation**

2.5.1 M file

1) command M file: A combination of some command lines. Function M file: defines the function program, with a specific format;

Example: Command M file: x = [2 3]; F = cos (X)

Function M file: function f = Cost (X)

F = 100 * (X (2)-x (1) ^ 2) ^ 2...

-(_X (1) ^ 2;

2) The form of the function M file is:

Function [output variable list] = function name (input variable List)

Function body statement:

2.5.2 four types of loops and Selection control structures

1) while

Relational Expression {statements}

End

S = 0; n = 1

While S <= 100

S = S + N ^ 2; n = n + 1;

End

N, S

2)

For x = X1: Step: Xn

{Statements}

End

For example, for k =

X (k) = 1/k;

End

Format rat % set the output format to rational number

X

For example, create a function M file to calculate the factorial of natural number n.

Function f = jch (n)

F = 1;

For I = 1: n

F = f * I;

End

3) switch expression (scalar or string)

Case value 1,

Statement body 1

Case {value: 2.1, value: 2.2 ,...}

Statement Body 2

...

Otherwise,

Statement body n

End

For x = x1: step: xn

{Statements}

End