Programming in MATLAB. Algorithmic operators Matlab Variants of individual tasks

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

Consider the operators m-files in more detail.

Assignment operator. The main operator of the programming system Matlab is an assignment operator with the following structure:

Variable Name= 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 (Figure 1.3.4-1).

Rice. 1.3.4-1. Assignment Operators Examples

All variables used on the right side of the assignment operator must be predefined. 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 operators located in m-files.

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

Variable Name= input ("Request");

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

Rice. 1.3.4-3. Evaluating a Symbolic Expression

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 construction allows several particular variants. The simplest is truncated forking [x] looks like this:

ifBooleanExpression

Instructions

Recall that if BooleanExpression returns boolean 1 (that is, "True"), the Instructions that make up the body of the structure if ... end... Moreover, the operator end indicates the end of the instruction list. The statements in the list are separated by a comma or semicolon. If BooleanExpression fails (gives boolean 0 , "False"), then Instructions are also not met.

Below is an example of using the simplest truncated branching implemented using the operator if(fig. 1.3.4-4).

Rice. 1.3.4-5. Example of standard branching

From the above example, you can see that the operator if can be either in one line or in several lines.

Consider an example of a more complex one - nested forking... Let's consider an example

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

Rice. 1.3.4-7. Function that implements nested forking

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

switchExpression

caseConception_1

Instruction_List_1

caseValue_2

Instruction_List_2

caseValue_N

Instruction_List_N

Otherwise

Instruction_List_N + 1

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

M-function that implements multiple forking is shown in Fig. 4-8, and referring to it with the initial data, allowing you to check each branch of the fork, is shown in Fig. 1.3.4-9.

Rice. 1.3.4-9. Function calls multifunc ()

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

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

for vag = s: d: e

Instruction1

InstructionN

where s - the initial value of the loop variable var, d - the increment of this variable and e - the final value of the manipulated variable, upon exceeding which the cycle 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 an operator end.

As an example of using the operator for ... end calculate the sum of the array elements NS 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 NS is determined by the function length... In addition to calling a function in the command window, it is possible 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 the loop continue , which transfers control to the next iteration of the loop, skipping the statements that are written after it, and in the nested loop, it transfers control to the next iteration of the main loop. Operator break can be used to prematurely interrupt the execution of a cycle (for example, when debugging a program section). As soon as it is encountered in the program, the loop is interrupted.

In addition to simple regular cycles, Matlab has the ability to organize nested loops... 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 is shown in Fig. 1.3.4-13.

Rice. 1.3.4-13. Appeal to script-file with the 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 instructions located in the body of the repetition structure are executed only if some BooleanExpression"True." As soon as the condition becomes "false", the repetition 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. Dialogue program using operator while ... end

This program saved in m-file with the name primer11, serves for repeated calculation of the circumference from the radius value entered by the user r where the dialog is implemented using the command input. Variable input strings r and calculating 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 quantity r is defined to be 0, the loop repeats at least once.

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

Rice. 1.3.4-16. Interruption of the program with the use of the operator break

Operator continue transfers control to the next iteration of the loop, skipping the statements that are written after it, and in the nested loop, it transfers 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. Interruption of the program with the use of the operator continue

Examples of solving problems using

M-files

Example 1.3.5-1. You are given n numbers ... It is required to calculate their sum: where

To solve the problem, the 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 called in a loop organized to calculate the sum (Fig. 1.3.5-2).

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

To calculate the sum of the values ​​of the function, created script-file named zadashа.m, in which the number of numbers ( n = 10) and the vector of their values ​​( b), and then a regular loop is organized to call the function fb () and calculating the amount.

Calculations are done 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 to execute

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

In fig. 1.3.5-4 is given script-file named zadasha2, where the matrix is ​​introduced, a consisting of three rows and four columns. The cycle is organized by the number of formed array elements b by calling the function sred_ar ()... An array is passed to the function a, line number ( i) and the number of elements in the line ( m). Displaying 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 running script-file with the name zadasha2 out the window Command Window a column of array elements is output b

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

Rice. 1.3.5-9. Function launch sumf () to execute


Laboratory work on the topic

"Algorithmization and programming tools

In Matlab "

Questions to be studied

1) Types m- files.

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

3) Features script- files and m- functions.

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

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

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

7) Tools of the programming language in the Matlab system.

8) The main operators of the m-language, their purpose and formats .

2. General task

1) Study the material of Topic 1.3 (p.p. 1.3.1 - 1.3.5).

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

