Conditional if statement

In the very simple case syntax given operator if looks like:

if<выражение>
<операторы>
end

I draw your attention to the fact that, in contrast to modern languages programming does not use such a thing as a compound statement. The conditional statement block must end official word end.

The following 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

The analysis of the given 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 construct

if<выражение>
<операторы1>% executed if condition is true
else
<операторы2>% executed if 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 if the variable x is positive, and if it is, then the value 1 is displayed on the screen, and all other conditions are ignored. If the first condition turned out to be false, then the execution of the program goes on 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 0 is output.

The above example can be written in a simpler form using another MatLab if statement construct:

if<выражение1>
<операторы1>% executed if expression1 is true
elseif<выражение2>
<операторы2>% executed if expression2 is true
...
elseif<выражениеN>
<операторыN>% 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

With the if statement, you can test for 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 done 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. Let it be required to check whether the 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 if the variable x does not belong to the range from 0 to 2. This is achieved by triggering one of the two conditions: x< 0 или x > 2:

x = 1;
if x< 0 | x > 2
disp("x is not in the range 0 to 2");
else
disp("x is in the range 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 the variable x is in the range -5 to 5, but not in the range 0 to 1. Obviously, this can be implemented as follows:

x = 1;
if (x >= -5 & x<= 5) & (x < 0 | x > 1)
disp("x belongs to [-5, 5] but is not in ");
else
disp("x is either not in [-5, 5] or in ");
end

Note that parentheses have been 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, then the condition would look like this: (x >= -5 and x<= 5 и x < 0) или x >1. Obviously, such a check would give a different result than expected.

Parentheses in programming are used to change the execution precedence of statements. Like arithmetic operators, logical ones can also be changed at the request of the programmer. Thanks to the use of parentheses, the check is performed first inside them, and then outside them. That is why, in the example above, they are necessary to achieve the desired result.

A priority logical operations next:

NOT (~) - the highest priority;
And (&) - medium priority;
OR (|) is the lowest priority.

while loop statement

The MatLab programming language has two loop statements: while and for. With their help, for example, programming of recurrent algorithms, calculation of the sum of a series, enumeration of array elements, and much more is performed.

In the simplest case, the loop in the program is organized using the while statement, which has the following syntax:

while<условие>
<операторы>
end

Here<условие>means a conditional expression like that used in an if statement, and the while loop runs as long as the condition is true.

Note that if the condition is false before the loop starts, then the statements in the loop will never be executed.

Here is an example of the while loop for calculating the sum of a series:


i=1; % total counter
while i<= 20 % цикл (работает пока i <= 20)

end % end of loop
disp(S); % display sum 210 on screen

Now we will complicate the task and we will calculate the sum of the series , while . Here, two conditions are obtained in the loop statement: 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 statement:

S = 0; % initial sum value
i=1; % total counter
while i<= 20 & S <= 20 % цикл (работает пока i<=10 и S<=20
S=S+i; % counted amount
i=i+1; % increment counter by 1
end % end of loop

The above example shows the possibility of using compound conditions in a while loop. In general, as a conditional expression, you can write the same conditions as in the conditional if statement.

The work of any loop operator, including while, can be forcibly terminated using the break statement. For example, the previous program could be rewritten as follows using the break statement:

S = 0; % initial sum value
i=1; % total counter
while i<= 20 % цикл (работает пока i<=10
S=S+i; % counted amount
i=i+1; % increment counter by 1
if S > 20% if S > 20,
break; % then the loop ends
end
end % end of loop
disp(S); % display the sum of 21 on the screen

In this example, the second condition for terminating the loop, when S is greater than 20, is written in the loop itself, and using the break statement, the loop is exited to the disp() function immediately after the while loop.

The second loop execution control operator continue allows you to skip the execution of the program fragment 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 sum value
a = ; % array
i=0; % array index count
while i< length(a) % цикл (работает пока i меньше
% array length a)
i=i+1; % increments index counter by 1
if i == 5% if index is 5
continue; % then we do not calculate it
end
S=S+a(i); % sum of items counted
end % end of loop
disp(S); % display sum 40 on screen

It should be noted that in this program the index of the array i is incremented before the condition is checked. This is done so that the index value increases by 1 on each iteration of the loop. If the increment of the counter i is written as in the previous examples, i.e. after the sum has been calculated, the continue statement would cause its value to stop at 5 and the while loop would run "forever".

for loop statement

Often, when organizing a loop, it is required to iterate over the counter value in a given range of values ​​and with a given change step. 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 elements of the vector. To calculate the sum of the series, a counter from a to b is also specified with the required step change step. And so on. Due to the fact that such tasks are often encountered in programming practice, a separate 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 statement is as follows:

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

Let's consider the work of this cycle on the example of the implementation of the algorithm for finding 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 end of vector c
% step 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 counter i and changes its value from 1 to 10 in increments of 1. Note that if the increment is not explicitly specified, then it defaults to 1.

In the following example, consider the implementation of the algorithm for shifting vector elements to the right, i.e. the penultimate element is put in place of the last one, the next one is put in place of the penultimate one, and so on. to the first element:

a = ;
disp(a);
for i=length(a):-1:2 % loop from 10 to 2 with step -1
a(i)=a(i-1); % shift elements of 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 cycle with a counter from a larger value to a smaller one, you must explicitly specify the step, in this case, -1. If this is not done, the loop will immediately terminate its work and the program will not work correctly.

Equation solutions

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

while looping condition of MATLAB command

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 write a condition in the form,

understood by MATLAB, use the ">" (greater than) sign. The text of the file-function mysin, which calculates the sum of the series based on the recurrence relation

k 2k(2k + \) k 1

shown in listing 7.7.

Note ^

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

Listing 7.7. File function mysin, which calculates the sine by series expansion

function s - mysin(x)

"% Calculation of the sine by series expansion

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

Ї calculation of the first term of the sum for k \u003d O k \u003d 0; them;

% calculation of auxiliary variable x2 - x*x;

while abs(u) > 1.Oe-IO k = k + 1; u \u003d -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 the loop before 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 set from the command line): "fplot (@rnysin, [-pi, pi])" hold on

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

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

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

The condition of a while loop can contain a logical expression composed of relational operators and logical operators or operators. To set the condition for repeating the cycle, the operations of the relation given in Table. 7.1.

Table 7.1. relation operations

Notation Operation relation
== Equality
< Меньше
<= Меньше или равно
>= Greater than or equal
Not equal

More complex conditions are specified 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 operation "and" - &

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

The main 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)
Negating "not" a * 1.9 not (a == 1.9) - (a == 1.9)

^ 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 the series diverges due to the fact that 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 loop. Perform summation by limiting the number of terms. Add a limit to the number of terms in the while loop condition of the mysin function file (see Listing 7.6):

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

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

^ Note ^

To specify the order in which logical operations are performed, parentheses should be used (for more information about logical operators and logical operations and the possibility of applying them to arrays, see

sec. "Logical expressions with arrays and numbers" of this chapter).

When programming algorithms, in addition to organizing repetitive 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 the branching algorithm.

Branch operators

The if conditional statement and the switch statement allow you to create a flexible branching algorithm in which, when certain conditions are met, the 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 met, or in an if-eiseif-eise construct to write branching algorithms.362

Part II. Computing and programming

Input Argument Validation

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

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

Consider the operators m-files for details.

assignment operator. The main operator of the programming system matlab is assignment operator, which has the following structure:

VariableName= expression

The operator is designed to identify variables and is denoted by the symbol = , to the left of which is the variable name, 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. Assignment Statement Examples

All variables used on the right side of an assignment statement must be predefined. If the command line ends with a semicolon ( ; ), then the result of the statement is not displayed, otherwise it is displayed on 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 in Matlab can be done both 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 named a. In the example below, into a variable a a numerical value is entered first, and then a numerical expression (Fig. 1.3.4-2).

Rice. 1.3.4-3. Evaluation of an expression given in symbolic form

Conditional statement if... end. Conditional operator if in 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 - truncated fork [x] has the following form:

ifBooleanExpression

Instructions

Recall that if BooleanExpression returns a boolean 1 (i.e. "True") are executed Instructions, constituting the body of the structure if...end. At the same time, the operator end indicates the end of the list of instructions. The instructions in the list are separated by a comma or semicolon. If a BooleanExpression not executed (gives boolean value 0 , "False"), then Instructions are also not implemented.

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 can be seen that the operator if It can be either in one line or in several lines.

Consider a more complex example - nested branch. Consider an example

moreover, in order to fully reflect the structure of a complex branching, without caring about the transfer of long command lines, we use m-function (Fig. 1.3.4-7). Let's select the 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 a nested branch

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

switchExpression

caseReading_1

List_instructions_1

casevalue_2

List_instructions_2

caseValue_N

Instruction_List_N

otherwise

List_of_instructions_N+1

If the expression after the header switch has the value of one of the expressions Meaning..., then the statement block is executed case, otherwise - the list of instructions after the operator otherwise. When executing a block case those lists of instructions are executed for which Meaning coincides with Expression. Please note that Meaning can be a number, a constant, a variable, a vector of cells, or even a string variable. Let's explain the use of the enumeration 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 multifunction()

Function multifunc(x,n) two parameters, with the second playing 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 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 vag = s:d:e

Instruction1

InstructionN

where s- the initial value of the loop variable var, d- increment this variable and e - final value of the control variable, above which 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 the loop ends with the statement end.

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

Rice. 1.3.4-11. Function call summa() and built-in function sum()

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

In addition to simple regular loops in Matlab, it is possible 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 shown in fig. 1.3.4-13.

Rice. 1.3.4-13. Appeal to script-file named 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 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. Dialog program using operator while...end

This program, stored in m-file named primer11, is used to repeatedly calculate the circumference of a user-entered value of the radius r, where the dialog 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 is repeated. But it's worth asking r<0 , the calculation of the circumference stops and the loop terminates. Since in the second line of the program the value r is set to 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 transfers control to the next iteration of the loop, skipping the statements that follow it, and in a 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. Interrupting a program using a statement continue

Examples of solving problems using

M-files

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

To solve the 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 called 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 ​​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 functions fb() and calculating the sum.

The calculations are made by running script-file by typing in the window command line command window his name zadasha. The results of its implementation 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.

On fig. 1.3.5-4 is given script-file named zadasha2, where the matrix is ​​introduced, a, consisting of three rows and four columns. A loop is organized by the number of formed array elements 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 string ( m). Displaying array elements b provided in the column.

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

As a result of the launch script-file named zadasha2 out the window command window a column of array elements is displayed b

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

Rice. 1.3.5-9. Function launch sumf() for execution


Laboratory work on the topic

"Means of algorithmization and programming

In matlab"

Issues to be studied

1) Views m- files.

