Infinite loop matlab. Loop in Matlab for – Illustrated tutorial on MatLab › Programming Basics › Loops like for…end

Department: Information technology

PROGRAMMING INMATLAB

OperatorsMATLAB

· Loop statements

Cyclefor

Syntax

for count=start:step:final

MATLAB commands

Description

count is a loop variable,

start - its initial value,

final - its final value,

step - the step by which count increases with each subsequent entry into the loop

the loop ends as soon as the value of count becomes greater than final.

Example

Let it be necessary to derive a family of curves for x€, which is specified by a function depending on the parameter

y (x, a) = e-ax sin x,

for parameter a values ​​from -0.1 to 0.1. Below is a listing of the program file for displaying a family of curves.

Program listing

x = ;

for a = -0.1:0.02:0.1

y = exp (-a*x).*sin(x);

As a result of executing the program, a graphic window will appear that contains the required family of curves.

Cyclewhile

Syntax

while loop condition

MATLAB commands

Description

The loop runs as long as the loop condition is true. To set the loop execution condition, the following relational operations are allowed:

Setting more complex conditions is done using logical operators. The logical operators are given in the following table

Example

Branch Operators

Conditional operatorif

Syntax

if condition

MATLAB commands

Description

If the condition is true, then the MATLAB commands located between if and end are executed, and if the condition is not true, then the commands located after end are executed.

Example

Conditional operatorelseif

Syntax

if condition1

elseif condition2

………………………

elseif condition

Description

Depending on the fulfillment of a particular condition, the corresponding branch of the program runs; if all conditions are false, then the commands placed after else are executed.

Example

Operatorswitch

Syntax

switch variable

case value1

case value2

……………………

case meaningn

Each branch is defined by a case statement and is entered when the switch statement variable takes the value specified after case or one of the values ​​from the case list. After executing any of the branches, the switch exits, and the values ​​​​specified in other cases are no longer checked. If no suitable values ​​are found for the variable, then the program branch corresponding to otherwise is executed.

Example

Cycle interruptions. Exceptional situations.

Operatorbreak

Syntax

The break operator is used to organize cyclic calculations: for…end, while…end. When the condition is met

if condition

The break statement ends the loop (for or while) and the statements that are located in the lines following end are executed. In the case of nested loops, break exits the inner loop.

Exception handling, operatortrycatch

Syntax

statements whose execution

may lead to an error

statements to be executed

when an error occurs in the block

between try and catch

Description

The try...catch construct allows you to bypass exception situations (errors that lead to the termination of the program, for example, accessing a non-existent file) and take some actions if they occur.

Example

Servicefunctions

disp- outputs text or variable value to the command window

input- requests input from the keyboard. Used when creating applications with a command line interface.

eval - executes the contents of a string or string variable, like MATLAB commands

clear- deletes work environment variables.

Withlc- clears the command window

More information about these and other functions can be found by running at the command line

helpfunction_name

Tasksto perform laboratory work

The number of a specific assignment option is determined by the teacher.

Exercise1

This task involves finding an algebraic interpolation polynomial of degree n for a certain set of data: Pn(x) .

Goal of the work:

It is necessary to create a program for calculating the coefficients of an algebraic interpolation polynomial Pn(x)= a0 + a1 x+ + anxn.

Guidelines:

Xi

yi

Odds a0 , a1 , …, an are determined from solving the system of equations:

Here n- order of the interpolation polynomial,

n+1 - number of given pairs of points ( x, y),

a0 , a1 ,… an- the required coefficients of the polynomial Pn(x)= a0 + a1 x+ + anxn).

Program requirements

· Set the boundaries of the segment , on which the interpolation polynomial is constructed P(x)

· Set n- the number of interpolation segments (or, which is the same, the degree of the polynomial)

Note: x0, xn, n entered from the keyboard.

· To obtain initial data (x, y) (number of pairs of points (xi, yi) , from which the interpolation polynomial is constructed P(x) - n1=n+1) provide:

b Entering randomly located nodes xi, i=0, n from the keyboard

ь Calculation of nodes xi, i=0, n, corresponding to the uniform arrangement of the argument x on the segment

b In paragraphs. 1.2 values yi, i=0, n either entered from the keyboard (if the source function is unknown) or calculated from a given function f(x). The expression defining the function is entered from the keyboard and must comply with the rules for writing expressions in MATLAB

ь Data entry ( xi, yi, i=0, n) from file

· Solve a system of equations to determine the coefficients of the polynomial P(x)

· Construct graphs of the original tabular function and the polynomial P(x)

· If the source data is given as a function f(x), plot the interpolation error /f(x) - P(x)/. Calculate the maximum absolute value of the interpolation error at a given interval.

Exercise2

Spline interpolation

Goal of the work:

It is necessary to create a program for calculating coefficients and constructing a spline function S(x), “glued together” from pieces of 3rd order polynomials S i(x), which have a special recording form:

function S i(x) defined on the segment ,

Program requirements

When performing this work you must:

· Set the boundaries of the segment on which the spline function S(x) is constructed

· Set n - the number of interpolation segments, on each of which the cubic polynomial Si(x) is constructed.

· Note: x0, xn, n are entered from the keyboard.

· Organize the input of initial data (x, y) (the number of pairs of points (xi, yi) from which the spline function S(x), n1=n+1 is constructed), providing:

b Entering randomly located nodes xi, i=0, n from the keyboard

b Calculation of nodes xi, i=0, n, corresponding to the uniform location of the argument x on the segment

