matlab---basic knowledge

Table of contents

foreword

1. Matlab system environment

1. The interface of matlab

 Newline

 2. Set the current folder

 How to create the cd function

​Edit 3. Tool area window

 4. Simple assignment application

5. Matlab search path

How to set the file search path

 think:

Two, matlab numerical data

1. Classification of numeric data types

2. Numeric data output format

3. Common mathematical functions

(1) The calling format of the function is:

(2) Application of common functions

 (3) Example of function application

3. Variables and their operations

1. Variables and assignment statements

2. Assignment statement

3. Predefined variables

4. Variable management

(1) Deletion and modification of memory variables

(2) Memory variable file

4. Representation of matlab matrix

1. Establishment of matrix

2. Colon expressions

 3. Structural matrix and unit matrix

5. Reference of matrix elements

1. Reference method of matrix elements

    (1) Refer to the elements of the matrix by subscript

     (2) Reference by serial number

               (3) Use logical symbols to quote

Six. MATLAB basic operations

1. Arithmetic operations

2. Relational operations

3. Logical operations

Seven. String processing

1. String representation

2. String operations

(1) Execution of strings

 (2) Conversion between string and value

(3) Comparison of strings

(4) Find and replace strings

Summarize


foreword

Matlab Section 1: Basic knowledge

1. Matlab system environment

1. The interface of matlab

 Newline

 2. Set the current folder

 How to create the cd function

 3. Tool area window

 4. Simple assignment application

 clear: Clear the screen.

Introduction to format

5. Matlab search path

Variables --> Internal Functions --> Program Files --> Program Files in the Current Folder --> Program Files in Folders in the File Search Path

If you define a variable, don't use an existing specific function name.

How to set the file search path

1. Use the path command to set the file search path. For example:

>>path(path,'e:\mat.work')

2. Use the dialog box to set the file search path.

clc: Clear all commands.

help elfun: find some easy functions

Place the cursor on an unknown function and press the F1 key to find out the meaning of the function

 think:

(1) If an M file with the same name is created under the current folder and the search path folder, which file will be executed when the file name is entered in the command line window?

Program file search order Now search in the current folder and then in the file search path

(2) If the file created by the user is neither saved in the folder nor in the file search path, what information will appear when the file name is entered in the command line window?

error message

Two, matlab numerical data

1. Classification of numeric data types

1. Integer:

(1) Unsigned: 8 bits (00000000~11111111)

(2) Signed: 8 bits (10000000~01111111)

The uint8 function converts numeric data to an unsigned 8-bit integer, and the int8 function converts numeric data to a signed 8-bit integer

>>x=int8(129)
x=
   127  %%带符号的最大为127,所以转换时只能转成127
>>x=uint8(129)
x=
   129  %%无符号的最大为255,所以转换后仍为129

2. Floating point type:

(1) Single precision: four bytes

(2) Double precision: eight bytes (higher precision) (numeric data defaults to double precision)

Use single to convert other types of numbers to single precision.

Using double, convert to double precision

>>class(4)
ans=
double   %%调用class函数
>>class(single(4))
ans=
single   %%调用single函数

3. Plural:

The complex number type includes real part and imaginary part. The real part and imaginary part are double precision by default, and the unit of imaginary part is represented by i or j.

>>6+5i
ans=6.0000+5.0000i
>>6+5j
ans=6.0000+5.0000i

Use the real function to find the real part and the imag function to find the imaginary part 

2. Numeric data output format

The format of the format command: format format character

>>format long
>>50/3
ans=16.666666666666668
>>format
>>50/3
ans=16.6667   %%format只影响数据输出格式不影响其定义

3. Common mathematical functions

(1) The calling format of the function is:

    function name (value of function argument)

            The argument of the function is specified as a matrix variable, of course, it can also be a scalar, and the scalar itself is a special case of the matrix.

            When the function is operated, the function is applied to each element of the matrix item by item, so the result of the final operation is a matrix with the same type as the argument

>>A=[4,2;3,6]
A=
  4  2
  3  6  %%创建矩阵A 2*2
>>B=exp(A)
B=
  54.5982   7.3891
  20.0855 403.4288    %%调用exp函数,求自然指数
                         B中数据均为A求自然指数所对应

(2) Application of common functions

     1. Trigonometric functions have functions with radian as the unit and functions with angle as the unit. If the function is with angle as the unit, add "d" after the function name to show the difference.

