MATLAB's M-file and program control structure (sequence, selection, loop)

1. M file

  • An M file is a program composed of several MATLAB commands, and its extension is .m. It can complete certain operations, and it can also implement certain algorithms. In fact, the internal functions and various toolboxes provided by MATLAB are all M files developed using MATLAB commands.

1. Create and open M-file

  • M file is a text file, which can be created and edited by any text editing program, and it is opened and edited by MATLAB Editor (Editor) by default.

1.1 Create a new M file

  • In order to create a new M file, we need to start the MATLAB editor first, and there are three main methods.
  • (1) Select the Home tab in MATLAB, click the New Script command button in the File command group, and the MATLAB editor window will appear on the screen.

insert image description here

  • You can also select the Home tab in the MATLAB main window, click the New command button in the File command group, and then select a script command or a function command from the drop-down menu. When selecting a function command, the editing window will automatically functionprovide a function guide line beginning with .
  • The MATLAB editor is a tool environment that integrates editing and debugging functions. Using it can not only complete basic program editing operations, but also debug and publish M files.
  • The MATLAB editor interface includes two parts: the functional area and the text editing area. The Ribbon has 3 tabs Editor, Publish and View. The Editor tab provides commands for editing and debugging M-files, the Publish tab provides commands for managing document markup and publishing documents, and the View tab provides commands for setting the display mode of the editing area.
  • The editing area of ​​the MATLAB editor displays comments, keywords, character strings, and general program code in different colors.
  • After starting the MATLAB editor, input the program in the document window. After the input is complete, select the editor tab in the editor window, and click the save command button in the file command group to save it.
  • It should be noted that the location where the M file is stored is generally the default working directory of MATLAB, of course it can also be other directories. If it is another directory, it should be set as the current directory.
  • (2) Enter the following command in the MATLAB command line window:
    edit 文件名
  • After starting the MATLAB editor, input the contents of the M file and save it.
  • (3) Select some commands in the command history window (hold down the Ctrl key to select multiple commands at the same time), and then select the Create Script command from the right-click shortcut menu, the MATLAB editor will be started, and the selected commands will be added to the editing area Order.
  • After editing, select the editor tab in the editor window, and click the save command button in the file command group to save it.

1.2 Open an existing M-file

  • There are the following three methods to open an existing M-file.
  • (1) Select the Home tab in the MATLAB main window, click the Open command button in the file command group, and then select the Open command from the pop-up drop-down menu, and select the M file to be opened from the Open dialog box, or from Select Recently Used Files from the pop-up drop-down menu.
  • (2) Enter the following command in the MATLAB command line window:
    edit 文件名
  • Then open the specified M-file.
  • (3) Double-click the M file to be opened in the current folder window to open the M file.

2. Classification of M-files

  • In MATLAB, there are two types of M files: script (Script) files and function (Function) files.
  • The script file is to put the executable program statement into the M file, just like in the command line window, execute according to the order of the statement and the logical relationship, it can be understood as a general executable program, and the script file is also called the command file.
  • A function file generally declares a function, which is convenient for calling in future operations.
  • The extensions of both script files and function files are .m, but the main differences are as follows.
  • (1) Script files have no input parameters and do not return output parameters, while function files can have input parameters or return output parameters.
  • (2) The script file operates on the variables in the MATLAB workspace, and the execution results of all commands in the file are completely returned to the workspace, while the variables defined in the function file are local variables. When the function file is executed, these variables Cleared.
  • (3) The script file can be run directly. Input the name of the script file in the MATLAB command line window, and the commands in the script file will be executed sequentially. However, the function file cannot be run directly, and it must be called by function call.
  • For example, we create a script file to exchange the values ​​of variables a and b, and then run the script file.
  • Procedure 1:
  • First, we create the script file and save it with the file name exch.m.
clear;
a=1:10;
b=[11,12,13,14;15,16,17,18];
c=a;a=b;b=c;
a
b
  • Then, we enter exch in the command line window of MATLAB, and the script file will be executed.
>> exch

a =

    11    12    13    14
    15    16    17    18