b In paragraphs. 1,2 the values ​​of yi, i=0, n are either entered from the keyboard (if the original function is unknown) or calculated from a given function f(x). The expression defining the function is entered from the keyboard and must comply with the rules for writing expressions in MATLAB

b Enter data (xi, yi, i=0, n) from file

b S1""(x0)=0, S3""(x3)=0

b S1"(x0)=f "(x0), S3"(x3)=f "(x3)

b S1""(x0)=f "(x0), S3""(x0)=f "(x3)

· To determine the coefficients of a natural cubic spline (boundary conditions 1), it is necessary to solve the following system of equations:

Coefficients?0 =0,?n =0

· Construct graphs of the original function and spline functions for all three types of boundary conditions.

· Construct graphs of spline interpolation error functions f(x) - S(x) for all three types of boundary conditions.

Note:

In MATLAB, the indexes of one-dimensional and two-dimensional arrays start from 1, not from 0. Take this into account when composing the program.

Exercise№3

Function approximation using the least squares method (LSM).

This task involves finding an approximating function (a polynomial of degree m) for a certain set of data, constructed by the least squares method (LSM).

Goal of the work:

Do you need to create a program for finding the coefficients of a polynomial? (x)= a0 + a1 * x+… an * xm least squares method.

Let, for example, have the following set of data:

Xi

yi

The search for the necessary coefficients is carried out as follows:

Where n - amount of points ( x, y),

m - degree of the desired polynomial,

a 0 , a 1 , …, a m - the required coefficients ( ? ( x )= a 0 + a 1 x + … + a m x m ).

Program requirements

When performing this work you must:

· Set the boundaries of the segment on which the approximating function is constructed?(x)=a0+a1*x+… an * xm

· Set m - degree of the polynomial

· Note: x1, xn, m are entered from the keyboard.

· To obtain the initial data (x, y), from which the approximating function is constructed?(x)=a0+a1*x+… an* xm, provide:

b Entering randomly located nodes xi, i=1, n from the keyboard

b Calculation of nodes xi, i=1, n, corresponding to the uniform location of the argument x on the segment

b In paragraphs. 1,2 the values ​​of yi, i=1, n are either entered from the keyboard (if the original function is unknown) or calculated from a given function f(x). The expression defining the function is entered from the keyboard and must comply with the rules for writing expressions in MATLAB

b Enter data (xi, yi, i=1, n) from file

· Solve the system of equations to determine the coefficients of the polynomial?(x)

· Construct graphs of the original tabular function and polynomial?(x)

· If the source data is given as a function f(x), plot the interpolation error /f(x) - ?(x)/. Calculate the maximum absolute value of the interpolation error at a given interval.

When performing the last point on the segment take at least 500 points for calculations

Requirements for laboratory work

The report must contain:

1. Statement of the problem

2. Program text

3. Test results

Note: Program texts must be provided with comments.

Bibliography

1. Anufriev I.E. Self-instruction manual Matlab 5.3/6.x - St. Petersburg: BHV-Petersburg, 2003. - 736 pp.: ill.

2. V.P. Dyakonov MATLAB 6.5 SPI/7 + Simulink 5/6 in mathematics and modeling. Series "Professional's Library". - M.: SOLON-Press, 2005. - 576 p.: ill.

3. Anufriev I.E., Smirnov A.B., Smirnova E.N. MathLab 7. - St. Petersburg: BHV-Petersburg, 2005. - 1104 pp.: ill.

In addition to programs with linear structure, whose instructions are executed strictly in order, there are many algorithms whose structure nonlinear. In this case, a sequence of algorithm elements can be executed depending on certain conditions, sometimes with a finite number of repetitions - regular cycles, sometimes in the form of cycles that are completed when a given condition is met. Almost any serious program has a nonlinear structure. To create such programs, special control structures are required. They are available in any high-level programming language, and in particular in Matlab.

Let's look at the operators m-files for more details.

Assignment operator. The main operator of the programming system MatLab is assignment operator, having the following structure:

VariableName= expression

The operator is intended to identify variables and is denoted by the symbol = , to the left of which is the name of the variable, and to the right is an arithmetic or string expression (the rules for writing arithmetic and string expressions were discussed in section 1.1.2). Here are some examples of assignment operators (Fig. 1.3.4-1).

Rice. 1.3.4-1. Examples of assignment operators

All variables used on the right side of the assignment operator must be previously defined. If the command line ends with a semicolon ( ; ), then the result of the statement is not displayed, otherwise it is displayed in the next line of the command window. This remark also applies to the execution of assignment statements located in m-files.

Data entry operators. Data entry into Matlab can be done either using the assignment operator ( a=5;), and using the keyboard input function:

VariableName= input("Request");

This function enters an expression from the keyboard, and the result is stored in a variable called a. In the example below, into a variable a First, a numerical value is entered, and then a numerical expression (Fig. 1.3.4-2).

Rice. 1.3.4-3. Evaluating an expression given in symbolic form

Conditional statement if... end. Conditional operator if V general view is written as follows:

ifBooleanExpression1

Instructions1

elselfCondition2

BooleanExpression2

BooleanExpression3

The rules for writing logical expressions are described in Topic 1.1.

This design allows several private options. The simplest - truncated branch [x] has the following form:

ifBooleanExpression

Instructions

Let us recall that if BooleanExpression returns a boolean value 1 (i.e. “True”) are executed Instructions, constituting the body of the structure if...end. In this case the operator end indicates the end of the list of instructions. Instructions in a list are separated by a comma or semicolon. If BooleanExpression not executed (gives a boolean value 0 , "Lie"), then Instructions are also not fulfilled.