2) Creating and saving new, and opening 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) Calls 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) Explore Topics 1.3 (p.p. 1.3.1 – 1.3.5).

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

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

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

5) Create newscript -file where you enter the program code that describes the logic for solving the task.

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

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

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

9) Execute the script -file from window command linecommand window .

10) Save the text working window on external media.

11) Submit your results teacher work, answer to the questions posed.

12) Complete command clear all for the cleaning working environment .

13) Submit a report according to the work performed .


Variants of individual tasks

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 vertex of the polyline. Construct a polyline, while 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 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 positives and calculate their sum
Enter a natural number n and a vector of real numbers . Determine whether 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. Display its elements in a row and column
Form 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 a natural number n and a vector of real numbers . Find the number of two neighboring positive numbers and two neighboring numbers of different 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
Enter a vector of integers . Transform it in such a way that zeros are placed first, then all other elements. Determine the sum and number of elements whose values ​​are a multiple of 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 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 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. 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 obtain from it the vector C(4), whose elements are: · the largest of the elements in the first row; the smallest of the elements in the second row; the arithmetic mean of the elements of the third row; the sum of the elements of the fourth row
Enter a natural number n and a matrix of real numbers С(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 elements of k1 and k2 rows in the matrix
Enter a natural number n and a matrix of real numbers С(n,9). Find the arithmetic mean of each of the columns that have even numbers
Enter vectors of real numbers x(5), y(6), z(7). Calculate the value of t according to the following algorithm:
Enter vectors of real numbers x(5). Get for x=1, 3, 4 values where
Enter vectors of real numbers x(10). Get another array p(10) from it, the elements of which are sorted 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 - by ones, with the minimum - by twos, and set the remaining elements of the matrix equal to zero
Form a matrix A(4,4) according to the rule Delete 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 to the corresponding element of the vector C. Output the resulting vector C
Enter a matrix of real numbers A(3,4), all elements of which are different. In each row, you should choose the largest and smallest values, and write the sum of the indices of the columns in which they are located in the corresponding element of the vector С(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 the lab

Name of the student, group number

Option number

・Individual task

2) Protocol of calculations (sessions) in the window command window 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- the file is 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) Call to m- functions.