3) Develop m -functions for the implementation of standard algorithms: calculating finite sums, branching, finding the minimum and maximum in a data sequence, etc.

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

5) Create newscript -file in which enter the program code describing the logic of solving the problem.

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

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

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

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

10) Save the text working window on external media.

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

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

13) Prepare a report for the work done .


Options for individual assignments

Table 1.3.6-1

Exercise
Enter a natural number n and the 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 polyline vertex. Construct a polyline connecting the last vertex with the first
... Calculate the product , where
Enter a natural number n and a real number x. Calculate
Enter a natural number n. Find Largest Among Values , where k = 1, 2, ..., n, as well as the sum of all obtained values
Enter a natural number n. Among the meanings , where
(i = 1,2, ... n), find all positive ones and calculate their sum
Enter a natural number n and a vector of real numbers ... Determine if there are more positive or negative numbers in a vector, and determine the largest of the negative and the smallest of the positive numbers
Enter the matrix B (5,7) and form the vector C (5) from the first largest elements of the rows. Output its elements to row and column
Generate a vector according to the rule: , where k = 2,3,…, 7, if Find the sum of the squares of those numbers that do not exceed 2
Enter a natural number n and a vector of real numbers ... Find the number of two adjacent positive numbers and two adjacent numbers of opposite sign
Enter the square matrix A (4.4). Form a vector X from the maximum elements of its columns, display its elements on the screen in direct and reverse order
Introduce a vector of integers ... Transform it so that zeros are located first, then all other elements. Determine the sum and number of elements, the values ​​of which are a multiple of 5
Introduce a vector of real numbers ... Create an array x from it, each element of which is the maximum of three elements in a row in the array z
Form the matrix A (4,4) according to the rule:
Find and display the values ​​and indices of two identical elements. If there are none, display the message
Form the matrix D (3,2) according to the rule: ... Create a vector from negative elements of the resulting matrix
Set 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 formed matrices
Enter a square matrix of real numbers A (4,4). Find the sum of the largest values ​​of the elements of its rows. Form a new matrix B (4,4) by multiplying each element of the 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 line; · The smallest of the elements in the second line; · The arithmetic mean of the elements of the third line; The sum of the elements of the fourth line
Enter a natural number n and a 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 the matrix C on the screen
Enter natural numbers k1, k2 and a real 8x4 matrix. Swap the elements of k1 and k2 rows in the matrix
Enter a natural number n and a matrix of real numbers C (n, 9). Find the arithmetic mean of each of the even-numbered columns
Enter vectors of real numbers x (5), y (6), z (7). Calculate the value of t using the following algorithm:
Enter vectors of real numbers x (5). Get x = 1, 3, 4 values where
Enter vectors of real numbers x (10). Get from it another array p (10), the elements of which are ordered in ascending order
Enter the matrix of real numbers A (3,4). Replace the elements of the matrix row with the maximum sum of the values ​​of the elements - with ones, with the minimum - with twos, and set the remaining elements of the matrix equal to zero
Form matrix A (4,4) according to the rule Remove from it columns containing elements less than 10
Form the matrix B (9.3) according to the rule Determine the smallest element in each row of the matrix and write it into the corresponding element of the vector C. Output the resulting vector C
Introduce a matrix of real numbers A (3,4), all elements of which are different. In each row, the largest and smallest values ​​should be selected, and the sum of the indexes of the columns in which they are located should be written into 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 diagonal, create vectors B (4) and C (4) from these elements and display them on the screen

1) In the form of comments:

Lab title

Full name of the student, group number

· Option No.

Individual task

2) Protocol of calculations (sessions) in the window Command Window provided with the necessary comments.

1.3.7. Control questions on the topic

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

2) How script- is the file being run?

3) What is m- function I am?

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

5) Can m- function have multiple outputs?

6) Referring to m- function.

7) Operator format input ().

8) As using the operator if… end implement standard, truncated and nested branching?

9) Multi-forking operator format switch.

10) Format of the regular cycle operator for… end, specifics of setting the values ​​of the cycle variable.

11) Assignment of operators continue and brek.

12) Iterative Loop Operator while ... end and its structure.


Section 2. Solution technology
computational tasks by means of MatLab

The language of technical computing

Millions of engineers and scientists around the world use MATLAB® to analyze and develop systems and products that are transforming our world. The matrix language MATLAB is the world's most natural way to express computational mathematics. Built-in graphics make it easy to visualize and understand the data. The desktop environment encourages experimentation, exploration, and discovery. These MATLAB tools and capabilities are all rigorously tested and designed to work together.