Below is an example of using the simplest truncated branch, implemented using the operator if(Fig. 1.3.4-4).

Rice. 1.3.4-5. Example of a standard branch

From the above example it is clear that the operator if can be either one line or several lines.

Let's look at a more complex example - nested branch. Let's look at an example

Moreover, in order to fully reflect the structure of a complex branch, without worrying about wrapping long command lines, we use m-function (Fig. 1.3.4-7). Let's select data to check the main branch and turn to the function raz() with different initial data (Fig. 1.3.4-6).

Rice. 1.3.4-7. A function that implements nested branching

The multiple choice operator is switch. To implement multiple selection, the following construction is used switch:

switchExpression

caseConcept_1

List_of_instructions_1

caseValue_2

List_of_instructions_2

caseValue_N

List_of_instructions_N

Otherwise

Instruction_list_N+1

If the expression after the header switch has the meaning of one of the expressions Meaning..., then the block of statements is executed case, otherwise - a list of instructions after the operator otherwise. When executing a block case those lists of instructions are executed for which Meaning coincides with By expression. Please note that Meaning can be a number, a constant, a variable, a cell vector, or even a string variable. Let us explain the use of the search operator switch following example:

M-function that implements multiple branching is shown in Fig. 1.3.4-8, and accessing it with initial data that allows you to check each branch of the branch is shown in Fig. 1.3.4-9.

Rice. 1.3.4-9. Function calls multifunc()

Function multifunc(x,n) two parameters, with the second playing the role of an indicator that determines the type of functional dependence. The function value is written to a variable y. If n=1, then the first case block is executed, if 2, then the second one, if n=2, 3 or 4, then the third one. If the value of the variable n does not match any of the listed values, then the command located after the keyword is executed otherwise.

The regular loop operator is for...end. Type loop operator for...end usually used to organize calculations with a given number of loop repetitions. The structure of such a cycle is as follows:

for va = s:d:e

Instructions1

InstructionsN

Where s- initial value of loop variable var, d- increment of this variable and e - the final value of the control variable, when exceeded, the loop ends. It is also possible to write in the form s:e(in this case d=l). The list of instructions executed in a loop ends with the statement end.

As an example of using the operator for...end calculate the sum of array elements X, whose values ​​are defined in the command window using the m-function summa()(Fig. 1.3.4-10), the parameter of which is the vector x. Number of array elements X determined by the function length. In addition to calling the function, the command window allows you to check the result of calculations using the built-in function sum(x)(Fig. 1.3.4-11).

Rice. 1.3.4-11. Calling a function summa() and built-in function sum()

The operator can be used in a loop continue , which passes control to the next iteration of the loop, skipping the statements that are written after it, and in a nested loop it passes control to the next iteration of the main loop. Operator break can be used to terminate the execution of a loop early (for example, when debugging a section of a program). As soon as it is encountered in the program, the loop is interrupted.

In addition to simple regular cycles in Matlab, it is possible to organize nested loops. Let's consider an example of forming a two-dimensional array A, each element of which represents the sum of its indices (Fig. 1.3.4-12). Appeal to script-file vzikl shown in Fig. 1.3.4-13.

Rice. 1.3.4-13. Appeal to script-file with name vzikl

The iterative loop operator is while…end. General view of the structure while...end as follows:

whileBooleanExpression

Instructions

A distinctive feature of this structure is that the instructions located in the body of the repetition structure are executed only if some BooleanExpression"true". As soon as the condition becomes false, the repeat structure is exited and control is transferred to the instruction located after the keyword end.

Let's give a simple example (Fig. 1.3.4-14).


Rice. 1.3.4-14. A dialog program using the operator while...end

This program, saved in m-file named primer11, serves to repeatedly calculate the circumference from a user-entered radius value r, where the dialogue is implemented using the command input. Lines associated with variable input r and calculation of the circumference are included in the control structure while...end. This is necessary for cyclic repetition of calculations when entering different values r. Bye r>=0, the cycle repeats. But it's worth asking r<0 , the calculation of the circumference stops and the loop ends. Since in the second line of the program the value r is defined as 0, the loop is repeated at least once.

Working with the program in the command window is shown in Fig. 1.3.4-15.

Rice. 1.3.4-16. Interrupting a program using a statement break

Operator continue passes control to the next iteration of the loop, skipping the statements that are written after it, and in a nested loop it passes control to the next iteration of the main loop. Below is an example of calculating the sum and product of positive elements of a two-dimensional array b(3,3) (Fig. 1.3.4-17).


Rice. 1.3.4-17. Interrupting a program using a statement continue

Examples of problem solving using

M-files

Example 1.3.5-1. Given n numbers . You need to calculate their sum: Where

To solve this problem, a function has been developed fb(x), which implements the algorithm for calculating the current value of the function. The function has one input parameter – the current value of the array element b and one output parameter - y(Fig. 1.3.5-1). The function is accessed in a loop organized to calculate the sum (Fig. 1.3.5-2).

Rice. 1.3.5-2. A program that implements the calculation of the sum of numbers

To calculate the sum of function values, a function was created script-file with name zadasha.m, in which the number of numbers is first specified ( n=10) and the vector of their values ​​( b), and then a regular loop is organized to call the functions fb() and calculating the amount.

Calculations are performed by running script-file by typing in the command line of the window Command Window his name zadasha. The results of its execution are shown in Fig. 1.3.5-3.


Rice. 1.3.5-3. Launch script-file zadasha for execution

Example 1.3.5-2. Form a two-dimensional array a(3,4) from arbitrary numbers. Calculate and output a one-dimensional array b, each element of which is the arithmetic mean of the elements of the corresponding row of array a.

