Some MATLAB tips (III)

Source: Internet
Author: User

The MATLAB document of China Southern Airlines Wang Zhengsheng last night contains some unfamiliar or important things, which are excerpted as follows.

1. malab is translated into matrix laboratories and is used to provide interfaces to linpack and eispack matrix packages. Later, it gradually developed into a general technology computing graphic Interaction System and programming language.

2. In the command window, ESC clears all contents of the current line.

3. [Example 3] matrix element input
> B (1, 2) = 3; B (4, 4) = 6; B (4, 2) = 11
B =
0 3 0 0
0 0 0 0
0 0 0 0
0 11 0 6
This is actually a method of creating a matrix. The maximum coordinate has been given by the matrix dimension. For example, in this example, the maximum value of the row coordinate is 4 given in B () and B (), and the maximum value of the column coordinate is 4 given by B, therefore, the matrix dimension is 4x4.

5. Note: Matlab is case sensitive!

6. The roles of the WHO and whos commands are to list the variable names that reside in the MATLAB workshop. However, while giving variable names, whos also gives their dimensions and properties.

7. Several variables defined by the system itself at startup (The following table) reside in the MATLAB working memory are called permanent variables or predefined variables ).

System predefined Variables
EPS The smallest positive number of the computer, which is 2 ^ (-52) on the PC)
Pi The approximate value of the circumference rate π is 3.14159265358979
INF or inf Infinity
Nan Not quantitative
I, j Virtual number unit definition I = J = (−1) ^ (1/2)
Flops Number of floating-point operations, used to calculate the amount of Computing

Note: 1 they are customized when Matlab is started;
2. They will not be cleared by the clear memory variable command;
3. They can be redefined as other values, but clear the pre-defined values with clear.

8. Help elfun -- list all basic functions
Help directory name -- display all commands and functions in the specified directory

9. The lookfor command can search for a group of related commands based on the complete or incomplete keywords provided by the user.
[Example 2] search for Fourier transform commands
Lookfor Fourier
Lookfor command mechanism: scans the first line of each M file comment area in MATLAB, and displays the string that contains the query.

10. Create a numerical matrix using the command reshape
AV = % the row vector that generates 12 elements. AV starts with % and comments rows.
Bm = reshape (AV, 3,4) % create a 3 × 4 matrix BM using vector AV
AV =
1 2 3 4 5 6 7 8 9 10 11 12
Bm =
1 4 7 10
2 5 8 11
3 6 9 12

11. Use the diag command to generate a diagonal array.
AR = rand () % generates a 4 × 4 0-1 uniform distribution. Then the matrix Ar
D = diag (AR) % form a vector D with the primary diagonal element of the matrix
D = diag (d) % uses vector d to form a diagonal matrix D
AR =
0.9501 0.8913 0.8214 0.9218
0.2311 0.7621 0.4447 0.7382
0.6068 0.4565 0.6154 0.1763
0.4860 0.0185 0.7919 0.4057
D =
0.9501
0.7621
0.6154
0.4057
D =
0.9501 0 0 0
0 0.7621 0 0
0 0 0.6154 0
0 0 0 0.4057

12. [Example] matrix ID
X = [1 2 3 4 5] % to generate a 1 × 5 vector
X =
1 2 3 4 5
L = x <= 3% mark the position of the element less than or equal to 3
L =
1 1 1 0 0
X = x (l) % to obtain a subvector with no more than 3 elements
X =
1 2 3

13. Calculate the inverse of the inv (a) matrix.
F (a) calculates the function values of each element of.

14. inv commands are not very useful in MATLAB. MATLAB recommendation: Do not use inverse operations if possible!

15,Rand ('seed', 12 );% Select the random seed, that is, the starting value in the rand () algorithm. The purpose is to generate the same random number repeatedly.
For example:

> Rand ('seed', 12); Rand

Ans =

0.1549

> Rand ('seed', 12); Rand

Ans =

0.1549

If seed is not used, the random numbers are different each time:

> Rand

Ans =

0.6048

> Rand

Ans =

0.5040

16. When designing the inverse function inv, Matlab adopts the Gauss elimination method. When the left division operation solves the exact equation, it does not calculate the inverse but directly uses the Gauss elimination method to solve the problem, which effectively reduces the residual. Therefore, a better result can be obtained even under the high condition number.

17. Matrix Division Method for Solving Over-definite equations
(1) solutions for normal equations (ATA) x = at B.
(2) Use Householder transformation (Householder transformation) to directly obtain the least square solution of the original hyperdefinite equation.
Because the second method adopts orthogonal transformation, the accuracy and reliability of the solution obtained by the second method are much better than those obtained by the first method according to the least square theory. The second method is used for MATLAB to solve hyperdefinite equations.

18. Matrix Division
The solution of the undetermined equation is not unique. The solution obtained by Division has two important features: (1) There are at most rank (a) non-zero elements in the solution; (2) it is the smallest norm in this type of solution.

19, polynomial p (x) = a0xn + a1xn-1 +...+ An-1x + an, representing P = [A0, A1,..., An-1, an].

20. MATLAB Convention: polynomial coefficients are represented by row vectors, and a group of roots are represented by column vectors.

21, P = polyfit (X, Y, n) fitting the data given by the X and Y vectors with the nth Polynomial