7) Operator format input().

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

9) Multiple branch operator format switch.

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

11) Appointment of operators continue and break.

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


Section 2. Solution Technology
computing tasks using MatLab

Loops in matlab require a condition that a command or group of commands must
repeat several times.

The easiest way to create a loop is to use
for expression. Below is a simple example where 10 is calculated and displayed! = 10 * 9 * 8 ... * 2 * 1.

f = 1;
for n=2:10
f = f*n;
end

f=
3628800

A loop in matlab starts with a for statement and ends with an end statement. Team
between these expressions is executed nine times in total, once for each
values ​​n from 2 to 10. To interrupt intermediate output inside the loop, we
used a semicolon. To see the end result, you need
enter f after the loop ends. If you do not use a semicolon, the program
MATLAB will display every intermediate value 2!, 3!, etc.

In the Editor module, the for and end commands are automatically highlighted
in blue. This gives better readability if you paste between
them commands (how we did it); the Editor module does this
automatically. If you type for in the Command Window,
MATLAB will not issue a new >> command line prompt until you
enter the end command, which will cause the MATLAB program to complete a full loop and
will display a new command line.

  • If you use a loop in an M-file script with echo on display effect, then the commands will be echoed each time throughout the loop. You can prevent this by inserting an echo off command right before the end statement and an echo on command right after it; then each command in the loop will be reflected once (except end).

