Calculating the next element using the previous ones in Matlab. The simplest calculations in matlab. Computations and data approximation 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 the desired 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 - displaying information about the names (names) 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 general purpose math functions 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 are:

>> 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 operation.

>> 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 stores 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.

1.Command Window(Command window).

Mathematical expressions are written on the command line after the " >> " prompt. For example,

To perform the action, press the “Enter” key.

By default, the program writes the result to the special variable ans.

To save the result under a different name, use the variable name and the assignment sign “=”, for example

>> z = 1.25 /3.11

Edit in Command Window You can only use the current command line. In order to edit a previously entered command, you need to place the cursor in the input line and use the “ ” or “ ” keys.

If a command ends with “;”, then the result of its action is not displayed on the command line.

The command window can be closed with the “ ” button, and the “ ” button serves to separate the window from the system interface. You can return to the standard window form using the menu:

Main menuDesktopDesktop LayoutDefault.

You can clear the command window using the menu:

Main menuEditClear Command Window.

Main menu of the MatLab system.

Main menu MatLab contains the following items:

File(File) – work with files;

Edit(Edit) – editing;

View(View) – window management;

Web– communication with the developer company via the Internet;

Window(Window) – connection with system windows;

Help(Help) – link to the help system MatLab.

MATLAB system toolbar.

The toolbar buttons have the following purposes:

New file(New) – displays file editor windows;

Open file(Open) – opens file download windows;

Cut(Cut) – cuts the selected fragment and places it on the clipboard;

Copy(Copy) – copies the selected fragment to the clipboard;

Paste(Paste) – transfers the selected fragment from the clipboard to the input line;

Undo(Cancel) – cancels the result of the previous operation;

Redo(Repeat) – repeats the result of the previous operation;

Simulink– creates a Simulink model (extensions MatLab);

Help Window(Help) – opens help windows.

4. Output format of calculation results .



When entering real numbers, a dot is used to separate the fractional part!

>> s = 0.3467819

The calculation result is displayed in the format short(short notation for a number), which is defined by default. You can change the format to long(long number notation).

>> format long

0.34678190000000

On the list Numerical Format number formats available

short– a short notation of the number;

long– long number notation;

short e– short notation of a number in floating point format;

long e– long record of a number in floating point format;

short g– the second form of a short notation of a number;

long g– the second form of the long notation of a number;

The format for displaying numeric data can be set in the menu File(file) item Preferences(preferences). Go to tab Command Window(command window). In option Text display(text display), in list Numeric format(numeric format) set short g, in option Numeric display(display numbers) set compact. These output formats output numbers in a universal form of five significant digits and suppress white space between lines.

Basics of calculations in MatLab.

To perform simple arithmetic operations in MatLab operators are used:

· addition and subtraction +, – ;

· multiplication and division *, / ;

· exponentiation ^ .

Some special variables:

ans – the result of the last operation without an assignment sign;

eps – relative error in floating point calculations;

pi – number;

i or j – imaginary unit;

Inf – infinity;

NaN – undefined value.

Some built-in elementary functionsMatLab:

exp(x) – exponent of the number x;

log(x) – natural logarithm of the number x;

sqrt(x) – square root of number x;

abs(x) – modulus of number x;

sin(x), cos(x), tan(x), cot(x) – sine, cosine, tangent, cotangent of the number x;

asin(x), acos(x), atan(x), acot(x) – arcsine, arccosine, arctangent, arccotangent of number x;

sec(x), csc(x) – secant, cosecant of number x;

round(x) – rounding the number x to the nearest integer;

mod(x,y) – remainder of integer division of x by y, taking into account the sign;

sign(x) – return the sign of number x.

Let's calculate the value of the expression

>> exp(–2.5)*log(11.3)^0.3 – sqrt((sin(2.45*pi)+cos(3.78*pi))/tan(3.3))

If the operator cannot be placed on one line, then it is possible to continue entering it in the next line if you indicate the continuation sign “…” at the end of the first line, for example,

>> exp(–2.5)*log(11.3)^0.3 – ...

sqrt((sin(2.45*pi)+cos(3.78*pi))/tan(3.3))

Functions for working with complex numbers:

Entering a complex number

>> z = 3 + 4i

