# Practical is the best, teach you how to implement advanced applied mathematics problems in MATLAB (2)Practical is the best, teach you how to implement advanced applied mathematics problems in MATLAB (1)

## Preface

You can refer to the boutique column about the MATLAB series

MATLAB takes you from entry to master in 30 days

MATLAB in-depth understanding of advanced tutorial (with source code)

Friends you like can subscribe by themselves, and your support is my motivation for constant updates!

The first article in a series

Practical is the best, teach you how to implement advanced applied mathematics problems in MATLAB (1)

## Problems of Higher Applied Mathematics (001)

Operation questions today:

Start the MATLAB environment and give the statement:

tic,A=rand(500);B=inv(A);norm(A*B-eye(500)),toc，

Try to run the sentence, observe the result, and use the help command to query the help information of the sentence you are not familiar with, and give an explanation of the above block and result one by one.

1 、 tic ， toc

What is it for?

Must appear in pairs?

What is their role?

When do you need to add these two sentences?

2. Look at the help files of the four functions rand, inv, norm, and eye?

3. Compare the calculation time of the programs at both ends and store their time in an array.

【solution】

Practice and experience the following sentences in the MATLAB environment:

1. Solve the inverse of a 500 × 500 random matrix,

2. Find the product of the inverse matrix and the original matrix,

3. Find the difference between the result of 2 and the identity matrix, and find its norm.

Generally speaking, the accuracy obtained in this way can reach 10^−12.

>> tic, A=rand(500); B=inv(A); norm(A*B-eye(500)), toc

years =

1.2333e-012

Elapsed time is 1.301000 seconds.

Prompt: Question 1

Timing function in Matlab:

There are mainly tic, toc, cputime and etime. The timing function can quantitatively calculate the cpu time resources consumed to complete the specified program, which can be used as a parameter to compare the pros and cons of the program.

The tic and toc functions must appear in pairs and used in conjunction. tic indicates the beginning of timing, and toc indicates the end of timing.

The format is as follows:

tic

Arbitrary expression

heel

t=toc

cputime function

The cputime function returns the total cpu time used since the function was called, in seconds.

The format is as follows:

t=cputime;

Arbitrary expression or program

e = cputime-t;

etime function

The e=etime(t2,t1) command returns the time period between the vectors t1 and t2, and t1 and t2 must contain the 6 elements returned by the clock function;

Tip: Question 2

rand, generate random numbers

inv, inversion

norm, find the norm

eye, generate identity matrix

Tip: Question 3

It can record the return time t1 and t2 of the two programs, T=[t1,t2].

## Problems of Higher Applied Mathematics (002)

Use MATLAB statement to input matrix A and B matrix:

The A given above is a 4 × 4 matrix. If the command A(5, 6) = 5 is given, what result will be obtained?

Further on this basis, give the A(:,5)=[] command, what will be the result?

【solution】

Enter these two matrices directly:

>> A=[1  2  3  4; 4  3  2  1; 2  3  4  1; 3  2  4  1]

If the A(5,6)=5 command is given, although the number of rows and columns at this time is greater than the current dimension of the B matrix, the statement can still be executed.

>> A(5,6)=5

inferred:

Further on this basis, given the A(:,5)=[] command, the fifth column in the above matrix will be deleted:

>> A(:,5)=[]

Complex number matrices can also be entered with intuitive sentences:

>> B=[1+4i 2+3i 3+2i 4+1i; 4+1i 3+2i 2+3i 1+4i; 2+3i 3+2i 4+1i 1+4i; 3+2i 2+3i 4+1i 1+4i];

## Problems of Higher Applied Mathematics (003)

It can be calculated numerically

Try not to use the form of a loop to find the numerical solution of the sum.

Since the numerical method adopts the double form for calculation, it is difficult to guarantee the number of significant digits, so the result

Not necessarily accurate. Try to use symbolic operations to find the exact value of the sum.

[Solution] The following sentence can be used for symbolic operation

>> sum(sym(2).^[1:63])

years =

18446744073709551614

Since the result has 19 digits, the double type cannot accurately represent the result. This data type can represent up to 16 significant digits.

Its practical symbolic calculation method can retain significant numbers arbitrarily.

For example, the sum of 200 items or the sum of 1000 items can be obtained immediately by the following statement.

>> sum(sym(2).^[1:200])

years =

3213876088517980551083924184682325205044405987565585670602750

>> sum(sym(2).^[1:1000])

years =

214301721437253464189685009812000362112280962341106721488750077674070

210224987224498639675763139171625518934583510629365037429057138462808

719691551493971496078691355496484619708421492101247422837559083643060

929499671638825347975351183310878921541258291423929553730843353208596

63305248773674411336138750

Regarding the sum function sum:

>> help sum

sum Sum of elements.

S = sum(X) is the sum of the elements of the vector X.

If X is a matrix, S is a row vector with the sum over each column. For N-D arrays, sum(X) operates along the first non-singleton dimension.

