Calculating the next element using the previous ones in Matlab. Basics of Computing in MatLab

MATLAB has a very large (huge, this is its main resource) number of built-in functions, so it is important to be able to find reference information on required function.

Get quick help ( help) in the MATLAB command window is done using the commands:

>> help - display information about MATLAB sections (topics) with the ability

hypertext transition to display lists of functions of each section and reference information on the required function.

>> help - display information about the names (titles) of functions included in the section.

>> help<имя функции>- displaying help information on the function.

>> helpwin - displays a help window in which you can double-click to open help information for the desired topic or function.

>>lookfor - displaying reference information for a keyword.

>> help demos - displays a list of demo examples.

>> hthelp - opens an interactive window MATLABhelp.

>> help symbolic – displays information about the symbolic mathematics toolbox (symbolicmathtoolbox) MATLAB.

>> help signal processing toolbox – displays information about the functions of the Signal Processing Toolbox package. The help command is most often used for help.<имя функции>.

Example.

>> help abs

ABS Absolute value.

ABS(X) is the absolute value of the elements of X. When

X is complex, ABS(X) is the complex modulus (magnitude) of

the elements of X.

See also SIGN, ANGLE, UNWRAP.

Overloaded methods

help iddata/abs.m

Most functions have several syntax options. Function names in help messages are shown in uppercase characters, but must be used when entering function names. lowercase characters only. Help for the required function is displayed along with a list of related functions. To obtain more detailed information on the desired function with examples of calculations, use the command doc<имя функции>.

The main means for obtaining detailed help information is the help browser. Helpbrowser, which contains documentation for all installed MATLAB products. Documentation is accessed through the HELP menu. At the initial stage of work, the MATLAB section of the help system is especially useful and necessary to get acquainted with the package.

From the menu Help using the command Demos You can access MATLAB demos. These examples are very varied and useful for learning purposes and creating applications in MATLAB. You can also access demos by using the demo command from the command line.

Access to help information on the Internet: >>webhttp:// www. mathworks. com- loads the WEB site of the company MathWorks Inc. - manufacturer MATLAB.

  1. Simple calculations

MATLAB has the following basic arithmetic operations:

      Addition ( a+b, 15+23),

      Subtraction ( a-b, 17-3),

      Multiplication ( a*b, 0.18*6.12),

      Division ( a/b, 92.4/15),

      Exponentiation ( a^ b, 7.4^4).

Examples

Name Size Bytes Class Attributes

In this example, in addition to the simplest calculations, the command is used whos, which allows you to display a list of variables for the current session, which can also be done in the Workspace window.

To clear the Workspace, i.e. To remove variables from it, you can use the clear command. The clc command is used to clear the Command Window without clearing the work area.

MATLAB also supports mathematical functions general purpose, such as square root sqrt(x), calculation of direct and inverse trigonometric functions, exponential functions, etc. A list of all these functions with the ability to go to any of them can be obtained by entering in the command line help elfun. All elementary MATLAB functions are functions whose arguments can be arrays, i.e. implemented in the package vectorization calculations.

Example

>> v1 = [ 2 4 sqrt(10)]

2.0000 4.0000 3.1623

0.4161 -0.6536 -0.9998

MATLAB evaluates expressions from left to right in the usual order of precedence of exponentiation over multiplication and division, and the latter over addition and subtraction. Parentheses are used to change the order of calculations.

Example

>> 7*3+5-12/4

>> 7*(3+5-12/4)

The relative precision of MATLAB arithmetic operations is about 16 decimal digits in the number range 10 -308 to 10308. The default output format in MATLAB is short, allowing you to display no more than 5 significant digits of a number. This output format is not always sufficient.

Commands for setting output formats

>> format short - short representation in a fixed format (5 characters),

>> format short e– sets the format of scientific (exponential) notation with 5 decimal places,

>> format long – fixed-point long representation format with 15 decimal places,

>> format long e – scientific notation format with 15 decimal places,

>> format bank - monetary output format with two decimal places to the right of the decimal point,