22. Effective fitting interval diagram (use [0, 2.5] interval data to fit the [] interval data)
X = 0: 1: 5;
X1 =.. 5
Y = ERF (x); % error function
Y1 = ERF (X1 );
P = polyfit (x1, Y1, 6)
F = polyval (p, X );
Plot (X, Y, 'bo', X, F, 'r -')
Axis ([0, 5, 0, 2])
Legend ('fitting curve ', 'original cable ')

23. polynomial nonlinear function root r = roots (P)
Example P = [1 2 3 4];
R = roots (P)
R =
-1.6506
-0.1747 + 1.5469i
-0.1747-1.5469i

24. Single-variable nonlinear equation solving (single-Variable Function finding zero point)
Z = fzero ('fname', x0, Tol, trace)
Fname indicates the name of the function to be root searched. x0 indicates the start point of the search. A function may have multiple roots, but fzero only gives the root closest to x0; the relative precision of the tol control result. If Tol = EPS is missing, trace specifies whether the iteration information is displayed in the operation. If it is 1, it is displayed. If it is 0, it is not displayed, missing time trace = 0.

25. solving general nonlinear equations (groups)
This part of content is beyond the scope of the "main package" of Matlab, and it needs to use the optimization toolkit of Matlab. However, since nonlinear equations are a type of mathematical problem commonly encountered, we will briefly introduce the instructions for solving general nonlinear equations f (x) = 0 and their numerical solutions x.
X = fsolve ('fname', X0)
Fname indicates the name of the function to be root; x0 indicates the initial prediction value of the solution.

26. ode45 is less efficient than ode23's integral Segmentation

27. Execute an external program
Exclamation point (!) Is a special command of Matlab. It indicates that the subsequent command is an operating system command! You can execute other programs or operating system commands without exiting Matlab. This is useful.
Example: >>! Notepad XXX. m
Use NotePad to open the XXX. M file.

28. Read Binary data files
The fread function can read binary data files. For example, read and write all data unsigned characters in WZS. dat to the moment.
In array,
FID = fopen ('penny. dat ', 'R ');
A = fread (FID );
Ststus = fclose (FID );
The fread function can also have two parameters to control the number of read data and the accuracy of each data. For example, read the first 100 unsigned data characters of WZS. dat into and write them to matrix,
FID = fopen ('wzs. Dar ', 'R ');
A = fread (FID, 100 );
Ststus = fclose (FID );
Or read the first 100 data records of WZS. dat and combine them into a 10th-order matrix.
FID = fopen ('wzs. Dar ', 'R ');
A = fread (FID, [10 10]);
Ststus = fclose (FID );

29. Write binary data files
The Write function of MATLAB corresponds to the fread function. Its function is to write elements in the matrix into a file and return the number of written data according to the specified data precision. For example, you can create a 100-byte binary file that contains 25 RMB of the 5-level cube matrix.
Each element is stored in a 4-byte integer format. In the variable count, the return value of the fwrite function is 25:
Fwriteid = fopen ('Magic. bin', 'w ');
Count = fwrite (fwriteid, magic (5), 'integer * 4 ');
Status = fclose (fwriteid );

30, Taylor (F, n, a) -- function f is the symbol variable of the symbol variable X or the symbol variable closest to the letter X, in the n-1 order Taylor Polynomial of the point (the default value of N is 6, A defaults to 0 ).
For example:
Taylor (sin (x ))
Ans = X-1/6 * x ^ 3 + 1/120 * x ^ 5

F = Log (X)
S = Taylor (F, 4, 2)
F = Log (X)
S = Log (2) + 1/2 * x-1-1/8 * (X-2) ^ 2 + 1/24 * (X-2) ^ 3

31. A very simple Drawing Instruction
If expression F has only one symbol variable, for example, X, then ezplot (F, xmin, xmax) draws the x-axis curve F, X in [xmin
In xmax], the default value is xmin =-2PI and xmax = 2PI.
Example
Ezplot (sin (2 * X ))
Ezplot (sin (2 * X),-PI/2, PI/2)

32. Plot plot Linearity:

O or O Circle
X or X Cross
+ Plus sign

33. Add the legend ('sin (x) ', 'cos (x )');

34. The Fplot function can automatically sample the function to better reflect the variation of the function.
Function Format: Fplot (fname, LIMS, Tol), where fname is the function name and appears as a string; LIMS is the value range of the variable; Tol is the relative allowable error, and its default value is 2e-3.
For example:
Fplot ('sin (x) ', [0 2 * Pi],'-+ ')
Fplot ('[sin (x), cos (x)]', [0 2 * Pi], 1e-3 ,'*')
Fplot ('cos (TAN (pI * X) ', [0, 1], 1e-4)

It can be seen that the sampling points are very intensive when the coordinates are infinitely oscillating near the 0.5 coordinate. If the same interval sampling is used, the function variation is not reflected.

35. Pause Function
When running a program, you can use the pause function to view the intermediate results of the program or view the output graphics. The call format is:
Pause (delay in seconds)
If the delay time is omitted and pause is used directly, the program will be suspended until the user continues to execute the program after one click.

36 ,~ = Not equal

37. MATLAB has a difference in function calling: The tonality of the number of parameters passed by a function .. With this, a function can complete multiple functions. When calling a function, Matlab uses two permanent variables, nargin and nargout, to record the number of input real parameters when calling the function. By using these two variables in the function file, you can accurately know the number of input and output parameters when the function file is called, thus determining how the function is processed.
Function file examp. M:
Function fout = charray (A, B, C)
If nargin = 1
Fout =;
Else if nargin = 2
Fout = A + B;
Else if nargin = 3
Fout = (a * B * C)/2;
End

------

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.