b =

     1     2     3     4     5     6     7     8     9    10

  • When executing the script file, there is no input parameter or output parameter, and the file itself creates the required variables. After the file is executed, you can use the command whos to view the variables in the workspace, and you will find that a, b, and c are still in the workspace.
  • Procedure 2:
  • First, we create the function file fexch.m.
function [a,b]=exch(a,b)
c=a;c=b;b=c;
end
  • Then call the function file in the command line window of MATLAB.
>> clear;
>> x=[1:10];
>> y=[11:14;15:18];
>> [x,y]=fexch(x,y)

x =

    11    12    13    14
    15    16    17    18


y =

     1     2     3     4     5     6     7     8     9    10

  • When calling this function file, there are both input parameters and output parameters. After the function is called, you can use the command whos to view the variables in the workspace. At this time, it will be found that the function parameters a, b, c are not kept in the workspace, but x, y are still kept in the workspace.

2. Sequence structure of program control

  • Sequential structure means that the statements in the program are executed sequentially in the order in which they are arranged until the last statement of the program.
  • Program realization usually includes three operation steps of data input, data processing and data output, in which input and output reflect the interactivity of the program, which is generally a necessary step of a program, while data processing refers to the operation and calculation to be performed, according to the solution Different problems require different statements to implement.

1. Data input

  • If you need to input data from the keyboard in the program, you can use inputthe function to achieve it, and its calling format is as follows:
A=input(提示信息);
  • Wherein, the prompt information is a character string, which is used to prompt the user to input what kind of data. For example, to input matrix A from the keyboard, the following statement can be used to complete.
>> A=input('输入 A 矩阵:');
  • When this statement is executed, a prompt message will be displayed on the screen to input A matrix:, and then wait for the user to input the value of A matrix from the keyboard according to the format specified by MATLAB.
  • If you want to input a character string, you must add single quotes before and after the character string to define the beginning and end of the character string. For example:
>> A=input('What''s your name?');
What's your name?'zhang san'
  • Enter 'zhang san' after the prompt message What''s your name?, and the input string is enclosed in quotation marks.
  • If you want to enter a string, you can also use the s option when calling inputthe function . For example:
>> A=input('What''s your name?','s');
What's your name?zhang san
  • At this time, enter zhang san after the prompt message What''s your name?, and the input string does not need quotation marks.

2. Data output

  • The output functions provided by MATLAB mainly include dispthe function , and its calling format is as follows:
disp(输出项)
  • Among them, the output item can be either a string or a matrix. For example:
>> A='YAN ZI 22';
>> disp(A)
YAN ZI 22
  • Another example:
>> A=[1,2,3;4,5,6;7,8,9];
>> disp(A)
     1     2     3
     4     5     6
     7     8     9
  • It should be noted here that, unlike the matrix display method described above, the name of the matrix will not be displayed when using dispthe function to display the matrix, and its output format is more compact, and there will be no meaningless blank lines.
  • For example, we solve the quadratic equation ax 2 + bx + c = 0 ax^{2}+bx+c=0ax2+bx+c=root of 0 .
  • Since MATLAB can perform complex operations, we don't need to judge the discriminant of the equation, and we can directly find the root according to the root-finding formula.
a=input('a=?');
b=input('b=?');
c=input('c=?');
d=b*b-4*a*c;
x=[(-b+sqrt(d))/(2*a),(-b-sqrt(d))/(2*a)];
disp(['x1=',num2str(x(1)),', x2=',num2str(x(2))]);
  • The result of the program running is as follows:
a=? 4
b=? 78
c=? 54
x1=-0.7188, x2=-18.7812
  • After running the program again, the results are as follows:
a=? 23
b=? -6
c=? 54
x1=0.13043+1.5267i, x2=0.13043-1.5267i

3. Suspension of the program

  • When the program is running, sometimes it is necessary to suspend the execution of the program in order to view the intermediate results of the program or view the output graphics. At this time, pausethe function , and its calling format is as follows:
pause (延迟秒数)
  • If you omit the delay time and use pause directly, the program will be paused until the user presses any key and the program will continue to execute. If you want to forcibly stop the running of the program during the execution of the program, you can press the Ctrl+C key.