>> format rat - output format in the form of a rational fraction.

The output format can also be set by the menu command Preferences.

Please note that when entering numbers in exponential form, such as 15.8e-5, intervening spaces are not allowed.

MATLAB variable names must begin with a letter, and the maximum name length is 31 characters. The names must not be the same as the names of functions, procedures, or system variables. Names are case sensitive, e.g. var differs from Var.

An assignment operation is used to create a variable.

<имя переменной> = <выражение>;

In this case, the operator “;” suppresses echo output of calculation (assignment) results to the screen.

All declared variables are stored in the workspace ( Workspace) of the current MATLAB session and are available for calculations in this session, except in cases where the variables are specifically removed from the workspace by the command clear.

Examples

Character variable >> string="hello"

Real scalars (numbers)

>> y=5.2*x+15

To save variables in a file in the current directory (work folder by default), you can use the command save

>> save myfile x y

Command without specifying variable names save saves all workspace variables.

Variables can be removed from the workspace ( Workspace)MATLAB command clear

>> clear x y

Undefined function or variable "x".

Undefined function or variable "y".

If necessary, you can load variables from a file into the workspace with the command load

>>load myfile

MATLAB supports easy-to-use built-in complex number arithmetic. In most MATLAB mathematical functions, the arguments and results are assumed to be complex numbers. For example,

>> sqrt(-3)

Variables are reserved to denote the imaginary unit in MATLAB i And j:

3.0000 + 4.0000i

>>y= 2*(1+4*j)

2.0000 + 8.0000i

Special calculation functions with complex argument:

>> abs(x)% getting the modulus of a number

>> angle(x)% argument (phase) of the number in radians

>> conj(x)% complex conjugate

>> imag(x)% imaginary part of a number

>> real(x)% real part of a number

MATLAB predefined system variable names cannot be used as user variable names. The main ones of these names:

>> ans is the default variable name for the calculation result.

>> eps is a machine precision variable of order 10 -16 .

>> exit exit (end) of MATLAB.

>> i or j is an imaginary unit, i.e. .

>> pi is the number π.

>> Inf designation for infinity.

>> NaN is not a numeric result.

>> clear command to remove all variables from the workspace, this command should be used with great care.

>> clear x,y command removes the x and y variables.

>> what outputs a list of files with extensions '.m', '.mat', '.mex' from the current directory.

>> who displays the variables of the current workspace.

>> whos displays information about the current variables.

>> dir lists the files in the current directory.

>> save saves all current variables in the MATLAB.mat file in the current directory.

>> load loads variables from MATLAB.mat into the current session.

>> diary saves the text (commands) and calculation results of the current session (session diary) in a file called diary.

>> diary filename saves the current session in a file named filename.

>> diary off pauses writing to the file.

>> diary on enables recording of the session to a file.

The interpretive programming language of the MATLAB system is created in such a way that any (sometimes very complex) calculations can be performed in the direct calculation mode, that is, without the user preparing a program. In this case, MATLAB performs the functions of a supercalculator and works in command line mode.

Working with the system is interactive in nature and follows the rule “ask a question and receive an answer.” The user types a calculated expression on the keyboard, edits it (if necessary) in command line and completes the entry by pressing the ENTER key. As an example, the figure shows the simplest and quite obvious calculations.

Even from such simple examples Some instructive conclusions can be drawn:

* to indicate the input of initial data, the >> symbol is used;

* data is entered using a simple line editor;

* to block the output of the calculation result of a certain expression, you need to set a sign after it; (semicolon);

* if a variable is not specified for the value of the calculation result, then MATLAB assigns such a variable named ans;

* the assignment sign is the equal sign =, familiar to mathematicians, and not the combined sign:=, as in many other programming languages ​​and mathematical systems;

* built-in functions (eg sin) are written lowercase letters, and their arguments are indicated in parentheses;

* the result of calculations is displayed in output lines (without the >> sign);

* the dialogue takes place in the style of “asked a question - received an answer.”