>>sin(pi/2)
ans=
    1
>>sind(900
ans=
    1

   2. The abs function can find the absolute value of a real number, the modulus of a complex number, and the ASCII value of a string

>>abs(-4)
ans=
   4
>>abs(3+4i)
ans=
   5
>>abs('a')
ans=
  97

  3. Rounding function

 The round function rounds to integers according to the rounding rules

 The ceil function rounds up, taking the first integer greater than or equal to this number

 The floor function rounds down to take the first integer less than or equal to this number

 The fix function is fixed to take a number close to 0, rounding off the decimal

4. Character length

intmin(int8)=-128: the minimum range of int8 is -128

intmax(int8)=127 : the maximum range of int8 is 127

realmax: the largest positive floating point number (only for double, single)

realmin: minimum

 (3) Example of function application

Respectively find a three-digit positive integer, tens, hundreds

>>m=345
>>m1=rem(m,10)  %%相当于a%b
m1=
  5
>>m2=rem(fix(m/10),10)   %%fix函数取靠近0的整数
m2=
  4
>>m3=fix(m/100)
m3=
  3

 Find [1, 100] all prime numbers

MATLB provides a function isprime(n) to determine whether n is a prime number, and returns 1 when n is a prime number, otherwise returns 0.

>>x=1:100;   %%生成1到100间所有整数组成的向量x
>>k=isprime(x);   %%调用isprime函数
>>k1=find(k);   %%调用find函数(找出函数中非0数)
>>p=x(k1)  %%输出全部素数
p=
  1至15列
    2  3  5  7  11  13  17  19  23  29  31  37  41  43  47
  16至25列
    53  59  61  67  71  73  79  83  89  97

3. Variables and their operations

1. Variables and assignment statements

  Variables are essentially an abstraction of memory units

  In matlab, a variable name is a sequence of characters beginning with a letter followed by letters, numbers or underscores, up to 63 characters.

Notice:

(1) Variable names are case-sensitive.

(2) Standard function names and commands must use lowercase letters

2. Assignment statement

(1) variable = expression

(2) Expression

3. Predefined variables

  variables defined by the system itself

        ans is the default assignment variable

        i and j represent imaginary units

        pi stands for pi

        NaN represents a non-number (the part you want to cut off, set its coordinate data to NaN)

 inf: short for infinity

In matlab nan is different in different cases. Example: (d)

~: 1. stands for not 2. stands for ignoring output data

For (f) '~' description negation

4. Variable management

(1) Deletion and modification of memory variables

  

a. Right click in the workspace to modify

b. who command and whos command

 Using these two commands, you can display the contents of the workspace

(2) Memory variable file

     The file used to save the variables in the matlab workspace is called a memory variable file, and its extension is .mat, also called a MAT file

save command: create memory variable file

load command: load memory variable file

>>save mydata a x  %%把a x存入mydata文件中,下次就可以使用
>>load mydata    %%将mydata文件中的内容存入此次工程中

4. Representation of matlab matrix

1. Establishment of matrix

(1) Create a matrix using the direct input method: enclose the elements of the matrix in square brackets , input the elements in the order of the matrix rows, separate the elements in the same row with commas or spaces , and use commas between elements in different rows number interval.

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

     A=

            1   2   3

             4   5   6

(2) Use the established matrix to build a larger matrix: a large matrix can be spliced ​​from the established small matrices.

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

>>B=[-1,-2,-3;-4,-5,-6;-7,-8,-9];

>>C=[A,B;B,A]

Complex matrices can be constructed using real and imaginary part matrices.

>>B=[1,2,3;4,5,6];

>>C=[6,7,8;9,10,11];

>>A=B+C*i

A=

      1.0000+6.0000i 2.0000+7.0000i ......

vector is a special type of matrix

2. Colon expressions

(1) format

 (2) linspace function

 3. Structural matrix and unit matrix

(1) Structure matrix

      The format is:

              struct matrix element.membername=expression

   >>a(1).x1=10;a(1).x2='liu';a(1).x3=[11,21;34,78];

%% Assign values ​​to the first, second and third elements of matrix a1

(2) Cell matrix

     Building a unit matrix is ​​similar to a general matrix, just input it directly, but the unit matrix is ​​enclosed in braces.

>>b={10,'liu',[11,21;34,78];12,'wang',[34,191;27,578];...

14,'cai',[13,890;67,231]}

5. Reference of matrix elements

1. Reference method of matrix elements

    (1) Refer to the elements of the matrix by subscript

        A[3,2] represents the element in the 3rd row and 2nd column of the A matrix.

        >>A(3,2)=200 %% only changes the amount of elements at this place

Example: When %% is insufficient, 0 is automatically filled to make the matrix complete, as in the example

     (2) Reference by serial number

There is a one-to-one correspondence between the serial number and the subscript. Taking the m*m matrix A as an example, the serial number of the matrix element A(i, j) is (j-1)*m+i

  The subscripts of the matrix elements can be converted to each other using the sub2ind and in2sub functions

   sub2ind function: Convert the row and column subscripts of the specified elements in the matrix into stored serial numbers. The calling format is:

D=sub2ind(S,I,J)

D: Corresponding serial number

S: vector of row and column numbers

I: the row index of the transformation matrix element

J: the column subscript of the transformation matrix element

  int2sub function: will convert the serial number of the matrix element into the corresponding subscript, and its calling format is:

[I,J]=ind2sub(S,D)

[I,J]: row subscript

S: vector of row and column numbers

D: serial number

[3,3]: Matrix with 3 rows and 3 columns

1, 3, 5 represent the corresponding subscripts (1,1) (3,1) (2,2)

 Obtain submatrix using colon expression

end operator: Indicates the subscript of the end element of a certain dimension

Delete elements of a matrix using an empty matrix

An empty matrix is ​​a matrix without any elements

>>x=[]

x=

     []

x is an empty matrix

change the shape of the matrix

reshape(A,m,n): On the premise that the total elements of the matrix remain unchanged, rearrange the matrix into a two-dimensional matrix of m*n

Note: The reshape function only changes the number of elements of the original matrix and their storage order

 (3) Use logical symbols to quote

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

veac =

     1     2     3     4     7     8     9     5     6

>> v = [ 1 0 1 1 0 1 0 0 1 ]

v =

     1     0     1     1     0     1     0     0     1

>> veac(v)
数组索引必须为正整数或逻辑值。
 
>> v = logical([ 1 0 1 1 0 1 0 0 1 ])

v =

  1×9 logical 数组

   1   0   1   1   0   1   0   0   1

>> veac(v)

ans =

     1     3     4     8     6

Note that the normal input vector is not a logical vector, but a double type, so it must be converted into a logical type before array indexing can be performed. 

Six. MATLAB basic operations

1. Arithmetic operations

(1) Basic arithmetic operations

    Basic arithmetic operators: +, -, *, / (right division), \ (left division)

Arithmetic operations in MATLAB are performed in the sense of matrices

Arithmetic operations on single data are just a special case of matrix operations

a. Addition and subtraction

If two matrices are of the same type, the corresponding elements of the two matrices are added and subtracted during operation.

If the two matrices are of different types, MATLAB will give an error message.

b. Multiplication operation

Matrices A and B are multiplied, and the columns of A are required to be consistent with the rows of B. It is said that A and B can be multiplied, or the dimensions or sizes of A and B matrices are compatible.

Differing Dimensions Error

c. Division operation

In MATLAB: right division '/' and left division '\' 

If the A matrix is ​​a non-singular square matrix, then A/B is equivalent to B* inv (A), and B\A is equivalent to inv (A)*B.

For matrices, right division and left division represent two different divisor matrix and dividend matrix relationships

b. Power operation

The power operation of a matrix can be expressed as A^x, requiring A to be a square matrix and x to be a variable.

(2) Point operation

Dot operator: .* ; ,/ ; ,\ ; ,^

The correlation operation of two matrices refers to the correlation operation of their corresponding elements, requiring that the two matrices have the same type

2. Relational operations

Relational operators: <, <=, >, >=, ==, ~= (not equal to)

(1) When the two comparison quantities are scalars, directly compare the size of the two numbers, and output 0 if not established, otherwise output 1.

(2) When the quantities involved in the comparison are two matrices of the same type, the comparison is performed on the elements at the same position of the two matrices one by one according to the scalar relational operation rules , and the final result of the relational operation is a matrix of the same type as the original matrix, which Consists of 0 and 1.

(3) When a scalar and a matrix are involved in the comparison, each element of the matrix is ​​compared one by one according to the scalar relational operation rules , and the final result of the relational operation is a matrix with the same type as the original matrix, consisting of 0 or 1 

 rem function and mod function

3. Logical operations

Logical operators: & | ~ (monocular operation)

Arithmetic Operations > Logical Operations

Monocular operation (only one variable is required for operation) > binocular operation (two variables are required for operation)

Seven. String processing

1. String representation

  In matlab, strings are sequences of characters enclosed in single quotes

>> xm='Njtech University'
>> xm(1 , 3)   %取字符串1到3的字符
ans =
Njt

If a character in the string contains a single quotation mark, the single quotation mark character must be represented by two single quotation marks.

>> 'I''m a teacher.'
ans =
I'm a teacher

Build a multiline string, forming a matrix of strings.

>> ch=['abcdef';'123456']; %两行的矩阵
>> ch(2,3)
ans=
  3

example

Create a vector of strings, then do the following with the vector:

1) Take the substring composed of the 1st to 5th characters.