3.0000 + 4.0000i

The functions abs(z), angle(z) return the modulus and argument of a complex number, where , ;

complex(a,b) constructs a complex number from its real and imaginary parts:

conj(z)returns the complex conjugate number;

imag(z), real(z) returns the imaginary and real parts of the complex number z.

6. Vectors.

Entering, adding, subtracting, multiplying by a number.

Vector in MatLab formed using the square brackets operator. In this case, the elements of a column vector are separated by a semicolon “;”, and the elements of a row vector are separated by a space “” or a comma “,”.

Let's introduce a column vector.

>> x =

Let's introduce a row vector .

>> y =

To transpose a vector, use the apostrophe “’”:

>> z = y’

To find the sum and difference of vectors, the “+” and “–” signs are used:

>> c = x + z

Multiplication of a vector by a number is carried out both on the right and on the left using the “*” sign.

Vectors can be arguments to built-in functions, e.g.

>> d = sin(c)

To refer to the elements of vectors, parentheses () are used, for example,

>> x_2 = x(2)

The last element of the vector can be selected by typing the command

>> X_end = x(end)

From several vectors you can make one, for example

>> r =

1.3 5.4 6.9 7.1 3.5 8.2

The colon character " : " is used to separate multiple elements from a vector, for example

>> w = r(3:5)

The colon character " : " also allows you to replace elements of a vector, for example,

>> r(3:5)= 0

1.3 5.4 0 0 0 8.2

The “:” symbol can also be used to construct a vector, each element of which differs from the previous one by a constant number, i.e. step, for example

>> h =

1 1.2 1.4 1.6 1.8 2

The step can be negative (in this case, the starting number must be greater than the final number).

A step equal to one can be omitted

>> k =

Basic functions for working with vectors.

  • length(x) – determining the length of vector x;
  • prod(x) – multiplication of all elements of vector x;
  • sum(x) – summation of all elements of vector x;
  • max(x) – finding the maximum element of vector x;
  • min(x) – finding the minimum element of vector x.

If you call the min or max function with two output arguments = min(x),

then the first variable is assigned the value of the minimum (maximum) element, and the second variable is assigned the number of this element.

7 Matrices.

Various matrix input methods.

1. A matrix can be entered as a column vector consisting of two elements, each of which is a row vector and is separated by a semicolon. For example, let's introduce the matrix

>>A =

2. The matrix can be entered line by line by executing the sequence of commands:

>> A = . 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 the relative error tolerance RelTol (default 1e3) and the absolute error tolerance vector AbsTol (all components default 1e6).

[T,Y]=solver(@ F,tspan,y 0 ,options p 1 ,p 2...) gives a solution similar to the one described above, passing additional parameters 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 graphs of functions.

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 graphs of functions.

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 its 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.

Goal of the work: familiarization with the basic commands of the MATLAB system

Lab Manual

WHAT IS MATLAB?

MATLAB is a high-performance language for technical calculations. It includes calculations, visualization and programming in a user-friendly environment where problems and solutions are expressed in a form close to mathematics. Typical Use MATLAB- This:

    mathematical calculations;

    creation of algorithms;

    modeling;

    data analysis, research and visualization;

    scientific and engineering graphics;

    application development, including graphical interface creation.

MATLAB is an interactive system in which the main data element is an array. This allows you to solve various technical computing problems, especially those involving matrices and vectors, several times faster than writing programs using “scalar” programming languages ​​such as Si or Fortran .

Word MATLAB means matrix laboratory ( matrix laboratory ). MATLAB was specifically written to provide easy access to LINPACK And EISPACK, which are modern software tools for matrix calculations.

MATLAB has evolved over several years, focusing on different users. In a university environment, it was a standard tool for working in various fields of mathematics, engineering and science. In industry, MATLAB is a tool for highly productive research, development and data analysis.

IN MATLAB An important role is played by specialized groups of programs called toolboxes. They are very important for most users MATLAB, as they allow you to study and apply specialized methods. Toolboxes are a comprehensive collection of features MATLAB(M-files), which allow solving particular classes of problems. Toolboxes are used for signal processing, control systems, neural networks, fuzzy logic, wavelets, modeling, etc.

MATLAB SYSTEM