The following examples illustrate the use of MATLAB to perform a number of other simple vector operations. The figure also shows the browser window file system, which is available on the Current Directory tab. In command mode, it is more convenient to call the file system browser window from the toolbar by activating the button after the list of MATLAB system directories. There may be cases where calculations are abandoned if the current directory is incorrectly set, if the m-files needed for calculations are not detected.

In most mathematical systems, calculating sin(V) or exp(V), where V is a vector, would produce an error because the functions sin and exp must have a scalar argument. However, MATLAB is a matrix system, and a vector is a type of matrix with size 1×n or n×1. Therefore, in our case, the result of the calculation will be a vector of the same size as the argument V, but the elements of the returned vector will be the sines or exponents of the elements of the vector V.

A matrix is ​​specified as a series of vectors representing its rows, enclosed in square brackets. A space or comma is used to separate elements of vectors, and a semicolon is used to separate one vector from another. To select an individual element of the matrix M, an expression of the form M(j,i) is used, where M is the name of the matrix, j is the row number and i is the column number.

To view the contents of arrays, it is convenient to use the Workspace browser. Each vector and matrix in it are represented as a square with cells, to the right of which the size of the array is indicated. Double click clicking on the square with the mouse leads to the appearance of the Array Editor window. Working with the array editor is quite obvious - you can not only view array elements, but also edit and replace them.

As can be seen from the given examples, input of initial expressions for calculations in the MATLAB system is carried out in the most common text format. The results of calculations, with the exception of graphic ones, are displayed in the same format. Here are examples of recording calculations performed by MATLAB on the command line:

Working with the array editor

To get started, select "MATLAB Help" from the Help menu.

>> type sin

sin is a built-in function.

>> help sin

SIN(X) is the sine of the elements of X.

Overloaded methods

>>V=

0.8415 0.9093 0.1411 -0.7568

Error using ==> ^

Matrix must be square.

You can pay attention to the form of the responses when performing simple operations without specifying the variable to which the result is assigned. In such cases, MATLAB itself assigns a variable, ans, to which the result is assigned and the value of which is then displayed.

Output form and line breaks in the session

It should be noted the features of output in the MATLAB system. The output starts on a new line, with numeric data being indented and text data being indented. To save space in this book, future output will be given without a new line. For example, outputting a row vector

will be given in the form:

The exception is the output of column vectors and matrices - here the more visual and default output form of MATLAB will be preserved.

In some cases, the mathematical expression you enter may be so long that one line is not enough for it. Then part of the expression can be moved to a new line using the ellipsis "..." (3 or more dots), for example:

s = 1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 + 1/7 ...

1/8 + 1/9 - 1/10 + 1/11 - 1/12;

The maximum number of characters in one line of command mode is 4096, and in an m-file it is not limited, but with such long lines It's inconvenient to work. In earlier versions, one line had a maximum of 256 characters.

Running MATLAB Examples from the Command Line

MATLAB has many application examples, some of which can be run directly from the command line. For example, the command

runs the m-file bench.m of the system testing demo.

with boundary conditions y(t 0 , t end, p) = y, Where t end, t 0 initial and endpoints intervals. Parameter t(independent variable) does not necessarily mean time, although most often the solution to the DE is sought in the time domain. The DE system in Cauchy form is written similarly to (1.1), but under y in this case, a column vector of dependent variables is implied. Vector p sets the initial conditions.

To solve second and higher order DEs, they need to be reduced to a first order DE system.

There are possible differential equations that are not allowed with respect to the derivative:

F(t, y, dy/dt) = 0. (1.2)

Equations (1.2) usually cannot be reduced analytically to form (1.1). However, the numerical solution does not cause any particular difficulties to determine f(y, t) solve (1.2) numerically with respect to the derivative for given y And t.

ODE solvers

Various numerical methods are implemented in MATLAB to solve ODE systems. Their implementations are named solvers ODU.

In this section, the generic name solver means one of the possible numerical methods for solving an ODE: ode45, ode23, ode113, ode15s, ode23s, ode23t, ode23tb, bvp4c or pdepe.

Solvers implement the following methods for solving DE systems:

Ode45 one-step explicit Runge-Kutta methods of 4th and 5th orders modified by Dormand and Prince. This is the classic method recommended for initially trying out a solution. In many cases it gives good results, if the system of equations being solved is not rigid.

Ode23 one-step explicit Runge-Kutta methods of 2nd and 4th orders as modified by Bogacki and Champin. With moderate rigidity of the ODE system and low accuracy requirements, this method can provide a gain in solution speed.

Ode113 multi-step Adams-Bashworth-Moulton method of variable order predictor-corrector class. This is an adaptive method that can provide highly accurate solutions.

Ode15s is a multi-step variable order method (from 1 to 5, default 5) using numerical "backward differentiation" formulas. This is an adaptive method and should be used if the ode45 solver does not provide a solution and the remote control system is rigid.

Ode23s is a one-step method using a modified 2nd order Rosenbrock formula. Can provide high speed of calculations with low accuracy of solving a rigid remote control system.

Ode23t implicit trapezoid method with interpolation. This method gives good results when solving problems that describe oscillatory systems with an almost harmonic output signal. For moderately rigid systems, the DE can provide a highly accurate solution.

Ode23tb implicit Runge Kutta method at the beginning of the solution and a method using 2nd order backward differentiation formulas subsequently. Despite the relatively low accuracy, this method may be more effective than ode15s.

Bvp4c serves for the boundary value problem of remote control systems of the form y′ = f(t, y), F(y(a), y(b), p) = 0 (full form of the system of Cauchy equations). The problems it solves are called two-point boundary value problems, since the solution is sought by specifying boundary conditions both at the beginning and at the end of the solution interval.

All solvers can solve systems of explicit equations y′ = F(t, y), and to solve rigid systems of equations it is recommended to use only special solvers ode15s, ode23s, ode23t, ode23tb.

Using ODE Solvers

tspan vector defining the integration interval [ t 0 t final]. To obtain solutions at specific points in time t 0 , t 1 , …, t final(arranged in order of decreasing or increasing) must be used tspan = [t 0 t 1 … t final];

y 0 vector of initial conditions;

Options argument produced by the odeset function (another odeget or bvpget (bvp4c only) function allows you to print the options set by default or by the odeset/bvpset function);

p 1, p 2,… arbitrary parameters, passed to the function F;

T, Y decision matrix Y, where each row corresponds to the time returned in the column vector T.

Let's move on to a description of the syntax of functions for solving remote control systems (the name solver means any of the functions presented above).

[T,Y]=solver(@ F,tspan,y 0) integrates a remote control system of the form y′ = F(t, y) on the interval tspan with initial conditions y 0 . @F descriptor of an ODE function (you can also specify a function in the form " F"). Each row in the solutions array Y corresponds to the time value returned in the column vector T.

[T,Y]=solver(@ F,tspan,y 0 ,options) gives a solution similar to the one described above, but with options determined by the values ​​of the options argument created by the odeset function. Commonly used parameters include relative error tolerance RelTol (default 1e3) and vector acceptable values absolute error AbsTol (all components default to 1e6).

[T,Y]=solver(@ F,tspan,y 0 ,options p 1 ,p 2...) gives a solution similar to the one described above, passing Extra options p 1 , p 2 , ... in m-file F whenever it is called. Use options= if no options are specified.

Solution of first order ODE

PROCEDURE FOR PERFORMANCE OF THE WORK

· title page;

· initial data of the option;

· the solution of the problem;

· results of solving the problem.

Example

Find a solution to the differential equation on the segment for which at(1,7) = 5,3.

Create a user function in the Command Window

g=@(x,y);

In the function syntax @(x,y) x independent variable y dependent variable x-cos( y/pi) right side of the remote control.

The solution process is carried out by accessing the solver (solver) in the Command Window using the following operator:

Ode23(g,,);

The construction of a graph with a grid is carried out by the following operators:

The result is shown in Fig. 1.1

Rice. 1.2.1. Visualization of the numerical solution

EXERCISE