In Fig. 1.3.5-4 is given script-file with name zadasha2, where the matrix is ​​entered, A, consisting of three rows and four columns. A loop is organized based on the number of array elements being formed b by calling a function sred_ar(). An array is passed to the function A, line number ( i) and the number of elements in the line ( m). Printing Array Elements b provided in the column.

Rice. 1.3.5-5. Function sred_ar(), calculating the arithmetic mean
array string elements a

As a result of the launch script-file named zadasha2 out the window Command Window displays a column of array elements b

Rice. 1.3.5-7. Function fab(), calculating the value of the i-th term

Rice. 1.3.5-9. Running a function sumf() for execution


Laboratory work on the topic

"Algorithmization and programming tools

In Matlab"

Questions to be studied

1) Types m- files.

2) Creating and saving new, and opening previously created m-files.

3) Features script- files and m- functions.

4) Launch for execution script- file from a text editor.

5) Launch for execution script- file from the command window.

6) Appeals to script- files and m-f functions.

7) Programming language tools in the Matlab system.

8) Basic m-language operators, their purpose and formats .

2. General task

1) Study the material in Topic 1.3 (p.p. 1.3.1 – 1.3.5).

2) Select an individual task from table 1.3.6-1.

3) Design m -functions for implementing standard algorithms: calculating finite sums, branches, searching for minimum and maximum in a data sequence, etc.

4) Enter And save m -functions on external media.

5) Create newscript - a file into which you enter the program code that describes the logic for solving the problem.

6) Save the script -file in the current directory.

7) Debug scrip t-file, launching it for execution from a text editor with the commandRun .

8) Prepare And enter initial data for solving the problem;

9) Execute the script -file from command line windowCommand Window .

10) Save the text working window on external media.

11) Provide results work for a teacher, answer to the questions asked.

12) Execute team clear all for the cleaning Working environment .

13) Submit your report according to work completed .


Options for individual assignments

Table 1.3.6-1

Exercise
Enter a natural number n and a vector of real numbers Find: Where
Calculate Where

Set array , consisting of an even number of elements. Each pair of numbers , where i+1 is a multiple of two, specifies the coordinates of the vertex of the broken line. Construct a polyline, connecting the last vertex to the first
. Calculate product
, Where
Enter a natural number n and a real number x. Calculate
Enter a natural number n. Find the largest among values , where k=1, 2,…,n, as well as the sum of all obtained values
Enter a natural number n. Among the values
, Where (i=1,2,…n), find all positive ones and calculate their sum
Enter the natural number n and the vector of real numbers
. Determine whether there are more positive or negative numbers in a vector, and determine the largest of the negative and smallest of the positive numbers
, Where Enter the matrix B(5,7) and form the vector C(5) from the first largest elements of the rows. Display its elements in a row and column
Generate a vector according to the rule:
, where k=2,3,…, 7, if Find the sum of squares of those numbers that do not exceed 2 . Transform it so that the zeros come first, then all other elements. Determine the sum and number of elements whose values ​​are divisible by 5
Enter a vector of real numbers . Create an array x from it, each element of which is the maximum of three consecutive elements in the array z
Form matrix A(4,4) according to the rule:
Find and display the values ​​and indices of two identical elements. If there are none, display a message
Form the matrix D(3,2) according to the rule: .
Create a vector from the negative elements of the resulting matrix
Specify a natural number n. Calculate which of the n by n matrices contains more positive elements if their elements are formed according to the rule: Display the generated matrices
Enter the square matrix of real numbers A(4,4). Find the sum of the largest values ​​of the elements of its rows. Generate a new matrix B(4,4) by multiplying each element of matrix A by the found sum and dividing it by the determinant of the original matrix
Enter the matrix of real numbers A(4,7) and get from it the vector C(4), the elements of which are: · the largest of the elements in the first row;
· the smallest element in the second row;
· arithmetic mean of the elements of the third row;
· sum of elements of the fourth row
Enter the natural number n and the matrix of real numbers C(n,n). Find the arithmetic mean of the largest and smallest values ​​of its elements and, replacing the diagonal elements with this value, display matrix C on the screen Where
Enter the natural numbers k1, k2 and a real matrix of size 8x4. Swap elements k1 and k2 of rows in the matrix
Enter the natural number n and the matrix of real numbers C(n,9). Find the arithmetic mean of each of the even-numbered columns
Enter the vectors of real numbers x(5), y(6), z(7). Calculate the t value using the following algorithm:
Form the matrix B(9,3) according to the rule: Determine the smallest element in each row of the matrix and write it to the corresponding element of vector C. Output the resulting vector C
Enter a matrix of real numbers A(3,4), all of whose elements are different. In each row, you should select the largest and smallest values, and the sum of the indices of the columns in which they are located should be written in the corresponding element of the vector C(3)
Enter the matrix of real numbers A(4,4). Get sequences of elements of the main and secondary diagonals, create vectors B(4) and C(4) from these elements and display them on the screen

1) In the form of comments:

· Name of laboratory work

· Student’s name, group number

· Option No.

· Individual task

2) Calculation protocol (session) in the window Command Window, supplied with the necessary comments.

1.3.7. Security questions on the topic

1) What is script- file and what are its features?

2) How script- is the file being executed?

3) What is m- functions I?

4) What is the difference script- file from m- functions?

5) Can m- function have multiple output parameters?

6) Appeal to m- functions.

7) Operator format input().

8) How to use operator if...end implement standard, truncated and nested branching?

9) Format of the multiple branch operator switch.