The MATLAB system consists of five main parts:

    Language MATLAB. It is a high-level matrix and array language with thread management, functions, data structures, I/O, and object-oriented programming features. This allows you to program both “small scale” for quickly creating rough programs, and “big scale” for creating large and complex applications.

    Wednesday MATLAB . This is a set of tools and devices that the user or programmer works withMATLAB . It includes tools for managing variables in the workspaceMATLAB , data input and output, and creating, monitoring, and debugging M-files and MATLAB applications.

    Controlled graphics. This is a graphics systemMATLAB , which includes high-level commands for 2D and 3D data visualization, image processing, animation, and illustrated graphics. It also includes low-level commands that allow you to completely edit the appearance of graphics, just as you would when creatingGraphical User Interface (GUI) For MATLAB applications.

    Library of mathematical functions. This is an extensive collection of computational algorithms from elementary functions such as sum, sine, cosine, complex arithmetic, to more complex ones such as matrix inversion, finding eigenvalues, Bessel functions, and fast Fourier transform.

Software interface. This is a library that allows you to write programs inSi And Fortran that interact withMATLAB . It includes facilities for calling programs fromMATLAB (dynamic connection), callingMATLAB as a computing tool and for reading and writing MAT files.

ABOUT SIMULINK

Simulink, accompanying MATLAB program is an interactive system for modeling nonlinear dynamic systems. It is a mouse-controlled environment that allows you to simulate a process by dragging and manipulating diagram blocks on the screen.Simulink works with linear, nonlinear, continuous, discrete, multidimensional systems.

Blocksets - these are additions toSimulink , which provide block libraries for specialized applications such as communications, signal processing, power systems.

Real-Time Workshop is a program that allows you to generateWITH code from diagram blocks and run them on various real-time systems.

MATRICES AND MAGIC SQUARES

The best way to get started is with MATLAB- is to learn how to handle matrices. IN MATLAB a matrix is ​​a rectangular array of numbers. Particular importance is given to 1x1 matrices, which are scalars, and matrices that have one column or one row, called vectors. MATLAB uses a variety of ways to store numeric and non-numeric data, but at first it is best to think of all data as matrices. MATLAB organized so that all operations in it are as natural as possible. While other programming languages ​​work with numbers as language elements, MATLAB allows you to quickly and easily manipulate entire matrices.

A good example of a matrix can be found in an engraving from the Renaissance by an artist and math enthusiast. Albrecht Durer . This image contains a lot of math symbols, and if you look closely you can see a square matrix in the upper right corner. This matrix is ​​known as the magic square and in Dürer's time it was believed to have magical properties. It actually has remarkable properties that are worth studying.

INPUT OF MATRICES

You can enter matrices in MATLAB in several ways:

    enter a complete list of elements;

    load matrices from external files;

    generate matrices using built-in functions;

    create matrices using your own functions in M-files.

Let's start by introducing the Durer matrix as a list of elements. You must follow several basic conditions:

    separate string elements with spaces or commas

    use semicolon, ; , to mark the end of each line

    surround the entire list of elements with square brackets, .

To enter a matrix Durer just write (Fig. 1.1):

A=

MATLAB will display the matrix we entered,

A=

16 3 2 13

5 10 11 8

9 6 7 12

4 15 14 1

Rice. 1.1 Example MATLAB command window fragment

This matches the numbers on the engraving exactly. If we entered a matrix, it is automatically remembered by the environment MATLAB. And we can easily refer to her as A. Now we we have A in the workspaceMATLAB(Fig. 1.2)

Rice. 1.2 Example MATLAB workspace fragment

OPERATIONS OF SUMMATION OF ELEMENTS, TRANSPOSE AND DIAGONALIZATION OF THE MATRIX

You may already know that the special properties of the magic square are related to the different ways in which its elements are summed. If you take the sum of the elements along any row or column, or along any of the two main diagonals, you will always get the same number. Let's test this using MATLAB. The first statement we will check is

sum(A)

MATLAB will give the answer

ans =

34 34 34 34

When the output variable is not defined, MATLAB uses a variable ans, short for answer – answer for storing calculation results. We have calculated a row vector containing the sum of the elements of the matrix columns A. Indeed, each column has the same sum, the magic sum being 34.