2) Take the string upside down and rearrange it.

3) Change the lowercase letters in the string to the corresponding uppercase letters, leaving the rest of the characters unchanged.

4) Count the number of lowercase letters in the string

>>ch='ABc123d4e56Fg9';
>>subch=ch(1:5)    %取出1~5位的字符
subch=
ABc12
>>revch=ch(end:-1:1)   %输出从最后一位开始,以-1为步长移动,到第一位结束
revch=
9gF65e4d321cBA
>>k=find(ch>='a'&ch<='z')  %查找出小写字母
k=
  3 7 9 13
>>ch(k)=ch(k)-('a'-'A')  %将小写字母加上32,通过ASCII改变该字母为大写
ch=ABC123D4E56FG9
>>length(k)
ans=
   4

2. String operations

(1) Execution of strings

        Format: eval(s) s is a string

>>t=pi;
>>m='[t,sint(t),cos(t)]';   %m为字符串
>>y=eval(m)
y=
  3.1416   0.0000   -1.0000

 (2) Conversion between string and value

     1) Both the abs and double functions can be used to obtain the ASCII code value matrix corresponding to the string matrix

     2) The char function can convert the ASCII code matrix into a string matrix

>>s1='MATLAB';
>>a=abs(s1)
a=
  77 65 84 76 65 66