10) Regular loop operator format for...end, features of setting the values ​​of the loop variable.

11) Assignment of operators continue And brek.

12) Iterative loop operator while...end and its structure.


Section 2. Solution technology
computing problems using MatLab

Matlab loops and conditions: theory and examples

Good day. Today we will talk about cycles and conditions in Matlab. The material that is taken as a basis is help in Matlab and a few simple examples that we will look at.

Conditions in MATLAB

No programming language can do without such constructs as conditions, this is what we will talk about:
Let's start with the condition syntax if and look at the formal version of the entry in the help:

If expression, statements, end

What means:

If Condition, Action, end

Now examples:

X = 1; y = 61; if ((x >= 0.90) && (y >= 60)) disp("ok"); end;

&& is a logical multiplication operator (logical “AND”).
And here is an example with else:

X = 1; y = 50; if ((x >= 0.90) && (y >= 60)) disp("ok"); else disp("not right") end;

Unlike 1 example, “not right” will be displayed here.
A few words now about switch. Formally in the help:

Syntax switch switch_expr case case_expr statement, ..., statement case (case_expr1, case_expr2, case_expr3, ...) statement, ..., statement otherwise statement, ..., statement end

More down to earth:

Syntax switch switch_expr case Value - 1 Action case (Value - 2, Value - 3, Value - 4, ...) Action In other cases Action end

This means that if a given variable is equal to the value in case Value - 1, then the action is performed when case Value - 1 and so on. If none of case not suitable, action is performed when otherwise.
Here's an example:

Method = "Bilinear"; switch lower(method) case ("linear","bilinear") disp("Method is linear") case "cubic" disp("Method is cubic") case "nearest" disp("Method is nearest") otherwise disp( "Unknown method.") end

Loops in MATLAB

Now let's move on to cycles, starting with for.
In the help, this is written as

Syntax for index = values ​​program statements: end

In layman's terms this means:

Syntax for variable = value action end

Let’s not dwell on official formulations, it’s better to use clear and favorite examples

For m = 1:10 m end

This is what the most common usage looks like: for. In this loop we simply print out the value of m.
The second method using step ( step)

For s = 1.0: -0.1: 0.0 disp(s) end

In this case the cycle for goes from 1 to 0 in steps of -0.1.
Another option:

For s = disp(s) end

In this case the variable s will be sequentially equated to 1, 5, 8, 17 and, accordingly, output.
And also with for It is very convenient to display vectors. Here:

For e = eye(5) disp("Current value of e:") disp(e) end

In this example, there is a sequential access to the elements of the vector e.

Cycle while:
Formally in the help:

Syntax while expression program statements: end

Down to earth:

Syntax while Condition Action end

And let's immediately take an example (how it is used in real life).

Eps = 10; while eps > 1 eps = eps - 1 end

While in the condition ( eps > 1) is executed, the loop performs the action

(eps = eps-1).
Also in the condition while You can use logical operators AND - && and OR - || , writing several logical expressions into the condition.

If you have questions about the article, write in the comments.

codetown.ru

Loops for, while in Matlab (Matlab)

The for statement is designed to perform a specified number of repeated actions. The simplest use of the for statement is as follows:

for count = start:step:finalMatLab commandsend

Here count is a loop variable, start is its initial value, final is its final value, and step is the step by which count is increased each time the loop is entered. The loop ends as soon as count becomes greater than final. A loop variable can take not only integer values, but also real values ​​of any sign

The for loop is useful when performing repeated similar actions when the number of them is predetermined. A more flexible while loop allows you to get around this limitation.

while loop conditionMatLab commandsend

62. What command creates an M-book in a text editor Word associated with MatLab?

Starting a new M-book To start writing a new M-book, you need to: 1) launch the Word editor; 2) select in the dialog box Word option New from the menu File; 3) in the window that appears on the screen, select the M-book template. As a result of these actions, the system will be launched MatLAB, and the appearance of the main menu of the Word editor will change slightly - a new menu will appear in it Notebook. This will indicate that Word system connected MatLAB. If you now use the mouse to activate the menu Notebook window Word, an additional menu will appear on the screen

63. Which command in the Word text editor converts text into a MatLab input cell?

select a team Define Input Cell(Define Input Cell) in the menu Notebook(see Fig. 3.20), or press the keys; After this, the appearance of the command line should change - the command symbols become dark green, and the command becomes surrounded by dark gray square brackets;@

64. Which command in the Word text editor ensures that a MatLab command is executed in a cell?

select the Evaluate Cell command with the mouse, or press a key combination; the result of these actions should be the appearance immediately after the command text of the results of its execution by the MatLAB system. The results of the command are displayed in blue and enclosed in square brackets.

65. Which command in the Word text editor ensures that MatLab commands are executed throughout the M-book?

Commands of all cells or groups of input cells of a section are executed using the Evaluate Calc Zone item, and the entire M-book at once – Evaluate M-book

66. Which command in the Word text editor ensures that MatLab commands are executed in all cells automatically when opening an M-book?

Commands for cells with the Autolnit style are launched immediately after opening the M-book. It is useful to include a clear command in the first such cell to clear the work environment. To set the Autolnit style, use the Define Autoinit Cell item in the Notebook menu

67. What buttons does the Excel Link panel in an Excel spreadsheet contain when linked to MatLab?

68. What does the putmatrix command provide?

The MLPutMatrix function is used to place data from Excel worksheet cells into an array of the Matlab work environment. The arguments to this function are the name of the variable, enclosed in quotes, and the range of Excel cells related to this variable.

68. What does the getmatrix command provide?