1. Find solutions to first-order differential equations , satisfying the initial conditions y(x 0 ) = y 0 on the interval [ a,b].

2. Construct graphs of the function.

Task options.

Option No. y(x 0 )=y 0 [a,b]
y 0 (1,8)=2,6
y 0 (0,6)=0,8
y 0 (2,1)=2,5
y 0 (0,5)=0,6
y 0 (1,4)=2,2
y 0 (1,7)=5,3
y 0 (1,4)=2,5
y 0 (1,6)=4,6
y 0 (1,8)=2,6
y 0 (1,7)=5,3
y 0 (0,4)=0,8
y 0 (1,2)=1,4

Laboratory work No. 2

Solving ODE systems

GOAL OF THE WORK

To form students’ ideas about the use of remote control systems in various fields; instill the ability to solve the Cauchy problem for remote control systems.

PROCEDURE FOR PERFORMANCE OF THE WORK

1. Study the theoretical part. Complete the tasks corresponding to the number of your option and demonstrate them to the teacher.

2. Complete a laboratory report, which should contain:

· title page;

· initial data of the option;

· the solution of the problem;

· results of solving the problem.

Example

Solve the system

using the ode23() solver.

Solution:

1. Create an m-file of a function for calculating the right-hand sides of a remote control in the editor.

Let the name in the file editor be sisdu.m, then the function can look like this:

function z=sisdu(t,y)

z1=-3*y(2)+cos(t)-exp(t);

z2=4*y(2)-cos(t)+2*exp(t);

>> t0=0;tf=5;y0=[-3/17,4/17];

>> =ode23("sisdu",,y0);

>>plot(t,y)

Rice. 1.3.1. Visualization of the numerical solution obtained using the ode23 function.

1. What does it mean to solve the Cauchy problem for a remote control system?

2. What methods exist for solving remote control systems?

EXERCISE

1. Find the solution to the remote control system

satisfying the initial conditions on the interval ;

2. Construct function graphs.

For example, the solution function for the 8th option is given:

function z=ssisdu(t,y)

% option 8

z1=-a*y(1)+a*y(2);

z2=a*y(1)-(a-m)*y(2)+2*m*y(3);

z3=a*y(2)-(a-m)*y(3)+3*m*y(4);

z4=a*y(3)-3*m*y(4);

>> =ode23("ssisdu",,);

>> plot(t,100*y)

Rice. 1.3.2. Visualization of the numerical solution obtained using the ode23 function.

Task options.

Option No. Tasks
a m
0,1 1,2
0,2 1,5
0,3 1,7
0,4 1,9
0,5
0,6 1,9
0,7 2,3
0,8 2,7
0,9
0,1 1,5
0,2 1,1
0,3

Laboratory work No. 3

1.4 ODE solution n-th order

GOAL OF THE WORK

To form students’ ideas about the application of higher order remote control in various fields; instill the ability to solve the Cauchy problem for higher-order differential equations using application programs; develop skills in checking the results obtained.

PROCEDURE FOR PERFORMANCE OF THE WORK

1. Study the theoretical part. Complete the tasks corresponding to the number of your option and demonstrate them to the teacher.

2. Complete a laboratory report, which should contain:

· title page;

· initial data of the option;

· the solution of the problem;

· results of solving the problem.

Example 1.

Solve second order differential equations given initial conditions .

Solution:

First we bring the remote control to the system:

1. Create an m-file of the function for calculating the right sides of the remote control.

Let the file name be sisdu_3.m, then the function can look like this:

function z=sisdu_3(x,y)

z2=6*x*exp(x)+2*y(2)+y(1);

2. Perform the following steps:

>> x0=0;xf=10;y0=;

>> =ode23("sisdu_3",,y0);

>> plot(x,y(:,1))

Rice. 1.4.1. Visualization of the numerical solution obtained using the ode23 function.

SAMPLE QUESTIONS FOR JOB DEFENSE

1. What does it mean to solve the Cauchy problem for higher-order differential equations?

2. How to bring the remote control m-th order to the remote control system?

EXERCISE