S = sum(X,'all') sums all elements of X.

S = sum(X,DIM) sums along the dimension DIM.

S = sum(X,VECDIM) operates on the dimensions specified in the vector VECDIM. For example, sum(X,[1 2]) operates on the elements contained in  the first and second dimensions of X.

S = sum(...,TYPE) specifies the type in which the sum is performed, and the type of S.

Available options are:

'double'    -  S has class double for any input X

'native'    -  S has the same class as X

'default'   -  If X is floating point, that is double or single, S has the same class as X. If X is not floating point, S has class double.

S = sum(...,NANFLAG) specifies how NaN (Not-A-Number) values are treated.

The default is 'includenan':

'includenan' - the sum of a vector containing NaN values is also NaN.

'omitnan'    - the sum of a vector containing NaN values is the sum of all its non-NaN elements. If all elements are NaN, the result is 0.

Examples:

X = [0 1 2; 3 4 5]

sum(X, 1)

sum(X, 2)

X = int8(1:20)

sum(X)  % returns double(210), accumulates in double

sum(X,'native') % returns int8(127),

% because it accumulates in int8 but overflows and saturates.

## Problems of Higher Applied Mathematics (004)

Use MATLAB language to implement the following piecewise function

【solution】

Two methods,

First, use comparison expressions to solve

y=h*(x>D) + h/D*x.*(abs(x)<=D) -h*(x<-D);

Another method, using loop statements and conditional transfer statements

``for  i=1:length(x) if x(i)>D, y(i)=h; elseif abs(x(i))<=D, y(i)= h/D*x(i);  else, y(i)=-h; end end``

among them,

The former sentence structure is simple, but the scope of application is wider, allowing the use of matrix type x;

The latter can only use vector x, but cannot deal with matrix problems.

prompt:

Regarding the use of if statements:

>> help if

if Conditionally execute statements.

The general form of the if statement is

if expression

statements

elseif expression

statements

else

statements

end

The statements are executed if the real part of the expression has all non-zero elements.

The else and elseif parts are optional.

Zero or more elseif parts can be used as well as nested if's.

The expression is usually of the form expr rop expr where rop is ==, <, >, <=, >=, or ~=.

Example

``if I == J          A(I,J) = 2; elseif abs(I-J) == 1          A(I,J) = -1; else          A(I,J) = 0; end``

Regarding the use of the else statement:

Used with if.

else is used with if.

The statements after the else are executed if all the preceding if and elseif expressions are false.

The general form of the if statement is

if expression

statements

elseif expression

statements

else

end

## Problems of Higher Applied Mathematics (005)

Write a matrix addition function mat_add() so that its specific calling format is

The function is required to accept any number of matrices for solution operations.

【solution】

You can write the following function mat_add.m,

Use varargin variables to represent variable input variables.

``function A=mat_add(varargin) A=0; for  i=1:length(varargin),         A=A+varargin{i};  end``

If you want to get a proper error display, you can try the try, catch structure.

``function A=mat_add(varargin) try A=0; for i=1:length(varargin),  A=A+varargin{i};  end  catch,   error(lasterr);   end``

>> help try

try  Begin try block.

The general form of a try statement is:

try

statement, ..., statement,

catch me

statement, ..., statement

end

Normally, only the statements between the try and catch are executed. However, if an error occurs while executing any of the statements, theerror is captured into an object, me, of class MException, and the statements between the catch and end are executed. If an error occurs within the catch statements, execution stops, unless caught by another try...catch block.

The me argument is optional.

Begin catch block.

The general form of a TRY statement is:

try

statement, ..., statement,

catch me

statement, ..., statement

end

Normally, only the statements between the try and catch are executed. However, if an error occurs while executing any of the statements, the  error is captured into an object, me, of class MException, and the statements between the catch and end are executed. If an error occurs within the catch statements, execution stops, unless caught by another try...catch block.

The me argument is optional.

Write a MATLAB function yourself,

So that it can automatically generate an m × m Hankel matrix,

And make its call format:

``v=[h1, h2, hm, hm+1, · · · , h2m−1];   H=myhankel(v)。``

【solution】

There are many ways to solve such problems:

①The most direct method, Hi,j = hi+j−1, using double loop

``function H=myhankel(v) m=(length(v)+1)/2; % 严格说来还应该判定给定输入向量长度奇偶性 for i=1:m,       for j=1:m            H(i,j)=v(i+j-1);      end, end``

②Consider a certain row (or column), ai = [hi, hi+1, · · ·, hi+m−1], you can use a single loop to generate the Hankel matrix

``function H=myhankel(v) m=(length(v)+1)/2; % 严格说来还应该判定给定输入向量长度奇偶性 for  i=1:m,  H(i,:)=v(i:i+m-1); end``

③Using the existing hankel() function, then

``function H=myhankel(v) m=(length(v)+1)/2; % 严格说来还应该判定给定输入向量长度奇偶性 H=hankel(v(1:m),v(m:end));``