WeChat Official Account: Math Sentiment Click above to select Star or Top, and receive valuable content every day.
!
This layout uses md2All, a markdown formatting tool that can display the current preview correctly on platforms such as WeChat Official Accounts, Blog Garden, Juejin, CSDN, etc.
Introduction
With less than a month until the Mathematical Contest in Modeling, I am writing a complete MATLAB tutorial. This article is suitable for students with no background in MATLAB, but it can also serve as a refresher for those who are familiar with it. Common mathematical software includes<span>Maple, Mathematica, MATLAB</span>
, etc.; common large statistical software includes<span>SAS, SPSS, Hadoop</span>
, etc. Below, I will mainly introduce some MATLAB tutorials. MATLAB has five general functions: numerical computation (Numeric), symbolic computation (Symbolic), data visualization (Graphic), unified processing of data graphics and text (Notebook), and modeling and simulation visualization (Simulink).
MATLAB is widely used in theoretical research and engineering design in various fields, including linear algebra, matrix analysis, numerical computation, optimization problems, mathematical statistics, random signal analysis, circuits and systems, modeling, and simulation. It was launched by the American company Mathworks in 1984. The software has three main characteristics: first, it is powerful; second, it has a friendly interface and natural language; third, it has strong openness. The current version of MATLAB is MATLAB 2018.
Introduction to MATLAB
First, we need to understand what an M-file is, which has three points: (1) If we want to flexibly use MATLAB to solve practical problems and fully utilize MATLAB’s scientific and technical resources, we need to edit M-files; (2) Files containing MATLAB language code are called M-files, with the extension .m; (3) M-files can be edited using various text editors. Then, we store the program composed of MATLAB statements as files with the .m extension and execute the program file. This working mode is called program file mode. The syntax of M-files is generally similar to C language but has its own characteristics. It is just a simple ASCII text file that interprets and runs the program line by line during execution. MATLAB is an interpreted programming language.
There are two types of M-files
-
Independent M-files — called command files: They are actually a collection of instructions, and executing all instructions in the command window line by line yields the same result. There are no input or output parameters.
Command files consist of two parts: comment files and program files
%RANK Number of linearly independent rows or columns.
% K = RANK(X) is the number of singular values of X
% that are larger than MAX(SIZE(X)) * NORM(X) * EPS.
% K = RANK(X,tol) is the number of singular values of X that
% are larger than tol.
% Copyright (c) 1984-94 by The MathWorks, Inc.
s = svd(x);
if (nargin == 1)
tol = max(size(x)) * max(s) * eps;
end
r = sum(s > tol);
-
Calling M-files — called function files: MATLAB’s custom function files are called built-in function files. The method to call built-in functions is to use the function name and provide the corresponding entry and exit parameters. For example: sin.m function — cannot be found using type sin. Calling format: y=sin(2*x). In practical applications:
x=0:2*pi/180:2*pi;
y=sin(2*x)
plot(x,y)
MATLAB Program Structure and Operators
The program structure of the MATLAB language is consistent with other high-level languages, divided into sequential structure, loop structure, and branching structure.
-
Sequential structure — executes each statement in the program in order;
-
Loop structure — a group of statements executed repeatedly; loops are the main means for computers to solve problems. — Loop statements mainly include: (1) for -end (with executable statements in between); (2) while -end; (3) branching structure (if — else — end statements have three forms, and elseif can replace the switch-case-end statements in general high-level languages).
In conditional expressions, they usually consist of
-
Relational operators >, <, <=, >=, ==, ~=, etc.
-
Logical operators &, |, ~, etc.
-
Logical functions: isequal — true if equal; isempty — true if empty matrix; isstr — true if string.
MATLAB operators are divided into five categories: mathematical, relational, logical, bitwise, and set.
Mathematical operators: perform various mathematical operations, in order of priority:
-
Transpose .’, conjugate transpose ‘, power .^, matrix power ^
-
Positive, negative signs +, –
-
Multiplication .*, matrix multiplication, element-wise left division .\, ./, matrix left division \, /
-
Addition and subtraction +, –
-
The colon : completes operations from left to right at the same priority level, and when the order of operations is uncertain, it is best to enforce the order of operations using parentheses “()”.
For matrices, right division A/B is equivalent to the solution matrix X for B=A, while left division Aackslash B is equivalent to the solution matrix A*X=B.
Relational operators: there are six relational operators ==, ~=, >, >=, <, <=
Relational operators always perform element-wise operations on matrices; if the relation holds, it returns 1, otherwise, it returns 0.
Logical operators: there are three: & (and), | (or), ~ (not)
Related commands include: all(), any(). When all vector elements are “true”, all returns 1, while any returns 1 when any element is “true”.
Bitwise operators: logical operations on non-negative integers, with the following main functions:
-
bitand(): bitwise AND
-
bitor(): bitwise OR
-
bitxor(): bitwise XOR
-
bitset(): set a bit
-
bitget(): get a bit
-
bitcmp(): bitwise NOT
-
bitshift(): bit shift (left shift)
Set operators: limited to vector operations, where MATLAB treats vectors as sets to perform various set operations, with commonly used commands as follows:
-
Union(): union
-
intersect(): intersection
-
setdiff(): difference
-
setxor(): exclusive or
-
unique(): minimal equivalent set
-
ismember(): whether an element belongs to a set
Custom Functions in MATLAB
First, let’s write a piece of code in the command window. After creating the script, press F5 to run, and you can obtain:
for i = 1 : 10
x = linspace(0,10,101);
plot(x,sin(x + i));
print(gcf,'-deps',strcat('plot',num2str(i),'.ps'));
end
In the process of mastering MATLAB, we need to grasp several commonly used shortcuts:
-
%: single-line comment
-
ctrl + r: multi-line comment
-
ctrl + t: cancel multi-line comment
-
ctrl + i: smart indent
-
%%: specify section
-
ctrl + enter: execute section
-
f5: run program
Next, let’s take an example of the LMS algorithm to create the first MATLAB function:
MATLAB Plotting
The powerful plotting function is one of MATLAB’s features. MATLAB provides a series of plotting functions, and users do not need to worry too much about the details of plotting; they only need to provide some basic parameters to obtain the desired graphics. These functions are called high-level plotting functions. In addition, MATLAB also provides low-level plotting operations that directly manipulate graphic handles. Such operations treat each graphic element (such as axes, curves, text, etc.) as an independent object, and the system assigns a handle to each object, which can be used to manipulate that graphic element without affecting other parts.
Plotting Syntax
plot(X,Y) % Create a 2D line plot of data in Y against corresponding values in X.
plot(X,Y,LineSpec) % Set line style, marker symbol, and color.
plot(X1,Y1,…,Xn,Yn) % Plot multiple sets of X,Y pairs, all using the same coordinate area.
plot(X1,Y1,LineSpec1,…,Xn,Yn,LineSpecn) % Set the line style, marker symbol, and color for each line.
plot(Y) % Create a 2D line plot of data in Y against each index value.
plot(Y,LineSpec) % Set line style, marker symbol, and color.
plot(_,Name,Value) % Specify line properties using one or more Name,Value pair arguments.
plot(ax,_) % Create lines in the coordinate area specified by ax, rather than in the current coordinate area (gca).
h = plot(_) % Returns a column vector of graphic line objects.
-
1. Create a line plot
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
-
2. Plot multiple lines
x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);
figure
plot(x,y1,x,y2)
-
3. Specify line style
x = 0:pi/100:2*pi;
y1 = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);
figure
plot(x,y1,x,y2,'–',x,y3,':')
-
4. Specify line style, color, and marker
x = 0:pi/10:2*pi;
y1 = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);
figure
plot(x,y1,'g',x,y2,'b–o',x,y3,'c*')
-
5. Specify line width, marker size, and marker color
x = -pi:pi/10:pi;
y = tan(sin(x)) - sin(tan(x));
figure
plot(x,y,'–gs',…
‘LineWidth’,2,…
‘MarkerSize’,10,…
‘MarkerEdgeColor’,’b’,…
‘MarkerFaceColor’,[0.5,0.5,0.5])
-
6. Add title and axis labels
x = linspace(0,10,150);
y = cos(5*x);
figure
plot(x,y,'Color',[0,0.7,0.9])
title(‘2-D Line Plot’)
xlabel('x')
ylabel('cos(5x)')
-
7. Create and modify lines
x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);
p = plot(x,y1,x,y2);
… omitted several parts
Applications of MATLAB in Mathematical Modeling
1. Population Prediction Model
Example 1: The table below shows the population data of a certain region from 1971 to 2000. Try to provide a mathematical model for the population growth in this region. The scatter plot made from the data shows that the population changes over time in a nonlinear process and that there exists an asymptote parallel to the horizontal axis, so a Logistic curve model can be used for fitting.
Establish a population.m file. Since the form of the logistic curve model is y=1/(a+be^-t), we only need to assume y*=1/y, x*=e^-t, which can transform it into a linear model y*=a+bx*. The fitting program is as follows:
clear
clc
% Read population data (1971-2000)
Y=[33815 33981 34004 34165 34212 34327 34344 34458 34498 34476 34483 34488 34513 34497 34511 34520 34507 34509 34521 34513 34515 34517 34519 34519 34521 34521 34523 34525 34525 34527]
% Read time variable data (t=year-1970)
T=[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30]
% Linearization processing
for t = 1:30,
x(t)=exp(-t);
y(t)=1/Y(t);
end
% Calculate and output regression coefficients B
c=zeros(30,1)+1;
X=[c,x'];
B=inv(X'*X)*X'*y'
for i=1:30,
% Calculate regression fitting values
z(i)=B(1,1)+B(2,1)*x(i);
% Calculate deviation
s(i)=y(i)-sum(y)/30;
% Calculate error
w(i)=z(i)-y(i);
end
% Calculate the sum of squared deviations S
S=s*s';
% Regression error sum of squares Q
Q=w*w';
% Calculate regression sum of squares U
U=S-Q;
% Calculate and output F-test value
F=28*U/Q
% Calculate the fitting values of the nonlinear regression model
for j=1:30,
Y(j)=1/(B(1,1)+B(2,1)*exp(-j));
end
% Output the fitting curve of the nonlinear regression model (Logistic curve)
plot(T,Y)
2. Grey Prediction Model
Example 2: Below is an introduction to the MATLAB implementation process for grey prediction using a company’s income prediction problem. The profits of a certain company from 1999 to 2008 (unit: yuan/year): [89677, 99215, 109655, 120333, 135823,
159878, 182321, 209407, 246619, 300670]
Now we need to predict the profit situation of the company for the next few years.
Analysis: First, it should be noted that before establishing a grey prediction model, the original time series needs to be processed. The processed time series is called the generation column. Common data processing methods in grey systems include both cumulative and decremental methods. The grey prediction idea is very simple; it establishes a linear differential equation through a set of data sequences, where the coefficients are the development coefficients and grey action quantities. Thus, we only need to seek parameters to predict future values. Here, we use the mean generation matrix vector of cumulative data and apply the least squares method, and finally perform residual processing to establish it. The specific program is as follows:
clear
syms a b;
c=[a b]';
A=[89677,99215,109655,120333,135823,159878,182321,209407,246619,300670];
B=cumsum(A); % Original data cumulative
n=length(A);
for i=1:(n-1)
C(i)=(B(i)+B(i+1))/2; % Generate cumulative matrix
end
% Calculate the values of the undetermined parameters
D=A;D(1)=[];
D=D';
E=[-C;ones(1,n-1)];
c=inv(E*E')*E*D;
c=c';
a=c(1);b=c(2);
% Predict subsequent data
F=[];F(1)=A(1);
for i=2:(n+10)
F(i)=(A(1)-b/a)/exp(a*(i-1))+b/a ;
end
G=[];G(1)=A(1);
for i=2:(n+10)
G(i)=F(i)-F(i-1); % Get the predicted data
end
t1=1999:2008;
t2=1999:2018;
G
plot(t1,A,'o',t2,G) % Compare original data with predicted data
xlabel('Year')
ylabel('Profit')
There are too many models, and I won’t elaborate further. Please refer to relevant books.
MATLAB Reference Books
-
“MATLAB R2016a Complete Self-Learning Guide”
-
“MATLAB Handbook”
-
“MATLAB Numerical Computation”
-
“MATLAB Revealed”
-
“MATLAB in Mathematical Modeling”
-
“MATLAB from Beginner to Expert”
-
“MATLAB Function Quick Reference”