1. Find a solution to the differential equation that satisfies the initial conditions on the interval.

2. Construct function graphs.

Task options.

Option No. Tasks
Equations Initial conditions







Laboratory work No. 4 – 5

Dynamic systems (DS)

GOAL OF THE WORK

Introducing students to the basic concepts of DS, their classification, phase space of DS, kinematic interpretation of the DS system, evolution of DS. Equation of motion of a pendulum. Dynamics of the Van der Pol oscillator.

2. Dynamic system (DS) a mathematical object corresponding to real systems (physical, chemical, biological, etc.), the evolution of which is uniquely determined by the initial state. The DS is determined by a system of equations (differential, difference, integral, etc.) that allow the existence of a unique solution for each initial condition over an infinite time interval.

The state of the DS is described by a set of variables chosen for reasons of naturalness of their interpretation, simplicity of description, symmetry, etc. The set of states of the DS forms a phase space, each state corresponds to a point in it, and the evolution is depicted by (phase) trajectories. To determine the proximity of states, the concept of distance is introduced in the DS phase space. A set of states at a fixed moment in time is characterized by a phase volume.

The description of DS in the sense of specifying the law of evolution also allows for great variety: it is carried out using differential equations, discrete mappings, using graph theory, the theory of Markov chains, etc. The choice of one of the description methods specifies the specific type of mathematical model of the corresponding DS.

Mathematical model of DS is considered given if dynamic variables (coordinates) of the system are introduced that uniquely determine its state, and the law of evolution of the state over time is indicated.

Depending on the degree of approximation, different mathematical models can be assigned to the same system. The study of real systems follows the path of studying the corresponding mathematical models, the improvement and development of which is determined by the analysis of experimental and theoretical results and their comparison. In this regard, by a dynamic system we will understand precisely this mathematical model. By studying the same dynamic system (for example, the movement of a pendulum), depending on the degree to which various factors are taken into account, we will obtain different mathematical models.

1. You can start the program using the icon on the desktop or through the Start button (in the lower left corner of the screen). The MatLab working environment will open.

2. Click in the Command Window field to make it active.

Type 1+2 in the line with the " icon and the blinking vertical cursor and press Enter. As a result, the MatLab command window displays the following:

The result of calculating the sum 1+2 is written to a special variable ans and its value, equal to 3, is displayed in the command window. Below the response is a command line with a blinking cursor, indicating that MatLab is ready for further calculations. You can type new expressions on the command line and find their meanings.

3. To continue working with the previous expression, for example, to calculate (1+2)/4.5, it is advisable to use the existing result, which is stored in the ans variable.

Type ans/4.5 (a dot is used when entering decimals) and press Enter, you get:

4.The entry “ans = 0.6667” is called an echo.

The execution of each command in MatLab is accompanied by a similar echo, which often makes it difficult to perceive the program's operation.

To disable echo, follow the command with a symbol; (semicolon). For example:

Here the result of multiplying the variable ans by 3, which is intermediate, is not printed on the screen. Only the final answer is shown.

5.Save the variable values. For this:

— select Save Workspace As from the File menu;

— in the Save Workspace Variables dialog box that appears, specify the directory and file name (by default, it is proposed to save the file in the work subdirectory of the main MatLab directory). The results of the work will be saved in a file with the extension mat.

6. Close MatLab.

7.Start MatLab again. To restore the values ​​of variables from a previous work session, open the saved file using the Open sub-item of the File menu. Saved variables can be used in newly entered commands.

8.Record the executed commands and results in text file, which can then be read or printed from text editor. For this:

— enter the diary command;

— specify the name of the file in which the work log will be stored as an argument to the diary command.

An example is given in paragraph 1.3.

9. To exit the MatLab system, enter the quit command.

1. Study the theoretical part.

2. Get a variant of the task.

3. Follow the example given in paragraph 2.

4. Perform calculations according to your option.

5. Complete the report in in electronic format.

6. Defend your laboratory work by answering the teacher’s questions.

Options

Articles to read:

Basics of working with Mathcad. Simple calculations. Lesson 4