What about row amounts? MATLAB prefers to work with the columns of a matrix, so the best way to get the sum in the rows is to transpose our matrix, calculate the sum in the columns, and then transpose the result. The transposition operation is indicated by an apostrophe or single quotation mark. It flips the matrix around the main diagonal and swaps rows for columns. Thus

A'

causes

ans =

16 5 9 4

3 10 6 15

2 11 7 14

13 8 12 1

And the expression

sum(A’)’

causes the result to be a column vector containing the sums in the rows

ans =

34

34

34

34

The sum of the elements on the main diagonal can be easily obtained using the function diag, which selects this diagonal.

diag(A)

ans =

16

10

7

1

A function

sum(diag(A))

causes

ans =

34

Thus, we checked that the matrix on the engraving Durer really magical, and learned to use some matrix operations MATLAB. In subsequent sections, we will continue to use this matrix to demonstrate additional capabilities. MATLAB .

INDICES

Element in line i and column j matrices A denoted by A(i,j). For example, A(4,2) is the number in the fourth row and second column. For our magic square A(4,2) = 15. Thus, we can calculate the sum of the elements in the fourth column of the matrix A by typing

A(1,4) + A(2,4) + A(3,4) + A(4,4)

ans =

34

However, this is not the best way to sum a single row.

It is also possible to access matrix elements through a single index, A(k). This is a common way to refer to the rows and columns of a matrix. But it can only be used with two-dimensional matrices. In this case, the array is treated as a long vector formed from the columns of the original matrix.

So, for our magic square, A(8) is another way to refer to the value 15 stored in A(4,2).

If you are trying to use the value of an element outside of the matrix, MATLAB will give an error:

t=A(4.5)

??? Index exceeds matrix dimensions.

On the other hand, if you store a value outside the matrix, then the size of the matrix increases.

X=A;

X(4,5) = 17

X =

16 3 2 13 0

5 10 11 8 0

9 6 7 12 0

4 15 14 1 17

COLON OPERATOR

The colon, : , is one of the most important operatorsMATLAB . It manifests itself in various forms. Expression

1:10

ans =

1 2 3 4 5 6 7 8 9 10

To obtain the inverse interval, we describe the increment. For example

100:-7:50

ans =

100 93 86 79 72 65 58 51

0:pi/4:pi

which leads

ans =

0 0.7854 1.5708 2.3562 3.1416

The index expression, including the colon, refers to part of the matrix. A(1:k,j) are the first k elements j th matrix column A.

So sum(A(4, 1:4))
calculates the sum of the fourth row. But there is a better way. The colon, by itself, refers to all elements in the row and column of the matrix, and the word end - to the last row or column. So

sum(A(:,end))

calculates the sum of the elements in the last column of a matrix A

ans =

34

Why is the magic sum of a 4x4 square 34? If the integers from 1 to 16 are sorted into four groups with equal sums, that sum must be

sum(1:16)/4

which, of course, is equal

ans =

34

MAGIC FUNCTION

MATLAB actually has a built-in function that creates a magic square of almost any size. Not surprisingly, this function is called magic.

B=magic(4)

B=

16 2 3 13

5 11 10 8

9 7 6 12

4 14 15 1

This matrix is ​​almost the same matrix as in the engraving Durer , and it has all the same magical properties. The only difference is that the two middle columns have swapped places. In order to convert IN into the matrix Durer
A, let's rearrange them.

A=B(:,)

This means that for each row of the matrix IN elements are rewritten in order 1, 3, 2, 4

A=

16 3 2 13

5 10 11 8

9 6 7 12

4 15 14 1

Why Durer reordered the columns compared to what it usesMATLAB ? No doubt he wanted to include the date of the engraving, 1514, at the bottom of the magic square.

EXPRESSIONS

Like most other programming languages, MATLAB provides the ability to use mathematical expressions, but unlike many of them, these expressions in MATLAB involve matrices. The main components of the expression:

    variables

    operators

VARIABLES

IN MATLAB there is no need to define variable type or dimension. When MATLAB encounters a new variable name, it automatically creates the variable and allocates the appropriate amount of memory. If the variable already exists, MATLAB changes its composition and, if necessary, allocates additional memory. For example,