The reverse operation is performed by the MLGetMatrix function, and the arguments of this function are the name of the MatLab working environment variable with 22 data, enclosed in quotes, and the range of Excel cells where the data of this variable will be placed, also enclosed in quotes.

70. What is the purpose of Simulink?

The Matlab system includes a package for modeling dynamic systems - Simulink. This package is the core of an interactive software package designed for mathematical modeling of linear and nonlinear dynamic systems represented by their functional block diagram, called the S-model or simply the model

71. Which Simulink library contains signal sources?

Let's build the simplest model of a sinusoidal signal source that is fed to the input of a virtual oscilloscope. To do this, click on the button to open the library browser and in the left part of the browser window that appears, click on the section Sources(Sources), while icons of the blocks included in this section are displayed on the right side of the window

72. Which Simulink library contains recording virtual instruments?

oscilloscope Scope from the section Sinks.

73. Which Simulink library contains differentiation and integration blocks?

Continuous contains continuous blocks. The most important ones include the Derivative differentiation and Integrator integration blocks. The first block performs numerical differentiation of the input signal; no parameters are entered for this block. The second block in the parameters window contains several fields in which you can set the integration constant at the output of the block in the Initial condition field

74. Which Simulink library contains blocks for calculating elementary functions?

Library window Math contains blocks for performing mathematical operations

The blocks for calculating elementary functions include three blocks: a block of mathematical functions MathFunction, trigonometric functions block TrigonometricFunction and rounding function block Rounding Function.

75. How many step parameter values ​​are set in Simulink for a variable simulation step?

Two solver options in the Solver options field are of great importance: solution type and solution method. There are two possible options for the first option:

Variable-step solvers – solutions with variable steps;

Fixed-step solvers – solution with a fixed step. By default, the solution option with a variable step is set, when the step is automatically reduced as the rate of change of results increases and vice versa. This method generally produces better results than fixed-step simulations, eliminating discrepancies in most cases. The use of fixed-step modeling is usually used if this is due to the specifics of the problem being solved

studfiles.net

Loops like for...end MatLab

Lesson 20. Programming Basics Programming Basics
Basic programming tools
Basic Data Types
Types of programming
Duality of operators, commands and functions
Some restrictions
M-files for scripts and functions
Structure and properties of script files
Status of Variables in Functions
M-function-file structure
Variable status and global command
Using Subfunctions
Private directories
Error processing

Displaying Error Messages
lasterr function and error handling
Variable Functions
Functions for counting the number of arguments
Variables varargin and varargout
Comments
Features of executing m-function files
Creation of P-codes
Control structures
Dialog input
Conditional operator
Loops like for...end
Loops like while...end
Switch design
try...catch...end construct
Pausing calculations
The concept of object-oriented programming
Creating a Class or Object
Checking whether an object belongs to a given class
Other Object-Oriented Programming Features
What new have we learned?

Loops like for...end are usually used to organize calculations with a given number of repeating loops. The structure of such a cycle is as follows:

for va = Expression.

The expression is most often written in the form s:d:e, where s is the initial value of the loop variable var, d is the increment of this variable, and e is the final value of the control variable, upon reaching which the loop ends. It is also possible to write it in the form s:e (in this case d=l). The list of instructions executed in a loop ends with the end operator.

The following examples explain the use of a loop to obtain the squares of a loop variable:

» for 1=1:5 i^2. end;

"for x=0:.25:1 X ^ 2, end:

The continue statement passes control to the next iteration of the loop, skipping the statements that follow it, and in a nested loop it passes control to the next iteration of the main loop. The break statement can be used to terminate a loop early. As soon as it is encountered in the program, the loop is interrupted.

Nested loops are possible, for example:

As a result of executing this cycle (file for2.m), matrix A is formed: It should be noted that forming matrices using the operator: (colon) usually takes much less time than using a loop. However, the use of a cycle is often more visual and understandable. MATLAB allows an array of size A to be used as a loop variable

txp.

In this case, the loop is executed as many times as there are columns in array A, and at each step the variable var is a vector corresponding to the current column of array A:

"A=

"for var=A; var, end

radiomaster.ru

Illustrated tutorial on MatLab › Basics of programming › Loops like for…end. Loops like while...end. [page - 364] | Tutorials on math packages for...end Loops like for...end. Loops like while...end.

Loops like

are usually used to organize calculations with a given number of repeating cycles. The structure of such a cycle is as follows: var for var = Expression. Instructions..... Instructions end

The expression is most often written in the form s:d:e, where s is the initial value of the loop variable

, d is the increment of this variable and e is the final value of the control variable, upon reaching which the cycle ends. It is also possible to write it in the form s:e (in this case d=1). The list of instructions executed in a loop ends with the end operator.

The following examples explain the use of a loop to obtain the squares of the values ​​of a loop variable:

Operator continue passes control to the next iteration of the loop, skipping the statements that are written after it, and in a nested loop it passes control to the next iteration of the main loop. Operator break can be used to terminate a loop early. As soon as it is encountered in the program, the loop is interrupted. Nested loops are possible, for example:

A(1 .j) = i + j;

As a result of executing this loop (file for2.m) matrix A is formed:

It should be noted that forming matrices using the operator: (colon) usually takes much less time than using a loop. However, the use of a cycle is often more visual and understandable. MATLAB allows an array of size A to be used as a loop variable thp. In this case, the loop is executed as many times as there are columns in array A, and at each step the variable var is a vector corresponding to the current column of array A:

> > A = [ 1 2 3: 4 5 6 ]

> > for var = A; var , end

Loops like while...end

Loop type while is executed as long as the Condition is met:

while Condition Instructions end

Example of using a loop while has already been cited. Early termination of loops is implemented using the operators break or continue.

St. Petersburg: BHV-Petersburg, 2005. - 1104 p.
ISBN 5-94157-494-0
Download(direct link) : matlab72005.pdf Previous 1 .. 117 > .. >> Next

while MATLAB command loop repeat condition

In this example, the condition for repeating the cycle is that the modulus of the current term is x2k~l/(2k +1)! more than IO10. To record a condition in a form,

understandable by MATLAB, you should use the ">" (greater than) sign. Text of the file function mysin, which calculates the sum of a series based on a recurrence relation

k 2k(2k + \) k 1

is shown in Listing 7.7.

Note^

Of course, in the general case, the smallness of a summand is a relative concept; the summand can be, say, of the order of IO-10, but the sum itself is of the same order. In this case, the condition for ending the summation must be different, namely the smallness of the modulus of the ratio of the current summand to the already accumulated part of the sum. Let's not pay attention to this for now - our task is to study how to work with cycles.

Listing 7.7. File function mysin, calculating sine by series expansion

function s - mysin(x)

"% Calculation of sine by series expansion

% Usage: y = mysin [x), -pi< х < piГлава 7. Управляющие конструкции языка программирова ни я

Ї calculation of the first term of the sum for k = O k = 0; their;

% calculation of the auxiliary variable x2 - x*x;

while abs(u) > 1.Oe-IO k = k + 1; u = -u* x2/(2*k)/(2*k + 1)

Please note that the while loop, unlike for, does not have a loop variable, so we had to assign one to k before starting the loop, and increase k by one inside the loop.

Now compare the result by plotting the functions mysin and sin on the segment [-l, i] Fia on the same axes, for example, using fplot (commands can be specified from the command line): "fplot (@rnysin, [-pi, pi])" hold on

» fplot(@sin, t-pii pi]i "k.")

Rice. 7.3. Comparison of mysin and sin360_________ Part II. Computing and programming

The resulting graphs are shown in Fig. 7.3, they indicate the correct operation of the mysin file function.

A while loop condition can contain a logical expression made up of relational and logical operators or operators. To set the cycle repetition condition, the relational operations given in Table 1 are valid. 7.1.

Table 7.1. Relation operations

Designation Relational operation
== Equality
< Меньше
<= Меньше или равно
>= Greater than or equal to
Not equal

Setting more complex conditions is done using logical operators or operations. For example, condition -1<.г<2 состоит в одновременном выполнении неравенства а>-1 and x<2 и записывается при помощи логического оператора and

and(x >= -1, X< 2)

or equivalently using the logical operator "and" - &

(x >= -1) & (x< 2)

Basic logical operations and operators and examples of their recording are given in table. 7.2 (logical expressions are described in detail in the section “Logical operations with numbers and arrays” of this chapter).

Table 7.2. Boolean expressions

Expression type Expression Logical operator Logical operation
Logical "and" A*<3 И к=4 and (х < 3, k==4) (х<3) s (k = 4)
Logical "or" X = Ї or 2 or (x == 1, X= 2) (x == 1) I (x == 2)
Negation of “not” a* 1.9 not (a == 1.9) -(a == 1.9)Chapter 7. Control constructs of the programming language

^Note^

The not, and, and or operators are functions that return true (logical one) or false (logical zero). Any logical expression takes the same values.

When calculating the sum of an infinite series, it makes sense to limit the number of terms. If a series diverges because its terms do not tend to zero, then the condition for the smallness of the current term may never be satisfied and the program will go into loop. Perform the summation by limiting the number of terms. Add a limit on the number of terms to the while loop condition of the mysin function file (see Listing 7.6):

(abs(u) > 1.Oe-IO) & (k<= 100000) или в эквивалентной форме:

and l.Oe-lO,k<= 100000)

^Note^

To specify the order in which logical operations are performed, you should use parentheses (more information about logical operators and logical operations and the possibility of applying them to arrays is written in

section "Logical Expressions with Arrays and Numbers" in this chapter).

When programming algorithms, in addition to organizing repeating actions in the form of cycles, it is often necessary to execute one or another block of commands depending on certain conditions, i.e. use algorithm branching.

Branch Operators

The conditional if statement and the switch statement allow you to create a flexible branching algorithm in which, when certain conditions are met, a corresponding block of MATLAB statements or commands is executed. Almost all programming languages ​​have similar operators.

Conditional if statement

The if statement can be used in its simple form to execute a block of commands when some condition is satisfied, or in an if-eiseif-eise construct to write branching algorithms.362

Part II. Computing and programming

Checking Input Arguments

Let's start with a simple example - create a function file to calculate

Department: Information technology

PROGRAMMING INMATLAB


OperatorsMATLAB

· Loop statements

Cyclefor

Syntax

for count=start:step:final

MATLAB commands

Description

count – loop variable,

start – its initial value,

final – its final value,

step – step by which count increases with each subsequent entry into the loop

the loop ends as soon as the value of count becomes greater than final.

Example

Let it be necessary to derive a family of curves for x€, which is specified by a function depending on the parameter

y (x, a) = e -ax sin x,

for parameter a values ​​from -0.1 to 0.1. Below is a listing of the program file for displaying a family of curves.

Program listing

x = ;

for a = -0.1:0.02:0.1

y = exp (-a*x).*sin(x);

As a result of executing the program, a graphic window will appear that contains the required family of curves.

Cyclewhile

Syntax

while loop condition

MATLAB commands

Description

The loop runs as long as the loop condition is true. To set the loop execution condition, the following relational operations are allowed:

Setting more complex conditions is done using logical operators. The logical operators are given in the following table


Example

Branch Operators

Conditional operatorif

Syntax

if condition

MATLAB commands

Description

If the condition is true, then the MATLAB commands located between if and end are executed, and if the condition is not true, then the commands located after end are executed.

Example

Conditional operatorelseif

Syntax

if condition1

elseif condition2

………………………

elseif condition

Description

Depending on the fulfillment of a particular condition, the corresponding branch of the program runs; if all conditions are false, then the commands placed after else are executed.

Example

Operatorswitch

Syntax

switch variable

case value1

case value2

……………………

casemeaningn


Each branch is defined by a case statement and is entered when the switch statement variable takes the value specified after case or one of the values ​​from the case list. After executing any of the branches, the switch exits, and the values ​​​​specified in other cases are no longer checked. If no suitable values ​​are found for the variable, then the program branch corresponding to otherwise is executed.

Example

Cycle interruptions. Exceptional situations.

Operatorbreak

Syntax

The break operator is used to organize cyclic calculations: for…end, while…end. When the condition is met

if condition

The break statement ends the loop (for or while) and the statements that are located in the lines following end are executed. In the case of nested loops, break exits the inner loop.

Exception handling, operatortrycatch

Syntax

statements whose execution

may lead to an error

statements to be executed

when an error occurs in the block

between try and catch

Description

The try...catch construct allows you to bypass exception situations (errors that lead to the termination of the program, for example, accessing a non-existent file) and take some actions if they occur.

Example

Service functions

disp outputs text or the value of a variable to the command window

input– requests input from the keyboard. Used when creating applications with a command line interface.

eval executes the contents of a string or string variable, like MATLAB commands

clear– deletes work environment variables.

Withlc– clears the command window

More information about these and other functions can be found by running at the command line

helpfunction_name

Laboratory work assignments

The number of a specific assignment option is determined by the teacher.

Task No. 1

This task involves finding an algebraic interpolation polynomial of degree n for a certain set of data: P n(x) .

Goal of the work:

It is necessary to create a program for calculating the coefficients of an algebraic interpolation polynomial P n(x)= a 0 + a 1 x+ … + a n x n.

Guidelines:

Let, for example, have the following set of data:

i 0 1 2 3
Xi 1,2 1,4 1,6 1,8
y i 8,3893 8,6251 8,9286 8,9703

Odds a 0 , a 1 , …, a n are determined from solving the system of equations:

Here n– order of the interpolation polynomial,

n+1 – number of given pairs of points ( x, y),

a 0 , a 1 ,… a n– the required coefficients of the polynomial P n(x)= a 0 + a 1 x+ … + a n x n).

Program requirements

· Set the boundaries of the segment , on which the interpolation polynomial is constructed P(x)

· Set n– the number of interpolation segments (or, what is the same, the degree of the polynomial)

Note: x0, xn, n entered from the keyboard.

· To obtain initial data (x, y)(number of pairs of points (x i, y i), from which the interpolation polynomial is constructed P(x)n1=n+1) provide:

Entering random nodes x i, i=0, n from the keyboard

Node calculation x i , i=0, n, corresponding to the uniform arrangement of the argument x on the segment

In paragraphs 1.2 values y i , i=0, n either entered from the keyboard (if the source function is unknown) or calculated from a given function f(x). The expression defining the function is entered from the keyboard and must comply with the rules for writing expressions in MATLAB

Data input ( x i, y i, i=0, n) from file

· Solve a system of equations to determine the coefficients of the polynomial P(x)

· Construct graphs of the original tabular function and the polynomial P(x)

· If the source data is given as a function f(x), plot the interpolation error /f(x) – P(x)/. Calculate the maximum absolute value of the interpolation error at a given interval.

When performing the last point on the segment take at least 500 points for calculations

Task No. 2

Spline interpolation

Goal of the work:

It is necessary to create a program for calculating coefficients and constructing a spline function S(x), “glued together” from pieces of 3rd order polynomials S i(x), which have a special recording form:

,

function S i(x) defined on the segment ,

Program requirements

When performing this work you must:

· Set the boundaries of the segment on which the spline function S(x) is constructed

· Set n – the number of interpolation segments, on each of which the cubic polynomial Si(x) is constructed.

· Note: x0, xn, n are entered from the keyboard.

· Organize the input of initial data (x, y) (the number of pairs of points (xi, yi) from which the spline function S(x), n1=n+1 is constructed), providing:

Entering randomly located nodes xi, i=0, n from the keyboard

Calculation of nodes xi, i=0, n, corresponding to the uniform location of the argument x on the segment

In paragraphs 1,2 the values ​​of yi, i=0, n are either entered from the keyboard (if the original function is unknown) or calculated from a given function f(x). The expression defining the function is entered from the keyboard and must comply with the rules for writing expressions in MATLAB

Entering data (xi, yi, i=0, n) from file

S1""(x0)=0, S3""(x3)=0

S1"(x0)=f "(x0), S3"(x3)=f "(x3)

S1""(x0)=f "(x0), S3""(x0)=f "(x3)

· To determine the coefficients of a natural cubic spline (boundary conditions 1), it is necessary to solve the following system of equations:

Coefficients σ 0 =0,σ n =0

· Construct graphs of the original function and spline functions for all three types of boundary conditions.

· Construct graphs of spline interpolation error functions f(x) – S(x) for all three types of boundary conditions.

Note:

In MATLAB, the indexes of one-dimensional and two-dimensional arrays start from 1, not from 0. Take this into account when composing the program.