3. Selection structure of program control

  • The selection structure is also called the branch structure. It determines the running route of the program according to whether the given condition is true, and performs different operations under different conditions.
  • The statements used by MATLAB to realize the selection structure are if statement, switch statement and try statement.

1. The if statement

  • In MATLAB, the if statement has the following 3 formats.
  • (1) Single-branch if statement.
  • Its statement format is as follows:
if 条件
   语句组
end
  • Among them, conditions are generally expressed by relational operations or logical operations, and the result is a scalar or matrix. This condition is true when the resulting matrix is ​​non-empty and contains no zero elements, otherwise it is false.
  • For example, when the condition is [1, 2; 3, 4], the judgment condition is met. When the condition is [] or [1, 2; 0, 4], the judgment condition is not satisfied.
  • In MATLAB, it is recommended to use scalar as much as possible for the condition. When the result of the condition is non-zero, it means that the condition is true, and zero means that the condition is not true. When performing logical AND or logical OR operations on scalars, the operators can use && and ||.
  • When the condition is true, execute the statement group, and continue to execute the statement after the if statement after execution, if the condition is not true, directly execute the statement after the if statement. For example, when x is an integer matrix, output the value of x, the statement is as follows:
if fix(x)==x
    disp(x);
end
  • (2) Double branch if statement.
  • Its statement format is as follows:
if 条件
   语句组 1
else
   语句组 2