Note: there are three types of loops in matlab which are given below

1. The for loop in Matlab

a=0;
for i=1:10
a=a+1;
end

2. The while loop in Matlab

a=0;
while a<10
a=a+1;
end

3. The if loop in Matlab

a=10;
if a==10
"first case"
else
"second case"
end

ans =
first case

Therefore, from the above, we can conclude that you need to look at a lot of additional information and alternatives!


Department: Information Technology

PROGRAMMING INMATLAB


OperatorsMATLAB

· Loop statements

Cyclefor

Syntax

count=start:step:final

MATLAB commands

Description

count is a loop variable,

start is its initial value,

final is its final value,

step - the step by which count is incremented each time it enters the loop

the loop ends as soon as the value of 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) \u003d e-ax sin x,

for parameter values ​​a from -0.1 to 0.1. Below is a listing of a file program 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 graphical 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 (true) condition of the loop is true. The following relational operations are allowed to set the condition for the execution of a cycle:

More complex conditions are specified 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 placed between if and end are executed, and if the condition is not true, then the transition occurs to the commands located after the end.

Example

Conditional operatorelseif

Syntax

if condition1

elseif condition2

………………………

elseif condition

Description

Depending on the fulfillment of one or another 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

……………………

casevaluen


Each branch is defined by a case statement, the transition to it is performed when the switch statement variable 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 exits, while the values ​​specified in other cases are no longer checked. If there are no suitable values ​​for the variable, then the branch of the program corresponding to otherwise is executed.

Example

Loop interrupts. Exceptional situations.

Operatorbreak

Syntax

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

if condition

the break statement ends the loop (for or while) and the statements that are located on the lines following the end are executed. For nested loops, break exits the inner loop.

Exception Handling, Operatortrycatch

Syntax

statements 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 displays the text or value of a variable in 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- Removes work environment variables.

Withlc- clears the command window

For more information about these and other functions, run on the command line

helpfunction_name

Assignments for laboratory work

The number of a particular task option is determined by the teacher.

Task number 1

This task implies finding an algebraic interpolation polynomial of degree n for some set of data: P n(x) .

Objective:

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

Methodical instructions:

Let, for example, we 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 the solution of the system of equations:

Here nis the order of the interpolation polynomial,

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

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

Program Requirements

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

· Ask n is the number of interpolation segments (or, equivalently, 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), on which the interpolation polynomial is constructed P(x)n1=n+1) provide:

Entering Randomly Arranged 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 pp. 1.2 values y i , i=0, n either entered from the keyboard (if the original function is unknown), or calculated from a given function f(x). The expression that defines the 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 a system of equations to determine the coefficients of the polynomial P(x)

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

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

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

Task number 2

Spline interpolation

Objective:

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

,

S function 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 built

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

Entering arbitrary 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

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

Entering data (xi, yi, i=0, n) from a 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

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

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

Note:

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