Programming in MATLAB. Loop in Matlab for – Illustrated tutorial on MatLab › Programming Basics › Loops like for…end
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 vector of cells, 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 | |
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 | |
Enter the natural number n and the vector of real numbers . Find the number of two adjacent positive numbers and two adjacent numbers of different signs | |
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 | |
Enter a vector of integers . 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 | |
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: | |
Enter the vectors of real numbers x(5). Get values for x=1, 3, 4 Where | |
Enter the vectors of real numbers x(10). Get another array p(10) from it, 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 element values - ones, with the minimum - twos, and set the remaining elements of the matrix equal to zero | |
Form the matrix A(4,4) according to the rule Remove columns from it 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 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
Conditional if statement
In the simplest case, the syntax of this if statement is:
if<выражение>
<операторы>
end
I would like to draw your attention to the fact that, unlike modern programming languages, such a concept as a compound operator is not used. The conditional statement block must end with the service word end.
Below is an example implementation of the sign() function, which returns +1 if the number is greater than zero, -1 if the number is less than zero, and 0 if the number is zero:
x = 5;
if x > 0
disp(1);
end
if x< 0
disp(-1);
end
if x == 0
disp(0);
end
Analysis of the above example shows that all these three conditions are mutually exclusive, i.e. When one of them is triggered, there is no need to check the others. The implementation of just such logic will increase the speed of program execution. This can be achieved by using the design
if<выражение>
<операторы1>% are executed if the condition is true
else
<операторы2>% are executed if the condition is false
end
Then the above example can be written as follows:
X = 5;
if x > 0
disp(1);
else
if x< 0
disp(-1);
else
disp(0);
end
end
This program first checks to see if x is positive, and if so, prints the value 1 and ignores all other conditions. If the first condition turns out to be false, then the program execution proceeds via else (otherwise) to the second condition, where the variable x is checked for negativity, and if the condition is true, the value -1 is displayed on the screen. If both conditions are false, then the value 0 is displayed.
The above example can be written in a simpler form using another MatLab if statement construct:
if<выражение1>
<операторы1>% are executed if expression1 is true
elseif<выражение2>
<операторы2>% are executed if expression2 is true
...
elseif<выражениеN>
<операторыN>% are executed if expressionN is true
end
and is written as follows:
x = 5;
if x > 0
disp(1); % is executed if x > 0
elseif x< 0
disp(-1); % is executed if x< 0
else
disp(0); % is executed if x = 0
end
Using the if statement, you can test more complex (compound) conditions. For example, you need to determine: does the variable x fall within the range of values from 0 to 2? This can be implemented by simultaneously checking two conditions at once: x >= 0 and x<=2. Если эти оба условия истинны, то x попадает в диапазон от 0 до 2.
To implement compound conditions in MatLab, logical operators are used:
& - logical AND
| - logical OR
~ - logical NOT
Let's look at an example of using compound conditions. Suppose you want to check whether a variable x is in the range from 0 to 2. The program will be written as follows:
x = 1;
if x >= 0 & x<= 2
else
end
In the second example, we will check to see if the variable x does not belong to the range from 0 to 2. This is achieved by triggering one of two conditions: x< 0 или x > 2:
x = 1;
if x< 0 | x > 2
disp("x does not belong to the range from 0 to 2");
else
disp("x belongs to the range from 0 to 2");
end
Using the logical operators AND, OR, NOT, you can create a variety of compound conditions. For example, you can check that x is in the range -5 to 5, but not in the range 0 to 1. Obviously, this can be implemented like this:
x = 1;
if (x >= -5 & x<= 5) & (x < 0 | x > 1)
disp("x belongs to [-5, 5], but is not in ");
else
disp("x or not in [-5, 5] or in ");
end
Note that parentheses were used in the complex compound condition. The fact is that the priority of the AND operation is higher than the priority of the OR operation, and if there were no parentheses, the condition would look like this: (x >= -5 and x<= 5 и x < 0) или x >1. Obviously, such a check would give a different result from the expected one.
Parentheses in programming are used to change the execution priorities of statements. Like arithmetic operators, logical operators can also be modified at the request of the programmer. By using parentheses, the test is done inside them first, and then outside them. That is why in the example above they are necessary to achieve the required result.
The priority of logical operations is as follows:
NOT (~) – highest priority;
And (&) – medium priority;
OR (|) – lowest priority.
While loop operator
The MatLab programming language has two loop statements: while and for. With their help, for example, programming of recurrent algorithms, calculating the sum of a series, enumerating array elements, and much more is performed.
In the simplest case, a loop in a program is organized using the while statement, which has the following syntax:
while<условие>
<операторы>
end
Here<условие>means a conditional expression like the one used in an if statement, and the while loop runs as long as the condition is true.
Please note that if the condition is false before the loop begins, the statements included in the loop will not be executed even once.
Here's an example of how the while loop works to calculate the sum of a series:
i=1; % amount counter
while i<= 20 % цикл (работает пока i <= 20)
end % end of loop
disp(S); % displaying the amount 210 on the screen
Now let's complicate the problem and calculate the sum of the series, for now. Here, in the loop operator, two conditions are obtained: either the counter for i reaches 20, or the value of the sum S exceeds 20. This logic can be implemented using a compound conditional expression in the while loop operator:
S = 0; % initial value of the amount
i=1; % amount counter
while i<= 20 & S <= 20 % цикл (работает пока i<=10 и S<=20
S=S+i; % the amount is calculated
i=i+1; % increases the counter by 1
end % end of loop
The above example shows the possibility of using compound conditions in a while loop. In general, you can write the same conditions as a conditional expression as in a conditional if statement.
The work of any loop operator, including while, can be forcibly terminated using the break operator. For example, the previous program could be rewritten as follows using a break statement:
S = 0; % initial value of the amount
i=1; % amount counter
while i<= 20 % цикл (работает пока i<=10
S=S+i; % the amount is calculated
i=i+1; % increases the counter by 1
if S > 20% if S > 20,
break; % then the cycle ends
end
end % end of loop
disp(S); % display amount 21 on screen
In this example, the second condition for ending the loop, when S is greater than 20, is written in the loop itself and using the break operator, the loop is exited to the disp() function, located immediately after the while loop.
The second loop execution control operator continue allows you to skip the execution of the program fragment that comes after it. For example, you want to calculate the sum of the elements of an array
a = ;
excluding the element at index 5. Such a program can be written as follows:
S = 0; % initial value of the amount
a = ; % array
i=0; % array index counter
while i< length(a) % цикл (работает пока i меньше
% array length a)
i=i+1; % increases the index counter by 1
if i == 5% if index is 5
continue; % then we don’t count it
end
S=S+a(i); % the sum of the elements is calculated
end % end of loop
disp(S); % displaying the amount 40 on the screen
It should be noted that in this program, the array index i is increased before the condition is checked. This is done so that the index value increases by 1 at each iteration of the loop. If the increase in counter i is written as in the previous examples, i.e. after calculating the sum, then due to the continue operator its value would stop at 5 and the while loop would run “forever”.
The for loop operator
Often, when organizing a loop, you need to iterate through a counter value in a given range of values and with a given change step. For example, to iterate through 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 elements of the vector. To calculate the sum of the series, a counter from a to b is also specified with the required change step step. And so on. Due to the fact that such tasks are often encountered in programming practice, a for loop operator was proposed for their implementation, which makes it easier and more visual to implement a loop with a counter.
The syntax of the for loop operator is as follows:
for<счетчик> = <начальное значение>:<шаг>:<конечное значение>
<операторы цикла>
end
Let's consider the operation of this cycle using the example of implementing an algorithm for searching for the maximum value of an element in a vector:
a = ;
m = a(1); % current maximum value
for i=1:length(a) % loop from 1 to the end of vector c
% 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 steps of 1. Note that if the step size is not explicitly specified, then it is taken by default to be 1.
In the next example, we will consider the implementation of the algorithm for shifting vector elements to the right, i.e. the penultimate element is placed in the place of the last one, the next one in the place of the penultimate one, etc. to the first element:
a = ;
disp(a);
for i=length(a):-1:2 % cycle from 10 to 2 with step -1
a(i)=a(i-1); % shift the elements of vector a
end % end of for loop
disp(a);
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 larger value to a smaller one, you need to explicitly specify the step, in this case, -1. If this is not done, the loop will immediately terminate and the program will not work correctly.
Solutions to the equation
Technical Computing Language
Millions of engineers and scientists around the world use MATLAB ® to analyze and design the systems and products that transform our world. The MATLAB matrix language is the world's most natural way to express computational mathematics. Integrated graphics make data easy to visualize and understand. 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 take your ideas beyond the desktop. You can run studies on large data sets and scale to clusters and clouds. MATLAB code can be integrated with other languages, allowing you to deploy algorithms and applications to 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 pre-processing, visualization and research
Mathematics
Linear algebra, differentiation and integration, Fourier transforms and other mathematics
Graphic arts
2D and 3D graphics, images, animation
Programming
Scripts, functions and classes
Application creation
Develop apps with App Designer, Programmable Workflow, or GUIDE
Software Development Tools
Debugging and testing, organization of large projects, integration with version control system, packaging of toolboxes
Department: Information Technologies
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
……………………
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, operatortry… catch
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: Pn(x) .
Goal of the work:
It is necessary to create a program for calculating the coefficients of an algebraic interpolation polynomial Pn(x)= a 0 + a 1 x+ … + a n x n.
Guidelines:
0 | 1 | 2 | 3 | |
Xi |
1,2 | 1,4 | 1,6 | 1,8 |
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 Pn(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 randomly located nodes x i, i=0, n from the keyboard
ü Calculation of nodes 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 entry ( 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.
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
ü 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 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.
Task No. 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:
It is necessary to create a program for finding the coefficients of the polynomial φ (x)= a 0 + a 1 * x+… a n * x m least squares method.
Let, for example, have the following set of data:
Xi |
1,2 | 1,4 | 1,6 | 1,8 | 2,0 | 2,2 | 2,4 | 2,6 | 2,8 | 3,0 |
8,3893 | 8,6251 | 8,9286 | 8,9703 | 9,1731 | 9,1784 | 8,8424 | 8,7145 | 8,3077 | 7,9611 |
The search for the necessary coefficients is carried out as follows:
Where n - amount of points ( x, y),
m – degree of the required 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 φ(x)=a0+a1*x+… an* x m is constructed, provide:
ü Entering randomly located nodes xi, i=1, n from the keyboard
ü Calculation of nodes xi, i=1, n, corresponding to the uniform location of the argument x on the segment
ü 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
ü Data input (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 the 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.
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 p.: ill.
Often, when organizing a loop, you need to iterate through a counter value in a given range of values and with a given change step. For example, to iterate through 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 elements of the vector. To calculate the sum of the series, a counter from a to b is also specified with the required change step step. And so on. Due to the fact that such tasks are often encountered in programming practice, a for loop operator was proposed for their implementation, which makes it easier and more visual to implement a loop with a counter.
The syntax of the for loop operator is as follows:
for<счетчик> =
<начальное значение>:<шаг>:<конечное значение>
<операторы цикла>
end
Let's consider the operation of this cycle using the example of implementing an algorithm for searching for 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 vector c
% 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 steps of 1. Note that if the step size is not explicitly specified, then it is taken by default to be 1.
In the next example, we will consider the implementation of the algorithm for shifting vector elements to the right, i.e. the penultimate element is placed in the place of the last one, the next one in the place of the penultimate one, etc. to the first element:
function queue
a = ;
disp(a);
for i=length(a):-1:2 % cycle from 10 to 2 with step -1
a(i)=a(i-1); % shift the elements of vector a
end % end of for loop
disp(a);
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 larger value to a smaller one, you need to explicitly specify the step, in this case, -1. If this is not done, the loop will immediately terminate and the program will not work correctly.
In conclusion, let’s look at the operation of the for loop operator using the example of modeling a random sequence with a law of change
where is a 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 coefficient
N = 100; % number of simulated points
ex = 100; % process variance
et = ex*(1-r^2); % variance of random addition
x = zeros(N,1); % initialize vector x
x(1) = sqrt(ex)*randn; % simulation of 1st sample
for i=2:N % cycle from 2 to N
x(i)=r*x(i-1)+sqrt(et)*randn; % SP modeling
end % end of loop
plot(x); % display of SP as a graph
When running this program, the implementation of a simulated random sequence will be shown.
Rice. 2.1. The result of modeling 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 enough to multiply the random variable with unit variance by , because variance is the average square of a random variable relative to the mathematical expectation. As a result, we have the program line
x(1) = sqrt(ex)*randn;
Then, a for loop is implemented with counter i from 2 to N with step 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 simulated sequence on the screen in the form of a graph. Working with displaying graphs on the screen will be discussed in more detail in the next chapter.