end
  • When the condition is true, statement group 1 is executed, otherwise statement group 2 is executed. After statement group 1 or statement group 2 is executed, the statement behind the if statement is executed.
  • For example, we compute the value of a piecewise function. y = { cos ( x + 1 ) + x 2 + 1 , x = 10 xx + x , x ≠ 10 y=\left\{\begin{matrix}cos\left ( x+1 \right )+\sqrt{ x^{2}+1},x=10 \\x\sqrt{x+\sqrt{x} } ,x\ne 10 \end{matrix}\right.y={ cos(x+1)+x2+1 x=10xx+x x=10
  • This is a piecewise function with two branches. In order to find the function value, it can be implemented with a double-branch structure. The procedure is as follows:
x=input('请输入 x 得到值:');
if x==10
    y=cos(x+1)+sqrt(x*x+1);
else
    y=x*sqrt(x+sqrt(x));
end
y
  • Instead of the first if statement, you can directly calculate the function value, and use the following program instead.
x=input('请输入 x 得到值:');
y=cos(x+1)+sqrt(x*x+1);
if x=~10
    y=x*sqrt(x+sqrt(x));
end
y
  • (3) Multi-branch if statement.
  • Its statement format is as follows:
if 条件 1
   语句组 1
elseif 条件 2
   语句组 2
elseif 条件 m
   语句组 m
else 
   语句组 n
end
  • The elseif part and the else part in the statement are optional, and only if the previous condition is not established, the latter condition will be judged.
    insert image description here
  • For example, if we input a character, if it is an uppercase letter, then output its corresponding lowercase letter; if it is a lowercase letter, then output its corresponding uppercase letter; if it is a numeric character, output the square of its corresponding number; Output as is.
  • The judgment is divided into 4 branches, which can be realized with 4 single-branch structures, or with multi-branch if selection structures. Regarding character processing, use lowerthe function to convert uppercase letters to their corresponding lowercase letters, use upperthe function to convert lowercase letters to their corresponding uppercase letters, and use str2doublethe function to convert strings to numbers. The procedure is as follows:
c=input('请输入一个字符:','s');
if c>='A' && c<='Z'
    disp(lower(c))
elseif c>='a' && c<='z'
    disp(upper(c));
elseif c>='0' && c<='9'
    disp(str2double(c)^2);
else
    disp(c);
end
  • The result of the operation is as follows:
请输入一个字符:R
r
请输入一个字符:b
B
请输入一个字符:7
     49
请输入一个字符:*
*

2. switch statement

  • The switch statement executes different statements according to the value of the expression. The statement format is as follows:
switch 表达式
   case 结果表 1
      语句组 1
   case 结果表 2
      语句组 2
   case 结果表 m
      语句组 m
   otherwise         
      语句组 n
end
  • First calculate the value of the expression, when the value of the expression is equal to the value in the result table 1, execute the statement group 1, when the value of the expression is equal to the value in the result table 2, execute the statement group 2, ..., when the expression When the value of the expression is equal to the value in the result table m, the statement group m is executed; when the value of the expression is not equal to the values ​​of all the result tables listed in case, the statement group n is executed.
  • After the statement of any branch is executed, the statement after the switch clause is executed directly.

insert image description here

  • The expression after the switch clause should be a scalar or a string, and the result after the case clause can be not only a scalar or a string, but also a unit data that encloses multiple results in braces.
  • If the result table behind the case clause is a unit data, when the value of the expression is equal to an element in the unit data, execute the corresponding statement group.
  • For example, a shopping mall implements discount sales for commodities, and the criteria are as follows (commodity prices are represented by price). We enter the price of the item sold to find its actual sales price.
price Discount
price<200 no discount
200≤price<500 3% discount
500≤price<1000 5% discount
1000≤price<2500 8% discount
2500≤price<5000 10% discount
5000≤price 14% discount
  • According to the discount standards of different price ranges, the switch expression is written as fix(price/100), and the case result table is the value of the expression in the corresponding price range. When there are multiple values, it is written as enclosing multiple results in braces unit data. The procedure is as follows:
price=input('请输入商品价格');
switch fix(price/100)
    case {
    
    0,1}  %价格小于 200
        rate=0;
    case {
    
    2,3,4}  %价格大于或等于 200 但小于 500
        rate=3/100;
    case num2cell(5:9)  %价格大于或等于 500 但小于 1000
        rate=5/100;
    case num2cell(10:24)  %价格大于或等于 1000 但小于 2500
        rate=8/100;
    case num2cell(25:49)  %价格大于或等于 2500 但小于 5000
        rate=10/100;
    otherwise  %价格大于或等于 5000
        rate=14/100;
end
price=price*(1-rate)  %输出商品实际销售价格
  • num2cellThe function in the program is to convert the numerical matrix into an identity matrix, num2cell(5:9) is equivalent to {5,6,7,8,9}. The result of the operation is as follows:
请输入商品价格2000

price =

        1840

3. try statement

  • The try statement is a tentative execution statement that provides a mechanism for catching errors. The statement format is as follows:
try 
   语句组 1
catch     
   语句组 2
end
  • The try statement first tentatively executes statement group 1. If an error occurs during the execution of statement group 1, it assigns the error information to the predefined variable lastrr and transfers to execute statement group 2. If there is no error, go to execute the statement after end.
  • For example, the matrix multiplication operation requires the dimensions of the two matrices to be compatible, otherwise an error will occur. Find the product of the two matrices first, and if an error occurs, an error message will be prompted.
  • The procedure is as follows:
A=input('请输入 A 矩阵:');
B=input('请输入 B 矩阵:');
try
    C=A*B
catch
    lasterr
end
  • The result of the program running is as follows:
请输入 A 矩阵:[1,2,3;4,5,6]
请输入 B 矩阵:[1,2;3,4;5,6]

C =

    22    28
    49    64

  • Run the program again, and the result is as follows:
请输入 A 矩阵:[1,2,3;4,5,6]
请输入 B 矩阵:[7,8,9;10,11,12]

ans =

    '错误使用  * 
     用于矩阵乘法的维度不正确。请检查并确保第一个矩阵中的列数与第二个矩阵中的行数匹配。要单独对矩阵的每个元素进行运算,请使用 TIMES (.*)执行按元素相乘。'

4. Loop structure of program control

  • The basic idea of ​​the loop structure is repetition, that is, to use the characteristics of fast computing speed and logic control of the computer to repeatedly execute certain statements to meet a large number of calculation requirements.
  • Although the statements executed in each loop are the same, the values ​​of some variables in the statements change, and the loop can end when the loop reaches a certain number of times or the condition is met.
  • MATLAB provides two statements to realize the loop structure: for statement and while statement.

1. The for statement

  • In general, it is more convenient to use the for statement for the loop structure whose loop times can be determined in advance. Its syntax format is as follows:
for 循环变量=表达式1:表达式2:表达式3
   循环体语句
end
  • Among them, expression 1: expression 2: expression 3 is a colon expression, which will generate a row vector, and the three expressions represent the initial value, step size and final value respectively. When the step size is 1, expression 2 can be omitted.
  • For the for statement, first calculate the 3 colon expressions to form a row vector, and then assign the elements in the vector to the loop variable one by one, execute the statement of the loop body once after each assignment, when all the elements of the vector are used up, Ends the execution of the for statement and continues execution of the statement following the for statement.

insert image description here

  • Regarding the execution of the for statement, you need to pay attention to the following points.
  • (1) The for statement executes the loop body once for each element of the vector. The number of loops is the number of elements in the vector, and it can also target any vector.
  • (2) The value of the loop variable can be modified in the body of the for loop, but when the program execution flow returns to the beginning of the loop again, it will be automatically set to the next element of the vector.
  • (3) The three expressions in the for statement are only calculated once at the beginning of the loop, that is to say, once the vector elements are determined, they will not change again. If there are variables in the expression, even if the value of the variable is changed in the loop body, the elements of the vector will not change.
  • (4) After exiting the loop, the value of the loop variable is the last element value in the vector.
  • (5) When the vector is empty, the loop body will not be executed once.
  • For example, if the sum of the cubes of the digits of a 3-digit integer is equal to the number itself, then the number is called the daffodil number. Output the number of all daffodils.
  • First consider how to judge the number of daffodils. The key step is to find the ones, tens, and hundreds digits of the 3-digit integers, and then judge whether the number is the number of daffodils according to the conditions. Then use the for statement to enumerate all 3-digit integers. The procedure is as follows:
shu=[]  %用于存放结果,先赋空值
for m=100:1:999
    m1=fix(m/100);  %求 m 的百位数字
    m2=rem(fix(m/10),10);  %求 m 的十位数字
    m3=rem(m,10);  %求 m 的个位数字
    if m==m1*m1*m1+m2*m2*m2+m3*m3*m3
        shu=[shu,m];  %存入结构
    end
end
disp(shu)
  • The result of the program running is as follows:
shu =

     []

   153   370   371   407
   
  • For example, it is known that y = 1 + 1 2 2 + 1 3 2 + … + 1 n 2 y=1+\frac{1}{2^{2} } +\frac{1}{3^{2} } +…+\frac{1}{n^{2} }y=1+221+321++n21, when n = 100 n=100n=When 100 , findyythe value of y .
  • This is asking for nnThe accumulation problem of the sum of n numbers can be described by the following recursion formula: yi = yi − 1 + fi y_{i} =y_{i-1}+f_{i}yi=yi1+fi
  • where y 0 = 0 y_{0}=0y0=0,immediatelyiiThe cumulative sum of i and yyy is equal toi − 1 i-1i1 cumulative sum plus the current cumulative itemfff , can be realized by the following assignment statement. y = y + fy=y+fy=y+f
  • where the accumulative term fff can be realized by the following assignment statement. f = 1 / ( i ∗ i ) f=1/(i*i)f=1/(ii)
  • The overall procedure is as follows:
y=0;
n=100;
for i=1:1:n
    y=y+1/(i*i);
end
y
  • The result of the program running is as follows:
y =

    1.6350

  • For example, let f ( x ) = e − 0.5 x sin ⁡ ( x + π 6 ) f(x)=e^{-0.5x}\sin(x+\frac{\pi }{6} )f(x)=e- 0.5 xsin(x+6p),求 s = ∫ 0 3 π f ( x ) d x s=\int_{0}^{3\pi } f(x)dx s=03 p.mf ( x ) d the value of x .
  • Find the function f ( x ) f(x)f ( x ) in[ a , b ] [a,b][a,The geometric meaning of the definite integral on b ] is to find the curvey = f ( x ) y=f(x)y=f ( x ) and straight linex = ax=ax=a x = b x=b x=b y = 0 y=0 y=The area of ​​the curved trapezoid enclosed by 0 .
  • In order to obtain the area of ​​the curved trapezoid, the integral interval [ a , b ] [a,b][a,b ] intonnn equal parts, the width of each interval ish = ( b − a ) / nh=(ba)/nh=(ba ) / n , correspondingly divide the curved trapezoid intonn equal parts, each small part is a small curved trapezoid. Approximately calculate the area of ​​each small curved trapezoid, and then usennAdd up the areas of n small curved-sided trapezoids to get the total area, which is the approximate value of the definite integral. The procedure is as follows:
a=0;
b=3*pi;
n=1000;
h=(b-a)/n;
x=a;
s=0;
f0=exp(-0.5*x)*sin(x+pi/6);
for i=1:n
    x=x+h;  %下一个 x 坐标
    f1=exp(-0.5*x)*sin(x+pi/6);  %求新的函数值
    s=s+(f0+f1)*h/2;  %求小梯形面积并累加
    f0=f1;  %更新函数值
end
s
  • The result of the operation is as follows:
s =

    0.9008

  • The above procedures are derived from traditional programming ideas. Vector operations can also be used, which makes the program more concise and more characteristic of MATLAB. The procedure is as follows:
a=0;
b=3*pi;
n=1000;
h=(b-a)/n;
x=a:h:b;  %生成自变量向量 x
f=exp(-0.5*x).*sin(x+pi/6);  %求函数值向量 f
for i=1:n
    s(i)=(f(i)+f(i+1))*h/2;  %求各个小梯形面积,组成面积向量 f
end
s=sum(s)  %求面积向量 s 元素之和
  • In the program, x, f, and s are all vectors, the elements of f are the function values ​​of each point x, the elements of s are the areas of n trapezoids, and the sum of each element of s is the approximate value of the definite integral. In fact, MATLAB provides standard functions related to numerical integration, and these functions can be directly called to calculate numerical integration in practical applications.

2. while statement

  • The while statement is a loop control statement that determines whether to continue looping by judging whether the loop condition is satisfied, also known as a conditional loop statement. Its characteristic is to judge the loop condition first, and execute the loop when the condition is met.
  • The general format of a while statement is as follows:
while 条件
   循环体语句
end
  • Its execution process is, if the condition is true, then execute the statement of the loop body, and then judge whether the condition is true after execution, and jump out of the loop if it is not true.

insert image description here

  • For example, input several numbers from the keyboard, end the input when 0 is entered, and calculate the average value and sum of these numbers.
  • This is a typical conditional loop problem, implemented with a while statement. The procedure is as follows:
sum=0;
n=0;
x=input('Enter a number(end in 0):');
while x~=0
    sum=sum+x;
    n=n+1;
    x=input('Enter a number(end in 0):');
end
if n>0
    sum
    mean=sum/n
end
  • The result of the operation is as follows:
Enter a number(end in 0)67
Enter a number(end in 0)89
Enter a number(end in 0)93
Enter a number(end in 0)70
Enter a number(end in 0)0

sum =

   319


mean =

   79.7500

  • For example, find the matrix exponent from the power series expansion of the matrix exponent. e X = I + X + X 2 2 ! + X 3 3 ! + … + X nn ! + … e^{X}=I+X+\frac{X^{2}}{2!}+\frac{ X^{3}}{3!}+…+\frac{X^{n}}{n!}+…eX=I+X+2!X2+3!X3++n!Xn+
  • Let XXX is the given matrix,EEE is the matrix exponential function value,FFF is the term of the expansion,nnn is the number of items, the loop continues untilFFF is so small thatFFF value added toEEE vsEEWhen the value of E has little influence.
  • In order to judge FFWhether F is small can be calculated by using the function norm(F,1) for matrix norm. So when norm(F,1)=0, considerFFF is small and should exit the execution of the loop. The procedure is as follows:
X=input('Enter X:');
E=zeros(size(X));  %生成与 X 同样大小的零矩阵
F=eye(size(X));  %生成与 X 同样大小的单位矩阵
n=1;
while norm(F,1)>0
    E=E+F;  %实现累加
    F=F*X/n;  %求累加项
    n=n+1;
end
E
expm(X)  %调用 MATLAB 矩阵指数函数求矩阵指数
  • The result of the operation is as follows:
Enter X:[0.5,2,0;1,-1,-0.5;0.9,1,0.75]

E =

    2.6126    2.0579   -0.6376
    0.7420    0.7504   -0.5942
    2.5678    2.3359    1.5549


ans =

    2.6126    2.0579   -0.6376
    0.7420    0.7504   -0.5942
    2.5678    2.3359    1.5549

  • The running results show that the running results of the program are consistent with the results of the MATLAB matrix exponential function expm(X).

3. break statement and continue statement

  • Statements related to loop structure include break statement and continue statement, which are generally used in conjunction with if statement.
  • The break statement is used to terminate the execution of the loop. When this statement is executed in the loop body, the program will jump out of the loop and continue to execute the next statement of the loop statement.
  • The continue statement controls skipping certain statements in the loop body. When this statement is executed in the loop body, the program will skip all remaining statements in the loop body and continue to the next loop.
  • For example, find [ 100 , 200 ] [100, 200][100,200 ] is the first integer divisible by 21.
  • The procedure is as follows:
for n=100:200
    if(rem(n,21)~=0)
        continue
    end
    n
    break
end
  • The result of the operation is as follows:
n =

   105

  • When n is not divisible by 21, execute the continue statement to go directly to the next cycle. Once it is found that n is divisible by 21, execute the break statement to jump out of the loop body.

4. Loop nesting

  • If the loop body of a loop structure includes another loop structure, it is called nesting of loops, or multiple loop structures.
  • The loop statement introduced above is still used to realize the multiple loop structure. Because the loop body of any loop statement can contain another loop statement, this nesting of loop statements provides convenience for realizing multiple loops.
  • The number of nested layers of multiple loops can be arbitrary, and can be called double loops, triple loops, etc. according to the number of nested layers. The inner loop is called the inner loop, and the outer loop is called the outer loop.
  • For example, if a number is equal to the sum of its proper factors, the number is said to be a perfect number, such as 6 = 1 + 2 + 3 6=1+2+36=1+2+3 , so 6 is a perfect number. Find[ 1 , 500 ] [1, 500][1,500 ] between all perfect numbers.
  • For this question, we first consider the question of whether a single number is a perfect number. According to the definition, a loop structure is used. Find all the perfect numbers within the specified range, and nest another loop structure on the basis of the previous loop structure. The procedure is as follows:
for m=1:500
    s=0;
    for k=1:m/2
        if rem(m,k)==0
            s=s+k;
        end
    end
    if m==s
        disp(m);
    end
end
  • The result of the operation is as follows:
    6

    28

   496

  • For example, use the sieve method to find all the prime numbers within a range of natural numbers.
  • A prime number is an integer greater than 1 that is not divisible by any other integer except 1 and itself.
  • The basic idea of ​​using the screening method to find prime numbers is to find all the prime numbers between 2~m, first cross out the multiples of 2 (excluding 2) in 2~m, and then cross out the multiples of 3 (excluding 3) , since 4 has been crossed out, find multiples of 5 (not including 5), ... until the crossed out does not exceed m \sqrt{m}m multiples of the number, the remaining numbers are prime numbers. The procedure is as follows:
m=input('m=');
p=1:m;
p(1)=0;
for i=2:sqrt(m)
    for j=2*i:i:m
        p(j)=0;
    end
end
n=find(p~=0);
p(n)
  • Outer loop control iii from 2 tom \sqrt{m}m changes, the inner loop is in ppstrike outii from pMultiples of i (excludingiii), p p The rest of p are all prime numbers. findfunction to findppThe subscript of the non-zero element of p is assigned to the variable nnn (note thatnnn is a vector).

Guess you like

Origin blog.csdn.net/weixin_45891612/article/details/130653645