num_students = 25

creates a 1x1 matrix named num_students and stores the value 25 in its only element.

Variable names consist of letters, numbers, or underscores. MATLAB uses only the first 31 characters of the variable name. MATLAB Case sensitive, it distinguishes between uppercase and lowercase letters. That's why A And A– not the same variable. To see the matrix associated with a variable, simply enter the variable name.

NUMBERS

MATLAB uses the conventional decimal number system, with an optional decimal point and plus/minus signs for numbers. The scientific number system uses the letter e to determine the multiplier of a power of ten. Imaginary numbers are used i or j as a suffix.

All numbers are stored using the long format defined by the IEE floating point standard. Floating point numbers have a limited precision of approximately 16 significant digits and a limited range of approximately 10 -308 to 10308 (The VAX computer uses a different floating point format, but their precision and range are approximately the same).

OPERATORS

Expressions use normal arithmetic operations and precedence rules.

Addition

– subtraction

* multiplication

/ division

\ left division (described in the section Matrices and Linear Algebra in the book

“Using MATLAB”)

^ degree

‘ complex conjugate transpose

() determination of the order of calculation

FUNCTIONS

MATLAB provides a large number of elementary mathematical functions such as abs, sqrt, exp, sin. Calculating the square root or logarithm of a negative number is not an error: in this case, the result is the corresponding complex number. MATLAB also provides more complex functions, including the Gamma function and Bessel functions. Most of these functions have complex arguments. To list all elementary math functions, type

help elfun

To display more complex math and matrix functions, type

help specfun

help elmat

respectively.

Some features like sqrt And sin, – built-in They are part MATLAB, so they are very efficient, but their computational details are difficult to access. While other features such as gamma And sink implemented in M-files. Therefore, you can easily see their code and, if necessary, even modify it.

Several special functions provide the values ​​of frequently used constants.

pi 3.14159265…

i imaginary unit

j is the same as i

eps relative precision of a floating point number

realmin smallest floating point number

realmax largest floating point number

infinity

NaN is not a number

Infinity appears when dividing by zero or when executing a mathematical expression that results in overflow, i.e. to exceed realmax. Not a number (NaN) generated when evaluating expressions like 0/0 or Inf- Inf, which have no specific mathematical meaning.

Function names are not reserved, so it is possible to change their values ​​to new ones, for example

eps = 1.e-6

clear eps

EXPRESSIONS

You have already seen some examples of using expressions in MATLAB. Below are some more examples with results.

rho = (1+sqrt(5))/2

rho =

1.6180

A= abs(3+4i)

a =

5

z = sqrt(besselk(4/3,rho-i))

0.3730 + 0.3214i

huge = exp(log(realmax))

huge = 1.7977e+308

toobig = pi*huge

toobig = Inf

GENERATING MATRIXES

MATLAB has four functions that create basic matrices:

zeros all zeros

ones all units

rand uniform distribution of random elements

randn normal distribution of random elements

Some examples:

Z = zeros(2,4)

Z=

0 0 0 0

0 0 0 0

F = 5*ones(3,3)

F=

5 5 5

5 5 5

5 5 5

N = fix(10*rand(1,10))

N=

9 2 6 4 8 7 4 0 8 4

R = randn(4,4)

R=

-0.4326 -1.1465 0.3273 -0.5883

-1.6656 1.1909 0.1746 2.1832

0.1253 1.1892 -0.1867 -0.1364

0.2877 -0.0376 0.7258 0.1139

Team load reads binary files containing matrices created in MATLAB previously, or text files containing numerical data. Text files should be formatted as a rectangular table of numbers separated by spaces, with an equal number of elements on each line. For example, let's create outside MATLAB text file containing 4 lines:

16.0 3.0 2.0 13.0

5.0 10.0 11.0 8.0

9.0 6.0 7.0 12.0

4.0 15.0 14.0 1.0

Let's save this file under the name magik.dat. Then the teamloadmagik.dat will read this file and create a magik variable containing our matrix.

AN ASSOCIATION

Merging is the process of combining small matrices to create larger ones. In fact, you created your first matrix by combining its individual elements. A pair of square brackets is a union operator. For example, let's start with the matrix A(4x4 magic square) and form