MATLAB helps you bring your ideas to life outside of the desktop. You can run explorations on large datasets and scale to clusters and clouds. MATLAB code can be integrated with other languages, allowing you to deploy algorithms and applications across a network, enterprise, and industrial systems.

Beginning of work

Learn MATLAB Basics

Language basics

Syntax, array indexing and processing, data types, operators

Data import and analysis

Import and export of data, including large files; data preprocessing, visualization and research

Maths

Linear algebra, differentiation and integration, Fourier transforms and other mathematics

Graphics

2D and 3D graphics, images, animation

Programming

Scripts, functions and classes

Application creation

Application development with App Designer, programmable workflow, or GUIDE

Software development tools

Debugging and testing, organizing large projects, integration with a version control system, packaging toolboxes

The language of technical computing

Millions of engineers and scientists around the world use MATLAB® to analyze and develop systems and products that are transforming our world. The matrix language MATLAB is the world's most natural way to express computational mathematics. Built-in graphics make it easy to visualize and understand the data. The desktop environment encourages experimentation, exploration, and discovery. These MATLAB tools and capabilities are all rigorously tested and designed to work together.

MATLAB helps you bring your ideas to life outside of the desktop. You can run explorations on large datasets and scale to clusters and clouds. MATLAB code can be integrated with other languages, allowing you to deploy algorithms and applications across a network, enterprise, and industrial systems.

Beginning of work

Learn MATLAB Basics

Language basics

Syntax, array indexing and processing, data types, operators

Data import and analysis

Import and export of data, including large files; data preprocessing, visualization and research

Maths

Linear algebra, differentiation and integration, Fourier transforms and other mathematics

Graphics

2D and 3D graphics, images, animation

Programming

Scripts, functions and classes

Application creation

Application development with App Designer, programmable workflow, or GUIDE

Software development tools

Debugging and testing, organizing large projects, integration with a version control system, packaging toolboxes

Department: Information Technology

PROGRAMMING INMATLAB


OperatorsMATLAB

· Loop Operators

Cyclefor

Syntax

for count = start: step: final

MATLAB commands

Description

count is a loop variable,

start - its initial value,

final is its final value,

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

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

Example

Let it be required to derive a family of curves for x €, which is given 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 outputting 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 the program execution, a graphic window will appear, which contains the required family of curves.

Cyclewhile

Syntax

while loop condition

MATLAB commands

Description

The loop runs as long as the loop condition is satisfied (true). To set the conditions for the execution of the cycle, the following relation operations are allowed:

More complex conditions are specified using logical operators. Logical operators are shown in the following table


Example

Branching operators

Conditional operatorif

Syntax

if condition

MATLAB commands

Description

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

Example

Conditional operatorelseif

Syntax

if condition1

elseif condition2

………………………

elseif conditionn

Description

Depending on the fulfillment of this or that condition, the corresponding branch of the program works, if all the conditions are incorrect, then the commands placed after the else are executed.

Example

Operatorswitch

Syntax

switch variable

case value1

case value2

……………………

case value n


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

Example

Interrupts the cycle. Exceptional situations.

Operatorbreak

Syntax

The break operator is used when organizing 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 on the lines following end are executed. In the case of nested loops, break exits the inner loop.

Exception handling, operatortrycatch

Syntax

operators whose execution

may result in an error

statements to be executed

when an error occurs in a block

between try and catch

Description

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

Example

Service functions

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

input- makes a request for keyboard input. Used when creating applications with a command line interface.

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

clear- removes variables of the working environment.

withlc- clears the command window

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

helpfunction_name

Laboratory tasks

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

Task number 1

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

Purpose of work:

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

Methodical instructions:

For example, suppose you have the following set of data:

i 0 1 2 3
NSi 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 the solution of the system of equations:

Here n- the order of the interpolation polynomial,

n+1 - the number of specified 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).

Requirements for the program

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

· Ask 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 the initial data (x, y)(number of pairs of points (x i, y i), by which the interpolation polynomial is constructed P (x)n1 = n + 1) provide:

Entering randomly spaced nodes x i, i = 0, n from the keyboard

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

In pp. 1.2 values y i, i = 0, n either entered from the keyboard (if the original function is unknown), or calculated by a given function f (x)... An expression defining a function is entered from the keyboard and must follow the rules for writing expressions in MATLAB

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

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