>> char(a+32)
ans=
matlab

(3) Comparison of strings

   There are two ways to compare strings: using relational operators or string comparison functions.

  1) Comparison of relational operators: Each character in the two strings is used to compare the size of the ASCII value. The result of the comparison is a numerical vector, and the elements in the vector are either 1 or 0.

>>'www0'>='W123'

ans=

    1    1     1    0

2) The string comparison function is used to judge whether the strings are equal. There are four comparison methods. The functions are as follows:

strcmp(s1, s2): used to compare whether the strings s1 and s2 are equal, if they are equal, return the result 1, otherwise return 0;

strncmp(s1, s2, n): used to compare whether the first n characters of strings s1 and s2 are equal, if they are equal, return the result 1, otherwise return 0;

strcmpi(s1, s2): Under the premise of ignoring the case of letters, compare whether the strings s1 and s2 are equal, if they are equal, return the result 1, otherwise return 0;

strncmpi(s1, s2, n): Under the premise of ignoring the case of the letters, compare whether the first n characters of the strings s1 and s2 are equal, if they are equal, return the result 1, otherwise return 0

s1 = 'matlab';
s2 = 'matlab';
strcmp(s1,s2)
ans=
   1
s3 = 'matlab';
s4 = 'mat';
strncmp(s3,s4,3)
ans=
   1
s5 = 'Matlab';
s6 = 'MATLAB';
strcmpi(s5,s6)
ans=
   1
strncmpi(s5,s6,1)
ans=
   1

(4) Find and replace strings

  findstr(s1,s2): Returns the starting position of the short string in the long string.

  strrep(s1,s2,s3): Replace all string s2 in string s1 with string s3

>>p=findstr('This is a test!','is')
p=
  3  6
>>p=findstr('is','This is a test!')  %%空格也算一个字符
p=
  3  6
>>result=strrep('This is a test!','test','class')
result=
This is a class!

Summarize

The approximate number of basic knowledge of matlab

Guess you like

Origin blog.csdn.net/weixin_62436283/article/details/122540161