B = [A A+32; A+48 A+16]

The result will be an 8x8 matrix obtained by joining four submatrices

B=

16 3 2 13 48 35 34 45

5 10 11 8 37 42 43 40

9 6 7 12 41 38 39 44

4 15 14 1 36 47 46 33

64 51 50 61 32 19 18 29

53 58 59 56 21 26 27 24

57 54 55 60 25 22 23 28

52 63 62 49 20 31 30 17

This matrix is ​​only half magical. Its elements are a combination of integers from 1 to 64, and the sums in the columns are exactly equal to the value for the 8x8 magic square.

sum (B)

ans =

260 260 260 260 260 260 260 260

However, the sums in the rows of this matrix ( sum(B')') not all are the same. Additional operations are needed to make this matrix truly an 8x8 magic square.

DELETING ROWS AND COLUMNS

You can remove rows and columns from a matrix using just a couple of square brackets. Let's consider

X = A;

Now let's remove the second column of the matrix X.

X(:,2) =

This operation will change X in the following way

X =

16 2 13

5 11 8

9 7 12

4 14 1

If you remove one element of a matrix, the result will no longer be a matrix. So the expression

X(1,2) =

the result of the calculation will produce an error. However, using a single index removes a single element or sequence of elements and converts the remaining elements into a row vector. So

X(2:2:10) =

will give the result

X =

16 9 2 7 13 12 1

MATRIX MULTIPLICATION

When multiplying two matrices, the ‘*’ operator is used. For example, if

A=

16 3 2 13

5 10 11 8

9 6 7 12

4 15 14 1

B=

16 4 7 3

5 -7 2 9

0 8 23 65

-7 4 17 9

Then C = A*B will give results

C =

180 111 385 322

74 70 444 892

90 98 440 644

132 27 397 1066

MATLAB also provides the ability to perform element-by-element multiplication. A dot before the multiplication sign is used for this purpose. For example:

C = A.*B

as a result

C=

256 12 14 39

25 -70 22 72

0 48 161 780

-28 60 238 9

CREATING M-FILES

M-files are ordinary text files that are created using a text editor. For the personal computer operating environment, MATLAB supports a special built-in editor/debugger, although any other ASCII text editor can be used.

There are two ways to open the editor:

    from the File menu select the New option and then M-File.

    use edit command edit .

M-functions are M-files that accept input and output arguments. They operate on variables within their own workspace, distinct from the MATLAB system's workspace.

Example

The average function is a fairly simple M-file that calculates the average of the elements of a vector:

function y = average(x)

% AVERAGE Average value of the vector elements.

% AVERAGE(X), where X is a vector. Calculates the average of the elements

% vector.

% If the input argument is not a vector, an error is generated.

Size(x);

If (~((m == 1) | (n == 1)) | (m == 1 & n == 1))

Error('Input array must be a vector')

End

Y = sum(x)/length(x); % The actual calculation

Try entering these commands into an M file called average.m. The average function accepts a single input and a single output argument. In order to call the average function, you must enter the following statements:

z = 1:99;

average(z)


We get the result

ans = 50

STATISTICAL CHARACTERISTICS OF SIGNALS

The average value of the signal (its constant component) is determined by the following formula:

(1.1)

The standard deviation (RMS, deviation, variable component) of the signal is determined by the following formula:

(1.2)

The value of the statistical error of the received signal is determined by the following formula:

(1.3)

The normal distribution function is described by the following formula:

(1.4)

EXERCISE

    Work through the basic commands outlined above in MATLAB.

    Create an M-function that takes as input a vector of arbitrary dimension with data and returns:

    1. the average value calculated in accordance with formula (1.1), as well as obtained as a result of applying the mean function;

      standard deviation calculated in accordance with formula (1.2), as well as obtained as a result of applying the std function.

    Create an M-function that takes as input a vector of arbitrary dimension with data and returns the statistical error value T.E. in accordance with formula (1.3).

    Explore the hist histogram function yourself (check out help on this function - doc hist).

    Plot a graph of the normal distribution function in accordance with formula (1.4) using the plot and fplot functions.

    Create an M-function based on the randn command that generates normally distributed random noise with a given mean and standard deviation.