Build graphs of the original table-defined function and the polynomial P (x)

· If the initial data are specified as a function f (x), build a graph of the interpolation error / f (x) - P (x) /. Calculate the maximum modulus 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 number 2

Spline interpolation

Purpose of work:

It is necessary to compose a program for calculating the coefficients and constructing a spline function S (x), "glued" from pieces of 3rd order polynomials S i(x), which have a special notation:

,

function S i(x) defined on the segment

Requirements for the program

When performing this work, you must:

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

· Specify 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 the initial data (x, y) (the number of pairs of points (xi, yi), which are used to construct the spline function S (x), n1 = n + 1), providing:

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

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

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

Data input (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 the natural cubic spline (boundary conditions 1), it is necessary to solve the following system of equations:

Coefficients σ 0 = 0, σ n = 0

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

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

Note:

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

Often, when organizing a loop, it is required to iterate over the counter value in a given range of values ​​and with a given step of change. For example, to iterate over the elements of a vector (array), you need to organize a counter from 1 to N with a step of 1, where N is the number of vector elements. To calculate the sum of the series, a counter from a to b is also set with the required step. Etc. Due to the fact that such tasks are often encountered in programming practice, for their implementation, a for loop operator was proposed, which makes it easier and more visual to implement a loop with a counter.

The syntax of the for loop statement is as follows:

for<счетчик> = <начальное значение>:<шаг>:<конечное значение>
<операторы цикла>
end

Let's consider the operation of this cycle using an example of the implementation of the algorithm for finding the maximum value of an element in a vector:

function search_max
a =;
m = a (1); % current maximum value
for i = 1: length (a)% loop from 1 to the end of the vector with
% in steps of 1 (default)
if m< a(i) % если a(i) >m,
m = a (i); % then m = a (i)
end
end% end of for loop
disp (m);

In this example, the for loop sets the counter i and changes its value from 1 to 10 in increments of 1. Note that if the step size is not specified explicitly, it defaults to 1.

In the next example, we will consider the implementation of the algorithm for shifting the elements of a vector to the right, i.e. the penultimate element is put in the place of the last one, the next one - in the place of the penultimate one, etc. up to the first element:

function queue
a =;
disp (a);
for i = length (a): - 1: 2% loop from 10 to 2 in increments of -1
a (i) = a (i-1); % shift the elements of the vector a
end% end of for loop
disp (a);

The result of the program

3 6 5 3 6 9 5 3 1 0
3 3 6 5 3 6 9 5 3 1

The above example shows that to implement a loop with a counter from a higher value to a lower one, you need to explicitly specify the step, in this case, -1. If this is not done, then the cycle will immediately end its work and the program will not work correctly.

In conclusion, we will consider the operation of the for loop operator using the example of modeling a random sequence with the law of change

where is the coefficient from -1 to 1; - normal random variable with zero mathematical expectation and variance

,

where is the variance of the simulated random process. In this case, the first sample is modeled as a normal random variable with zero mathematical expectation and variance. The simulation program looks like this:

function modeling_x
r = 0.95; % model factor
N = 100; % number of simulated points
ex = 100; % process variance
et = ex * (1-r ^ 2); % variance of random addition
x = zeros (N, 1); % initialization of vector x
x (1) = sqrt (ex) * randn; % simulation of 1st sample
for i = 2: N% loop from 2 to N
x (i) = r * x (i-1) + sqrt (et) * randn; % simulation of joint venture
end% end of loop
plot (x); % display of SP in the form of a graph

When executing this program, the implementation of the simulated random sequence will be shown.

Rice. 2.1. The result of simulating a random sequence.

The work of the program begins with the definition of variables (in the program the variable ex) and for the implementation of the specified model. Then the variance is calculated and the first sample of the random process is simulated using the randn function. The randn function generates normal random variables with zero mean and unit variance. To generate a random variable with variance, it is sufficient to multiply the random variable with unit variance by, since variance is the mean square of a random variable relative to the mathematical expectation. As a result, we have a program line

x (1) = sqrt (ex) * randn;

Then, a for loop is implemented with a counter i from 2 to N with a step of 1. Inside the loop, the remaining N-1 samples of the random process are simulated in accordance with the above formula. The last line of the program contains the plot () function, which displays the modeled sequence on the screen in the form of a graph. Working with the display of graphs on the screen will be discussed in more detail in the next chapter.