How to set up smartphones and PCs. Informational portal
  • home
  • Iron
  • Basics of working with MATLAB. File functions with multiple output arguments

Basics of working with MATLAB. File functions with multiple output arguments

The MATLAB environment includes a command interpreter in a high-level language, a graphics system, extension packages, and is implemented in C. All work is organized through the Command Window, which appears when the matlab.exe program is launched. In the course of work, the data is located in the memory (Workspace), graphics windows are created to display curves, surfaces and other graphs.

Calculations are performed in the command window in dialog mode. The user enters commands or launches files with texts in the MATLAB language. The interpreter processes the input and produces results: numeric and string data, warnings and error messages. The input line is marked with >>. The command window displays numbers entered from the keyboard, variables, and the results of calculations. Variable names must start with a letter. The = sign corresponds to the assignment operator. Pressing the Enter key causes the system to evaluate the expression and display the result. Type from the keyboard in the input line:

Press the Enter key, the calculation result will appear on the screen in the viewing area:

All values ​​of variables calculated during the current session of work are stored in a specially reserved area of ​​computer memory called the workspace of the MATLAB system (Workspace). The clc command can clear the contents of the command window, but this will not affect the contents of the workspace. When it is no longer necessary to store a number of variables in the current session, they can be erased from the computer's memory with the clear or clear(name1, name2, ...) command. The first command removes all variables from memory, and the second removes the variables named name1 and name2. The who command can be used to display a list of all variables currently included in the system workspace. To view the value of any variable from the current workspace of the system, just type its name and press the Enter key.

After the end of the session with the MATLAB system, all previously calculated variables are lost. To save the contents of the workspace of the MATLAB system to a file on a computer disk, you need to execute the menu command File / Save Workspace As .... By default, the file name extension is mat, so such files are usually called MAT-files. To load a workspace previously saved on disk into the computer's memory, execute the menu command: File / Load Workspace ... .

Real Numbers and the Double Data Type

The MATLAB system represents at the machine level all real numbers given by the mantissa and the exponent, for example, 2.85093E+11, where the letter E denotes the base of the degree equal to 10. This basic data type is called double. MATLAB defaults to the short format for floating point output, which displays only four decimal digits after the decimal point.

Enter from the keyboard an example:

»res=5.345*2.868/3.14-99.455+1.274

Get the result of the calculation:

If the full representation of the real number res is required, enter the command from the keyboard:

press the Enter key and get more details:

res = -93.29900636942675

Now all calculation results will be shown with such high accuracy during this session in the MATLAB system environment. If you need to return to the old precision of the visual representation of real numbers in the command window before terminating the current session, you need to enter and execute (by pressing the Enter key) the command:

Integers are displayed by the system in the command window as integers.

Arithmetic operations are performed on real numbers and variables of double type: addition +, subtraction -, multiplication *, division / and exponentiation ^ . Priority in the execution of arithmetic operations is normal. Operators of the same precedence are performed in left-to-right order, but parentheses can change that order.

If there is no need to see the result of the calculation of some expression in the command window, then at the end of the entered expression, put a semicolon and only then press Enter.

The MATLAB system contains all the basic elementary functions for calculations with real numbers. Any function is characterized by its name, the list of input arguments (they are listed separated by commas and are inside the parentheses following the function name) and the calculated (returned) value. A list of all elementary mathematical functions available in the system can be obtained using the help elfun command. Appendix 1 lists the standard functions of a real argument.

Evaluate an expression involving the calculation of the arcsine function:

Make sure you get the following result:

corresponding to the number "pi". In the MATLAB system, there is a special notation for calculating the number "pi": pi. (A list of MATLAB system variables is in Appendix 2).

MATLAB also has logical functions, functions related to integer arithmetic (rounding to the nearest integer: round, truncation of the fractional part of a number: fix). There is also the mod function - the remainder of the division, taking into account the sign, sign - the sign of a number, lcm - the least common multiple, perms - the calculation of the number of permutations and nchoosek - the number of combinations and many others. Many of the functions have a domain of definition different from the set of all real numbers.

In addition to arithmetic operations on double type operands, relational and logical operations are also performed. Relational operations compare two operands in magnitude. These operations are written with the following characters or combinations of characters (Table 1):

Table 1


If the relational operator is true, its value is 1, and if it is false, it is 0. Relational operators have lower precedence than arithmetic operators.

Type an expression with relational operations from the keyboard and calculate

» a=1; b=2; c=3;

» res=(a

You will get the following result:

Logical operations on real numbers are denoted by the signs listed in Table 2:

table 2


& | ~
AND OR NOT

The first two of these operations are binary (two-operand), and the last one is unary (single-operand). Logical operators treat their operands as "true" (not equal to zero) or "false" (equal to zero). If both operands of the "AND" operation are true (not equal to zero), then the result of this operation is 1 ("true"); in all other cases, the "AND" operation produces the value 0 ("false"). The OR operation produces 0 (false) only if both operands are false (equal to zero). The "NOT" operation inverts "false" to "true". Logical operations have the lowest priority.

Complex numbers and complex functions

Complex variables, like real ones, automatically have the double type and do not require any preliminary description. The letters i or j are reserved for the imaginary unit. In the case when the coefficient in front of the imaginary unit is not a number, but a variable, the multiplication sign must be used between them. So, complex numbers can be written as follows:

» 2+3i; -6.789+0.834e-2*i; 4-2j; x+y*i;

Almost all elementary functions allow calculations with complex arguments. Evaluate the expression:

» res=sin(2+3i)*atan(4i)/(1 -6i)

The result will be:

1.8009 - 1.91901

The following functions are specially designed for working with complex numbers: abs (absolute value of a complex number), conj (complex conjugate), imag (imaginary part of a complex number), real (real part of a complex number), angle (argument of a complex number), isreal ( "true" if the number is real). The functions of a complex variable are listed in Appendix 1.

With regard to arithmetic operations, nothing new for complex numbers (compared to real ones) is impossible to say. The same applies to the relational operations “equal to” and “not equal to”. The rest of the relational operations produce a result based only on the real parts of these operands.

Enter an expression, get the result and explain it:

» c=2+3i; d=2i; » c>d

Boolean operations treat operands as false if they are zero. If at least one part of the complex operand (real or imaginary) is not equal to zero, then such an operand is treated as true.

Numeric arrays

To create a one-dimensional array, you can use the concatenation operation, which is denoted with square brackets. Array elements are placed between brackets and separated from each other by a space or a comma:

»al=; d=;

To access an individual array element, you need to apply the indexing operation, for which, after the element name, specify the element index in parentheses.

You can change the elements of an already formed array by applying the indexing and assignment operations. For example, by entering:

we will change the third element of the array. Or, after the introduction:

» al(2)=(al(1)+al(3))/2;

the second element of the array will become equal to the arithmetic mean of the first and third elements. Writing a non-existent element is perfectly valid - it means adding a new element to an already existing array:

Applying the length function to the array a1 after performing this operation, we find that the number of elements in the array has increased to four:

The same action - "lengthening the array a1" - can be performed using the concatenation operation:

You can define an array by listing all of its elements individually:

» a3(1)=67; a3(2)=7.8; a3(3)=0.017;

However, this method of creation is not efficient. Another way to create a one-dimensional array is based on the use of a special function, denoted by a colon (the operation of forming a range of numeric values). After a colon, type the first number of the range, the step (increment) and the final number of the range. For example:

»diap=3.7:0.3:8.974;

If you do not need to display the entire resulting array, then at the end of the set (after the end number of the range) you should type a semicolon. To find out how many elements are in an array, call the length(array name) function.

To create a two-dimensional array (matrix), you can also use the concatenation operation. The elements of the array are typed one after the other according to their location in the lines, a semicolon is used as a line separator.

Enter from the keyboard:

» a=

Press ENTER, we get:

The resulting matrix a of size 3x2 (the first indicates the number of rows, the second - the number of columns) can also be formed by vertical concatenation of row vectors:

»a=[;;];

or horizontal concatenation of column-vectors:

» a=[,];

The structure of the created arrays can be found using the whos(array name) command, the array dimension by the ndims function, and the array size by size.

Two-dimensional arrays can also be specified using the indexing operation, writing its elements separately. The row and column number at the intersection of which the specified array element is located are indicated separated by commas in parentheses. For example:

» a(1,1)=1; a(1,2)=2; a(2,1)=3; » a(2,2)=4; a(3,1)=5; a(3,2)=6;

However, it will be much more efficient if, before starting to write the array elements, create an array of the required size using the ones (m, n) or zeros (m, n) functions, filled with ones or zeros (m is the number of rows, n is the number of columns). When these functions are called, memory is pre-allocated for a given array size, after which the gradual prescribing of elements with the desired values ​​does not require rebuilding the memory structure allocated for the array. These functions can also be used when specifying arrays of other dimensions.

If, after forming the array X, you need to change its size without changing the array elements, you can use the reshape (X, M, N) function, where M and N are the new sizes of the X array

It is possible to explain the operation of this function only on the basis of the way in which the MATLAB system stores the elements of arrays in computer memory. It stores them in a contiguous area of ​​memory in column order: the elements of the first column are placed first, followed by the elements of the second column, and so on. In addition to the actual data (array elements), control information is also stored in the computer memory: the type of the array (for example, double), the dimension and size of the array, and other service information. This information is enough to determine the boundaries of the columns. It follows that to reshape the matrix with the reshape function, it is enough to change only the service information and not touch your own data.

You can swap the rows of a matrix with its columns using the transport operation, which is denoted by the sign." (dot and apostrophe). For example,

»A=;

The " (apostrophe) operation performs transposition for real matrices and transposition with simultaneous complex conjugation for complex matrices.

The objects that MATLAB works with are arrays. Even one given number in MATLAB's internal representation is an array consisting of one element. MATLAB allows you to do calculations with huge arrays of numbers as easily as with single numbers, and this is one of the most noticeable and important advantages of the MATLAB system over other software packages focused on calculations and programming. In addition to the memory required to store numeric elements (8 bytes each for real numbers and 16 bytes for complex numbers), MATLAB automatically allocates memory for control information when creating arrays.

Array Calculations

In traditional programming languages, arrays are computed element by element, in the sense that each individual operation must be programmed on a separate element of the array. In the M-language of the MATLAB system, powerful group operations are allowed on the entire array at once. It is the group operations of the MATLAB system that make it possible to set expressions in an extremely compact way, in the calculation of which a gigantic amount of work is actually performed.

Matrix addition and subtraction operations are denoted by the standard + and - signs.

Define matrices A and B and perform the matrix addition operation:

»A=; B=;

If operands of different sizes are used, an error message is generated, unless one of the operands is a scalar. When performing the operation A + scalar (A - matrix), the system will expand the scalar to an array of size A, which is further added element by element to A.

For element-wise multiplication and element-by-element division of arrays of the same size, as well as element-wise exponentiation of arrays, operations are used, denoted by combinations of two symbols: .* , ./, and .^. The use of symbol combinations is explained by the fact that the symbols * and / denote special linear algebra operations on vectors and matrices.

In addition to the ./ operation, called the right element-wise division operation, there is also the left element-wise division operation. \. The difference between these operations: the expression A./B results in a matrix with elements A (k, m) / B (k, m), and the expression A. \ B leads to a matrix with elements B (k, m) / A (k , m).

The sign * is assigned to the multiplication of matrices and vectors in the sense of linear algebra.

The \ sign is fixed in the MATLAB system for solving a rather complex linear algebra problem - finding the roots of a system of linear equations. For example, if you need to solve a system of linear equations Ay = b, where A is a given square matrix of size N´N, b is a given column vector of length N, then to find the unknown column vector y, it is enough to calculate the expression A \ b (this is equivalent to the operation : A -1 B).

Typical problems of analytical geometry in space, related to finding the lengths of vectors and angles between them, with the calculation of the scalar and vector products, are easily solved by various means of the MATLAB system. For example, to find the cross product of vectors, the special function cross is intended, for example:

»u=; v=;

The dot product of vectors can be calculated using the general function sum, which calculates the sum of all elements of vectors (for matrices, this function calculates the sums for all columns). The scalar product, as is known, is equal to the sum of the products of the corresponding coordinates (elements) of the vectors. So the expression is: » sum(u.*v)

calculates the dot product of two vectors u and v. The dot product can also be calculated as: u*v".

The length of a vector is calculated using the dot product and the square root function, for example:

» sqrt(sum(u.*u))

The relational and logical operations previously considered for scalars are performed element by element in the case of arrays. Both operands must be the same size, and the operation returns a result of the same size. In the case when one of the operands is a scalar, its preliminary expansion is performed, the meaning of which has already been explained using the example of arithmetic operations.

Among the functions that generate matrices with given properties, the function is often used eye, which produces unit square matrices, as well as the rand function, which is widely used in practice, generating an array with random elements uniformly distributed over the interval from 0 to 1. For example, the expression

generates a 3x3 array of random numbers with elements evenly distributed over the interval from 0 to 1.

If you call this function with two arguments, for example R=rand(2,3), you will get a 2x3 matrix R of random elements. When rand is called with three or more scalar arguments, multidimensional arrays of random numbers are produced.

The square matrix determinant is calculated using the det function. Among the functions that perform the simplest calculations on arrays, in addition to the sum function discussed above, the prod function is also used, which is similar in everything to the sum function, only it calculates not the sum of elements, but their product. The max and min functions search for the maximum and minimum elements of arrays, respectively. For vectors, they return a single numeric value, and for matrices, they generate a set of extreme elements computed for each column. The sort function sorts the elements of one-dimensional arrays in ascending order, and for matrices it sorts for each column separately.

MATLAB has the unique ability to perform group calculations on arrays using common math functions that only work with scalar arguments in traditional programming languages. As a result, with the help of extremely compact notations, convenient for typing in interactive mode with the command window of the MATLAB system, it is possible to perform a large amount of calculations. For example, just two short expressions

» x=0:0.01:pi/2; y=sin(x);

calculate the values ​​of the sin function at 158 ​​points at once, forming two vectors x and y with 158 elements each.

Plotting functions

The graphical capabilities of the MATLAB system are powerful and varied. Let's explore the most easy-to-use features (high-level graphics).

Form two vectors x and y:

» x=0:0.01:2; y=sin(x);

Call the function:

and you will get a graph of the function on the screen (Fig. 1).

Rice. 1. Graph of the function y=sin(x)

MATLAB displays graphics objects in special graphics windows that have the word Figure in their title. Without removing the first graphic window from the display screen, enter the expressions from the keyboard

and get a new graph of the function in the same graphics window (in this case, the old coordinate axes and the graph disappear - this can also be achieved with the clf command, the cla command removes only the graph, bringing the coordinate axes to their standard ranges from 0 to 1).

If you need to draw the second graph “on top of the first graph”, then before calling the plot graphic function again, you need to execute the hold on command, which is designed to hold the current graphics window:

» x=0:0.01:2; y=sin(x);

Almost the same thing will happen (Fig. 2) if you type:

» x=0:0.01:2; y=sin(x); z=cos(x);

»plot(x,y,x,z)

Rice. 2. Graphs of functions y=sin(x), z=cos(x), built in one graphic window

If you need to visualize several graphs at the same time so that they do not interfere with each other, then this can be done in two ways. The first solution is to plot them in different graphics windows. To do this, before calling the plot function again, type the figure command, which creates a new graphics window and forces all subsequent plotting functions to display them there.

The second solution for displaying multiple plots without conflicting axes ranges is to use the subplot function. This function allows you to divide the graphic information output area into several sub-areas, in each of which you can display graphs of various functions.

For example, for previously performed calculations with the sin and cos functions, plot the graphs of these two functions in the first sub-area, and plot the function exp(x) in the second sub-area of ​​the same graphics window (Fig. 3):

» subplot(1,2,1); plot(x,y,x,z)

» subplot(1,2,2); plot(x,w)

Rice. 3. Graphs of the functions y=sin(x), z=cos(x) and w=exp(x), built in two subareas of one graphic window

The ranges of variables on the coordinate axes of these subdomains are independent of each other. The subplot function takes three numeric arguments, the first of which is equal to the number of rows of subplots, the second is equal to the number of columns of subplots, and the third argument is the number of the subplot (the number is counted along the rows, moving to a new row when exhausted). You can remove the action of the subplot function with the command:

» subplot(1,1,1)

If for a single graph the ranges of variables along one or both coordinate axes are too large, then you can use the plotting functions on a logarithmic scale. The functions semilogx, semilogy and loglog are designed for this.

You can plot the function in polar coordinates (Fig. 4) using the polar graphic function.

» phi=0:0.01:2*pi; r=sin(3*phi);

Rice. 4. Graph of the function r=sin(3*phi) in polar coordinates

Let's consider additional features related to managing the appearance of charts - setting the color and style of lines, as well as placing various labels within the graphics window. For example, commands

» x=0:0.1:3; y=sin(x);

» plot(x,y,"r-",x,y, "ko")

allow you to make the graph look like a red solid line (Fig. 5), on which black circles are put down at discrete calculated points. Here the plot function plots the same function twice, but in two different styles. The first of these styles is labeled "r-", which means a line drawn in red (letter r), and a stroke means a solid line. The second style, labeled "ko", means drawing in black (letter k) circles (letter o) in place of the computed points.

Rice. 5. Plotting the function y=sin(x) in two different styles

In general, the function plot (x1, y1, s1, x2, y2, s2, ...) allows you to combine several graphs of functions y1(x1), y2(x2), ... in one graphics window by drawing them with styles s1, s2, ... etc.

Styles s1, s2,... are specified as a set of three character markers enclosed in single quotes (apostrophes). One of these markers specifies the line type (Table 3). Another marker sets the color (Table 4). The last marker sets the type of "dots" to be put down (Table 5). You may not specify all three markers. Then the default markers are used. The order in which the markers are specified is not significant, i.e. "r+-" and "-+r" produce the same result.

Table 3. Line type markers

Table 4 Markers that set the color of the line

Table 5 Markers defining point type

If you put a marker on the point type in the style line, but do not put a marker on the line type, then only calculated points are displayed, and they are not connected by a continuous line.


The MATLAB system sets the limits on the horizontal axis to the values ​​specified by the user for the independent variable. For the dependent variable on the vertical axis, MATLAB independently calculates the range of function values. If you need to abandon this scaling feature when plotting graphs in the MATLAB system, then you need to explicitly impose your own limits for changing variables along the coordinate axes. This is done using the axis() function.

The xlabel, ylabel, title and text functions are used to put down various inscriptions on the resulting figure. The xlabel function creates a label for the horizontal axis, the ylabel function also for the vertical axis (moreover, these labels are oriented along the coordinate axes). If you want to place an inscription in an arbitrary place in the figure, use the text function. The general title for the graph is created by the title function. In addition, using the grid on command, you can apply a measurement grid to the entire plotting area. For example (Fig. 6):

» x=0:0.1:3; y=sin(x);

» plot(x,y,"r-",x,y,"ko")

»title("Function sin(x) graph");

» xlabel("xcoordinate"); ylabel("sin(x)");

» text(2.1, 0.9, "\leftarrowsin(x)"); grid on

The label with the text function is placed starting from the point with the coordinates specified by the first two arguments. By default, coordinates are specified in the same units as the coordinates specified on the horizontal and vertical axes. Special control characters are entered inside text after the \ (backslash) character.

3D graphics

Each point in space is characterized by three coordinates. A set of points belonging to some line in space must be specified as three vectors, the first of which contains the first coordinates of these points, the second vector - their second coordinates, the third vector - the third coordinates. After that, these three vectors can be fed to the input of the plot3 function, which will project the corresponding three-dimensional line onto the plane and build the resulting image (Fig. 7). Enter from the keyboard:

» t=0:pi/50:10*pi; x=sin(t);

» y=cos(t); plot3(x,y,t); grid on

Rice. 7. Plot of a helix, built using the function plot3

The same plot3 function can also be used to depict surfaces in space, if, of course, you draw not one line, but many. Type from the keyboard:

» u=-2:0.1:2; v=-1:0.1:1;

»=meshgrid(u,v);

» z=exp(-X.^2-Y.^2);

Obtain a three-dimensional image of the graph of the function (Fig. 8).

The plot3 function draws a graph as a set of lines in space, each of which is a section of a three-dimensional surface by planes parallel to the yOz plane. In addition to this simple function, the MATLAB system has a number of other functions that allow you to achieve greater realism in the display of three-dimensional graphs.

Rice. 8. Plot of the surface in space, built using the function plot3


Scripts and m-files.

For simple operations, interactive mode is convenient, but if calculations need to be performed repeatedly or complex algorithms need to be implemented, then MATLAB m-files (the file extension consists of a single letter m) should be used. script-m-file (or script) - a text file containing MATLAB instructions to be executed in automatic batch mode. It is more convenient to create such a file using the MATLAB system editor. It is called from the command window of the MATLAB system by the menu command File/New/M-file (or the leftmost button on the toolbar, which shows a blank white sheet of paper). The commands written in script files will be executed if you enter the name of the script file (without extension) in the command line. Variables defined in the command window and variables defined in scripts constitute a single workspace of the MATLAB system, and the variables defined in scripts are global, their values ​​will replace the values ​​of the same variables that were used before calling this script file.

After creating the text of the script, it must be saved to disk. The path to the directory with the file must be known to the MATLAB system. The File/Set Path command invokes the Directory Path Viewer dialog box. To add a new directory to the list of access paths, execute the menu command Path/Add to path.

Working from the MatLab command line is difficult if you need to enter a lot of commands and change them often. Keeping a diary with the diary command and saving the working environment only makes things a little easier. The most convenient way to execute MatLab commands is to use M-files, in which you can type commands, execute them all at once or in parts, save them in a file and use them later. The M-file editor is designed to work with M-files. With this editor, you can create your own functions and call them, including from the command line.

Expand the menu file the main window of MatLab and in paragraph New select sub item M-file. The new file opens in the M-file editor window.

Type commands in the editor that lead to the construction of two graphs in one graphics window:

x = ;
f = exp(-x);
subplot(1, 2, 1)
plot(x, f)
g = sin(x);
subplot(1, 2, 2)
plot(x, g)

Save the file now with the name mydemo.m in a subdirectory work the main MatLab directory by selecting the item Save as menu file editor. To run all the commands contained in the file, select the item Run on the menu debug. A graphics window will appear on the screen. figure no.1, containing graphs of functions. If you decide to plot cosine instead of sine, then simply change the line g = sin(x) in the M-file to g = cos(x) and run all the commands again.

Remark 1

If an error is made while typing and MatLab cannot recognize the command, then the commands are executed until the incorrectly entered one, after which an error message is displayed in the command window.

A very handy feature provided by the M-file editor is execution of some commands. Close the graphics window figure No.1. Select with the mouse while holding down the left button, or with the arrow keys while holding down the key , the first four commands of the program and execute them from paragraph Evaluate Selection menu Text. Please note that only one graph corresponding to the executed commands was displayed in the graphics window. Remember that to execute some of the commands, you must select them and press . Run the remaining three program commands and monitor the state of the graphics window. Practice on your own, type some examples from previous labs in the M-file editor and run them.

Individual blocks of the M-file can be provided with comments, which are skipped during execution, but are convenient when working with an M-file. Comments in MatLab begin with a percent sign and are automatically highlighted in green, for example:

%plotting sin(x) in a separate window

Multiple files can be open at the same time in the M-file editor. The transition between files is carried out using the tabs with file names located at the bottom of the editor window.

Opening an existing M-file is done using the item open menu file working environment or M-file editor. You can also open a file in the editor with the MatLab edit command from the command line, specifying the file name as an argument, for example:

The edit command without an argument results in the creation of a new file.
All examples that appear in this and the following labs are best typed and saved in M-files, supplementing them with comments, and executed from the M-file editor. The application of numerical methods and programming in MatLab requires the creation of M-files.

2. Types of M-files

M-files in MatLab are of two types: program-file(Script M-Files) containing a sequence of commands, and function-file(Function M-Files), which describe user-defined functions.

The file-program (file-procedure) you created while reading the previous subsection. All variables declared in a file-program become available in the working environment after its execution. Execute the file program given in subsection 2.1 in the M?file editor and type the whos command at the command line to view the contents of the working environment. A description of the variables will appear in the command window:

» whos
Name Size Bytes Class
f 1x71 568 double array
g 1x71 568 double array
x 1x71 568 double array
Grand total is 213 elements using 1704 bytes

Variables defined in one program file can be used in other program files and in commands executed from the command line. The commands contained in the file program are executed in two ways:

  • From the M-file editor as described above.
  • From the command line or another program file, using the M-file name as the command.

The use of the second method is much more convenient, especially if the created program file will be repeatedly used later. In fact, the created M-file becomes a command that MatLab understands. Close all graphic windows and type mydemo at the command line, a graphic window appears corresponding to the commands of the mydemo.m program file. After entering the mydemo command, MatLab performs the following actions.

  • Checks if the command entered is the name of one of the variables defined in the runtime. If a variable is entered, its value is displayed.
  • If not a variable is entered, then MatLab searches for the entered command among the built-in functions. If the command is a built-in function, then it is executed.

If neither a variable nor a built-in function is entered, then MatLab starts searching for an M-file with the command name and extension m. Search starts with current directory(Current Directory), if the M-file is not found in it, then MatLab looks through the directories installed in search paths(Path). The found M-file is executed in MatLab.

If none of the above actions was successful, then a message is displayed in the command window, for example:

» mydem
??? Undefined function or variable "mydem".

As a rule, M-files are stored in the user's directory. In order for the MatLab system to find them, you must set the paths indicating the location of the M-files.

Remark 2

Keeping your own M-files outside the main MatLab directory is for two reasons. First, when reinstalling MatLab, files that are contained in subdirectories of the main MatLab directory may be destroyed. Secondly, when starting MatLab, all the files of the toolbox subdirectory are placed in the computer's memory in some optimal way so as to increase performance. If you have written an M-file to this directory, then you can use it only after restarting MatLab.

3. Setting paths

In MatLab version 6 .x the current directory and search paths are determined. These properties are set either using the appropriate dialog boxes or commands from the command line.

The current directory is determined in the dialog box Current Directory working environment. The window is present in the working environment if the item is selected Current Directory menu view working environment.
The current directory is selected from the list. If it is not in the list, then it can be added from the dialog box Browse for folder, called by clicking on the button located to the right of the list. The contents of the current directory are displayed in the file table.

Search paths are defined in the dialog box set Path path navigator, accessed from the point set Path menu file working environment.

To add a directory, click the button Add Folder Browse for Path select the desired directory. Adding a directory with all its subdirectories is done by clicking on the button Add with subfolders. MATLAB search path. The search order corresponds to the location of the paths in this field, the first directory is searched, the path to which is located at the top of the list. You can change the search order or even remove the path to a directory, for which select the directory in the field MATLAB search path and define its position using the following buttons:
move to Top - put at the top of the list;
move Up - move up one position;
Remove - remove from the list;
move Down - move down one position;
move to bottom - put at the bottom of the list.

4. Commands for setting paths.

Steps to set paths in MatLab 6 .x duplicate commands. The current directory is set with the cd command, for example cd c:\users\igor. The cd command, called without an argument, prints the path to the current directory. Paths are set using the path command, which is called with two arguments:

path (path, "c:\users\igor") - adds the directory c:\users\igor with the lowest search priority;
path ("c: \users\igor",path) - adds the directory c:\users\igor with the highest search priority.

Using the path command with no arguments causes a list of search paths to be displayed on the screen. You can remove a path from the list using the rmpath command:

rmpath("c:\users\igor") removes the path to c:\users\igor from the list of paths.

Remark 3

Don't unnecessarily remove directory paths, especially those you're not sure about. Removal may result in the fact that some of the functions defined in MatLab become unavailable.

Example. Create in the root directory of the drive D(or any other drive or directory where students are allowed to create their own directories) a directory with your last name, eg WORK_IVANOV, and write the M-file mydemo.m there under the name mydemo3.m. Set file paths and demonstrate file accessibility from the command line. Report the results in a lab report.

Solution:

1. In the root directory of the disk D the WORK_IVANOV directory is created.
2. The M-file mydemo.m is written to the WORK_IVANOV directory under the name mydemo3.m.
3. A dialog box opens set Path menu file MatLab working environment.
4. Button is pressed Add Folder and in the dialog that appears Browse for Path the WORK_IVANOV directory is selected.
5. Adding a directory with all its subdirectories is done by clicking on the button Add with subfolders. The path to the added directory appears in the field MATLAB search path.
6. To save the path, press the key Save dialog box set Path.
7. The correctness of all actions is checked by typing the mydemo3 command from the command line. A graphics window will appear on the screen.

5. File functions

The file programs discussed above are a sequence of MatLab commands, they have no input or output arguments. To use numerical methods and when programming your own applications in MatLab, you must be able to compose file functions that perform the necessary actions with input arguments and return the result in output arguments. This subsection provides some simple examples to help you understand how to work with file functions. Function files, like procedure files, are created in the M-file editor.

5.1. File functions with one input argument

Suppose that in calculations it is often necessary to use the function

It makes sense to write a function file once, and then call it wherever it is necessary to evaluate this function. Open a new file in the M-file editor and type the listing text

function f = myfun(x)
f= exp(-x)*sqrt((x^2+1)/(x^4+0.1));

The word function on the first line specifies that this file contains a function file. The first line is function header, which hosts function name and lists of input and output arguments. In the example in the listing, the function name is myfun, one input argument is x, and one output argument is f. After the title follows function body(in this example it consists of one line), where its value is calculated. It is important that the computed value is written to f. The semicolon is set to prevent unnecessary information from being displayed on the screen.

Now save the file in your working directory. Please note that the item selection Save or Save as menu file leads to the appearance of a dialog box for saving the file, in the field file name which already contains the name myfun. Do not change it, save the function file in a file with the suggested name.

Now the created function can be used in the same way as the built-in sin, cos and others, for example, from the command line:

»y=myfun(1.3)
Y =
0.2600

The call of own functions can be carried out from a file-program and from another file-function.

A warning

The directory containing the function file must be the current one, or the path to it must be added to the search path, otherwise MatLab simply will not find the function, or it will call another one with the same name instead (if it is in the searchable directories ).

The function file shown in the listing has one significant drawback. An attempt to evaluate function values ​​from an array results in an error, not an array of values, as occurs when evaluating built-in functions.

» x = ;
» y = myfun(x)
??? Error using ==> ^
Matrix must be square.
Error in ==> C:\MATLABRll\work\myfun.m
On line 2 ==> f = exp(-x)*sqrt((x^2+1)/(x^4+1));

If you have learned how to work with arrays, then eliminating this shortcoming will not cause difficulties. You just need to use element-wise operations when calculating the function value.
Modify the body of the function as shown in the following listing (don't forget to save the changes in the myfun.m file).

function f = myfun(x)
f = exp(-x).*sqrt((x.^2+1)./(x.^4+0.1));

Now the argument of the myfun function can be either a number or a vector or matrix of values, for example:

» x = ;
» y = myfun(x)
Y =
0.2600 0.0001

The variable y, into which the result of calling the myfun function is written, automatically becomes a vector of the required size.

Plot the function myfun on a segment from the command line or using the file program:

x = ;
y = myfun(x);
plot(x, y)

MatLab provides another way to work with file functions - using them as arguments to some commands. For example, to plot a graph, use the special function fplot, which replaces the sequence of commands given above. When fplot is called, the name of the function whose plot is to be plotted is enclosed in apostrophes, plotting limits are specified in a row vector of two elements

fplot("myfun", )

Plot myfun with plot and fplot on the same axes, with hold on. Note that the graph plotted with fplot more accurately reflects the behavior of the function, because fplot itself picks up the argument step, decreasing it in areas of fast change in the displayed function. Report the results in a lab report.

5.2. File Functions with Multiple Input Arguments

Writing file functions with multiple input arguments is almost the same as writing a single argument. All input arguments are placed in a comma-separated list. For example, the following listing contains a function file that calculates the length of the radius vector of a point in 3D space
Listing file function with multiple arguments

function r = radius3(x, y, z)
r = sqrt(x.^2 + y.^2 + z.^2);

» R = radius3(1, 1, 1)
R=
1.732

In addition to functions with multiple input arguments, MatLab allows you to create functions that return multiple values, i.e. having multiple output arguments.

5.3. File functions with multiple output arguments

File functions with multiple output arguments are useful for evaluating functions that return multiple values ​​(in mathematics they are called vector functions). The output arguments are added, separated by commas, to the list of output arguments, and the list itself is enclosed in square brackets. A good example is a function that converts a time given in seconds to hours, minutes, and seconds. This function file is shown in the following listing.

Listing of the function to convert seconds to hours, minutes and seconds

function = hms(sec)
hour = floor(sec/3600);
minute = floor((sec-hour*3600)/60);
second = sec-hour*3600-minute*60;

When calling file functions with multiple output arguments, the result should be written to a vector of the appropriate length:

» [H, M, S] = hms(10000)
H=
2
M =
46
S=
40

6. Basics of programming in MatLab

The function file and program file used in the previous subsections are the simplest examples of programs. All MatLab commands contained in them are executed sequentially. To solve many more serious problems, it is required to write programs in which actions are performed cyclically or, depending on certain conditions, various parts of programs are executed. Let's consider the main operators that specify the execution sequences of MatLab commands. Operators can be used both in file procedures and in functions, which allows you to create programs with a complex branching structure.

6.1. Loop statement for

The operator is designed to perform a given number of repetitive actions. The simplest use of the for statement is as follows:

for count = start:step:final
MatLab commands
end

Here count is a loop variable, start is its initial value, final is its final value, and step is 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. The loop variable can take not only integer values, but also real values ​​of any sign. Let's analyze the application of the for cycle operator on some typical examples.
Let it be required to derive a family of curves for , which is given by a function depending on the parameter for parameter values ​​from -0.1 to 0.1.
Type the text of the procedure file in the M-file editor and save it in the FORdem1.m file, and run it for execution (from the M-file editor or from the command line by typing the FORdem1 command in it and pressing ):

% file-program for constructing a family of curves
x = ;
for a = -0.1:0.02:0.1
y = exp(-a*x).*sin(x);
hold on
plot(x, y)
end

Remark 4

The M-file editor automatically suggests placing statements inside the loop, indented from the left margin. Use this opportunity for the convenience of working with the text of the program.

As a result of executing FORdem1, a graphical window will appear that contains the required family of curves.

Write a program file to calculate the sum

The algorithm for calculating the sum uses the accumulation of the result, i.e. first the sum is zero ( S= 0), then into a variable k unit is entered, 1/ k! is added to S and the result is put back into S. Further k increases by one, and the process continues until the last term is 1/10!. The file program Fordem2, shown in the following listing, calculates the desired amount.

Listing of the file-program Fordem2 for calculating the sum

% file-program for sum calculation
% 1/1!+1/2!+ … +1/10!

% Reset S to accumulate amount
S = 0;
% accumulation of the amount in the cycle
for k = 1:10
S = S + 1/factorial(k);
End
% print result to command window S

Type the program file in the M-file editor, save it in the current directory in the Fordem2.m file and execute. The result will be displayed in the command window, because in the last line of the file-program S contained without a semicolon to display the value of the variable S

Note that the rest of the lines in the file-program that might cause intermediate values ​​to be displayed are terminated with a semicolon to suppress output to the command window.

The first two lines with comments are not accidentally separated by an empty line from the rest of the program text. They are displayed when the user, using the help command from the command line, receives information about what Fordem2 is doing.

>>helpFordem2
file-program for calculating the sum
1/1!+1/2!+ … +1/10!

When writing file programs and file functions, don't neglect comments!
All variables used in the file program become available in the working environment. They are so-called global variables. On the other hand, the file program can use all the variables entered in the working environment.

Consider the problem of calculating the sum, similar to the previous one, but depending on the variable x

To calculate this amount in the Fordem2 file program, you need to change the line inside the for loop to

S = S + x.^k/factorial(k);

Before running the program, you must define a variable x on the command line with the following commands:

>> x = 1.5;
>>Fordem2
S=
3.4817

As x it can be a vector or a matrix, since element-wise operations were used in the Fordem2 file program when accumulating the sum.

Before launching Fordem2, it is necessary to assign to a variable x some value, and to calculate the sum, for example, from fifteen terms, you will have to make changes to the text of the file program. It is much better to write a generic file function that will have the value as input arguments x and the upper limit of the amount, and the output - the value of the amount S(x). The function file sumN is shown in the following listing.

Listing file-function for sum calculation

function S = sumN(x, N)
% file function to calculate sum
% x/1!+x^2/2!+ … +x^N/N!
% usage: S = sumN(x, N)

% reset S to accumulate amount
S = 0;
% accumulation of the amount in the cycle
for m = 1:1:N
S = S + x.^m/factorial(m);
end

The user can find out about the use of the sumN function by typing help sumN at the command line. The first three lines with comments will be displayed in the command window, separated from the text of the function file by an empty line.

Note that file function variables are not global (the m in function file is sumN). Attempting to view the value of the variable m from the command line results in a message that m is not defined. If there is a global variable with the same name in the working environment, defined from the command line or in a file program, then it is not related in any way to a local variable in the file function. As a rule, it is better to write your own algorithms in the form of file functions so that the variables used in the algorithm do not change the values ​​of the global environment variables of the same name.

For loops can be nested within each other, but the variables of the nested loops must be different.

The for loop is useful for performing repeated similar actions when their number is predetermined. A more flexible while loop allows you to get around this limitation.

6.2. while loop statement

Consider an example for calculating the sum, similar to the example from the previous paragraph. It is required to find the sum of a series for a given x(expansion in series):
.

The sum can be accumulated as long as the terms are not too small, let's say more modulo. The for loop is not enough here, since the number of terms is not known in advance. The solution is to use a while loop that runs as long as the condition of the loop is true:

while loop condition
MatLab commands
end

In this example, the loop condition assumes that the current term is greater than . The greater-than sign (>) is used to write this condition. The text of the file function mysin, which calculates the sum of a series, is shown in the following listing.

Listing 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

S = 0;
k = 0;
while abs(x.^(2*k+1)/factorial(2*k+1))>1.0e-10
S = S + (-1)^k*x.^(2*k+1)/factorial(2*k+1);
k = k + 1;
end

Please note that the while loop, unlike for, does not have a loop variable, so we had to assign zero to k before the beginning of the loop, and increase k by one inside the loop.
The while loop condition can contain more than just the > sign. To set the conditions for the execution of the cycle, other relational operations are also allowed, as shown in Table. one.

Table 1. Relationship operations

More complex conditions are specified using logical operators. For example, the condition consists in the simultaneous fulfillment of two inequalities and , and is written using the logical operator and

and(x >= -1, x< 2)

or equivalently with &

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

Logical operators and examples of their use are given in Table. 2.

Table 2. Logical operators

Operator

Writing to MatLab

Equivalent notation

Logic "AND"

and(x< 3, k == 4)

(x< 3) & (k == 4)

Logical "OR"

Or(x==1,x==2)

(x == 1) | (x==2)

Negative "NOT"

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 a small value of the current term may never be fulfilled and the program will loop. Perform the summation by adding a limit to the number of terms in the while loop condition of the mysin function file:

while (abs(x.^(2*k+1)/factorial(2*k+1))>1.0e-10)&(k<=10000))

or in the equivalent form

while and(abs(x.^(2*k+1)/factorial(2*k+1))>1.0e-10), k<=10000)

The organization of repetitive actions in the form of cycles makes the program simple and understandable, however, it is often necessary to execute one or another block of commands depending on certain conditions, i.e. use the branching algorithm.

6.3. Conditional if statement

Conditional operator if allows you to create a branching algorithm for executing commands, in which, under certain conditions, the corresponding block of statements or MatLab commands works.

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-elseif-else construct to write branching algorithms.
Let it be required to evaluate the expression . Let's say you're doing calculations in real numbers and you want to display a warning that the result is a complex number. Before calculating the function, you should check the value of the argument x, and display a warning in the command window if the modulus x does not exceed one. Here it is necessary to use a conditional if statement, the application of which in the simplest case looks like this:

if condition
MatLab commands
end

If the condition is met, then the MatLab commands placed between if and end are implemented, and if the condition is not met, then the transition to the commands located after end takes place. When recording a condition, the operations given in Table 1 are used. one.

The function file that checks the value of an argument is shown in the following listing. The warning command is used to display a warning in the command window.

Rfun file function listing that checks the value of the argument

function f = Rfun(x)
% calculates sqrt(x^2-1)
% prints a warning if the result is complex
% use y = Rfun(x)

% argument check
if abs(x)<1
warning("complex result")
end
% function evaluation
f = sqrt(x^2-1);

Now calling Rfun with an argument less than one will print a warning to the command window:

>> y = Rfun(0.2)
the result is complex
y=
0 + 0.97979589711327i

The function file Rfun only warns that its value is complex, and all calculations with it continue. If the complex result means a calculation error, then the execution of the function should be terminated using the error command instead of warning.

6.4. Branch statement if-elseif-else

In general, the application of the if-elseif-else branch operator looks like this:

if condition 1
MatLab commands
elseif condition 2
MatLab commands
elseif condition 3
MatLab commands
. . . . . . . . . . .
elseif condition N
MatLab commands
else
MatLab commands
end

Depending on the performance of one or the other N conditions, the corresponding branch of the program works if none of the N conditions, then the MatLab commands placed after the else are implemented. After executing any of the branches, the statement exits. There can be any number of branches or only two. In the case of two branches, the terminating else is used and the elseif is skipped. The statement must always end with end.
An example of using the if-elseif-else statement is shown in the following listing.

function ifdem(a)
% example using if-elseif-else statement

if (a == 0)
warning("a equals zero")
elseif a == 1
warning("and equals one")
elseif a == 2
warning("equal to two")
elseif a >= 3
warning("a, greater than or equal to three")
else
warning("a is less than three, and is not equal to zero, one, two")
end

6.5. Branch operator switch

A switch statement can be used to perform multiple selection or branching. . It is an alternative to the if-elseif-else statement. In general, the application of the switch branch statement looks like this:

switch switch_expression
case value 1
MatLab commands
case value 2
MatLab commands
. . . . . . . . . . .
case value N
MatLab commands
case (value N+1, value N+2, ...)
MatLab commands
. . . . . . . . . . . .
case (value NM+1, value NM+2,…)
otherwise
MatLab commands
end

In this statement, the value of the switch_expression is first evaluated (it can be a scalar numeric value or a character string). This value is then compared with the values: value 1, value 2, ..., value N, value N+1, value N+2, ..., value NM+1, value NM+2, ... (which can also be numeric or string) . If a match is found, then the MatLab commands following the corresponding case keyword are executed. Otherwise, the MatLab commands between otherwise and end keywords are executed.

There can be any number of lines with the keyword case, but there must be one line with the otherwise keyword.

After the execution of any of the branches, the switch exits, while the values ​​specified in other cases are not checked.

The use of switch is illustrated by the following example:

function demswitch(x)
a = 10/5 + x
switch a
case-1
warning("a = -1")
case 0
warning("a = 0")
case 1
warning("a = 1")
case (2, 3, 4)
warning("a is 2 or 3 or 4")
otherwise
warning("a is not equal to -1, 0, 1, 2, 3, 4")
end

>>x=-4
demswitch(x)
a =
1
warning: a = 1
>>x=1
demswitch(x)
a =
6
warning: a is not equal to -1, 0, 1, 2, 3, 4

6.6. Loop Break Statement break

When organizing cyclic calculations, care should be taken that no errors occur inside the cycle. For example, let's say an array x is given, consisting of integers, and it is required to form a new array y according to the rule y(i) = x(i+1)/x(i). Obviously, the problem can be solved with a for loop. But if one of the elements of the original array is equal to zero, then the division will result in inf, and subsequent calculations may be useless. This situation can be prevented by exiting the loop if the current value of x(i) is zero. The following program fragment demonstrates the use of the break statement to break a loop:

for x = 1:20
z=x-8;
if z==0
break
end
y = x/z
end

As soon as the variable z becomes 0, the loop is terminated.

The break statement allows you to prematurely terminate the execution of for and while loops. Outside of these loops, the break statement does not work.

If the break statement is used in a nested loop, then it exits only from the inner loop.

1. Lesson 23: Introduction to MATLAB extension packages

Lesson number 23.

Introduction to MATLAB extension packages

    Listing extension packages

    Simulinc for Windows

    Symbolic Mathematics Package

    Math Packages

    Packages for analysis and synthesis of control systems

    System identification packages

    Additional features of the Simulinc package

    Signal and Image Processing Packages

    Other application packages

In this lesson, we will briefly get acquainted with the main means of professional expansion of the system and its adaptation to the solution of certain classes of mathematical and scientific and technical problems - with the extension packages of the MATLAB system. Undoubtedly, at least part of these packages should be devoted to a separate training course or guide, perhaps more than one. For most of these extensions, separate books have been published abroad, and the volume of documentation for them amounts to hundreds of megabytes. Unfortunately, the scope of this book allows only a brief walk through the expansion packs to give the reader an idea of ​​where the system is heading.

2. Listing extension packages

Listing extension packages

The complete composition of the MATLAB 6.0 system contains a number of components, the name, version number and creation date of which can be displayed with the ver command:

MATLAB Version 6.0.0.88 (R12) on PCWIN MATLAB License Number: 0

MATLAB Toolbox

Version 6.0

06-0ct-2000

Version 4.0

Version 4.0

04-0ct-2000

Stateflow Coder

Version 4.0

04-0ct-2000

Real-Time Workshop

Version 4.0

COMA Reference Blockset

Version 1.0.2

Communication Blockset

Version 2.0

Communication Toolbox

Version 2.0

Control System Toolbox

Version 5.0

DSP Blockset

Version 4.0

Data Acquisition Toolbox

Version 2.0

05-0ct-2000

Database Toolbox

Version 2.1

Datafeed Toolbox

Version 1.2

Dials & Gauges Blockset

Version 1.1

Filter Design Toolbox

Version 2.0

Financial Derivatives Toolbox

Version 1.0

Financial Time Series Toolbox

Version 1.0

Financial Toolbox

Version 2.1.2

Fixed Point Blockset

Version 3.0

Fuzzy Logic Toolbox

Version 2.1

GARCH Toolbox

Version 1.0

Image Processing Toolbox

Version 2.2.2

Instrument Control Toolbox

Version 1.0

LMI Control Toolbox

Version 1.0.6

MATLAB Compiler

Version 2.1

MATLAB Report Generator

Version 1.1

Mapping Toolbox

Version 1.2


Version 1.0.5

Motorola DSP Developer's Kit

Version 1.1

Ol-Sep-2000

Mi-Analysis and Synthesis Toolbox

Version 3.0.5

Neural Network Toolbox

Version 4.0

Nonlinear Control Design Blockset

Version 1.1.4

Optimization Toolbox

Version 2.1

Partial Differential Equation Toolbox

Version 1.0.3

Power System Blockset

Version 2.1

Real-Time Workshop Ada Coder

Version 4.0

Real-Time Workshop Embedded Coder

Version 1.0

Requirements Management Interface

Version 1.0.1

Robust Control Toolbox

Version 2.0.7

SB2SL (converts SystemBuild to Simu

Version 2.1

Signal Processing Toolbox

Version 5.0

Simulink Accelerator

Version 1.0

Model Differentiation for Simulink and...

Version 1.0

Simulink Model Coverage Tool

Version 1.0

Simulink Report Generator

Version 1.1

Spline Toolbox

Version 3.0

Statistics Toolbox

Version 3.0

Symbolic Math Toolbox

Version 2.1.2


Version 5.0

Wavelet Toolbox

Version 2.0

Version 1.1

xPC Target Embedded Option

Version 1.1

Please note that almost all extension packages in MATLAB 6.0 are up to date and date back to 2000. Their description has been noticeably expanded, which in PDF format already occupies many more than tens of thousands of pages. Below is a brief description of the main expansion packs.

3 Simulink for Windows

Simulink for Windows

The Simulink extension package is used for simulation modeling of models consisting of graphic blocks with specified properties (parameters). Model components, in turn, are graphic blocks and models that are contained in a number of libraries and can be transferred to the main window with the mouse and connected to each other by the necessary links. Models can include signal sources of various types, virtual recording devices, graphical animation tools. Double-clicking on a model block displays a window with a list of its parameters that the user can change. Running a simulation provides mathematical modeling of the constructed model with a clear visual representation of the results. The package is based on the construction of block diagrams by transferring blocks from the library of components to the editing window of the model created by the user. The model is then run for execution. On fig. 23.1 shows the process of modeling a simple system - a hydraulic cylinder. Control is carried out using virtual oscilloscopes - in fig. 23.1 shows the screens of two such oscilloscopes and the window of a simple model subsystem. It is possible to model complex systems consisting of many subsystems.

Simulink composes and solves the equations of state of the model and allows you to connect a variety of virtual measuring instruments to the desired points in it. The clarity of presentation of simulation results is striking. A number of examples of using the Simulink package have already been given in Lesson 4. The previous version of the package is described in sufficient detail in books. The main innovation is the processing of matrix signals. Separate Simulink performance packages have been added, such as Simulink Accelerator for compiling model code, Simulink profiler for code analysis, etc.

Rice. 23.1. Example of Hydraulic Cylinder System Simulation Using Simulink Extension

1.gif

Image:

1b.gif

Image:

4. Real Time Windows Target and Workshop

Real Time Windows Target and Workshop

The powerful real-time simulation subsystem connected to Simulink (with additional hardware in the form of computer expansion boards), represented by the Real Time Windows Target and Workshop expansion packs, is a powerful tool for managing real objects and systems. In addition, these extensions allow you to create executable model codes. Rice. 4.21 in Lesson 4 shows an example of such a simulation for a system described by non-linear van der Pol differential equations. The advantage of such modeling is its mathematical and physical clarity. In Simulink model components, you can specify not only fixed parameters, but also mathematical relationships that describe the behavior of the models.

5. Report Generator for MATLAB and Simulink

Report Generator for MATLAB and Simulink

Report Generators - a tool introduced in MATLAB 5.3.1, provides information about the operation of the MATLAB system and the Simulink extension package. This tool is very useful when debugging complex computational algorithms or when modeling complex systems. Report generators are launched with the Report command. Reports can be presented as programs and edited.

Report generators can run commands and program fragments included in reports and allow you to control the behavior of complex calculations.

6. Neural Networks Toolbox

Neural Networks Toolbox

A package of applied programs containing tools for building neural networks based on the behavior of a mathematical analogue of a neuron. The package provides powerful support for the design, training, and simulation of many well-known network paradigms, from basic perceptron models to state-of-the-art associative and self-organizing networks. The package can be used to explore and apply neural networks to problems such as signal processing, nonlinear control, and financial modeling. The ability to generate portable C-code using Real Time Workshop is provided.

The package includes more than 15 known types of networks and learning rules, allowing the user to choose the most appropriate paradigm for a particular application or research task. For each type of architecture and training rules, there are functions for initialization, training, adaptation, creation and simulation, demonstration, and an example network application.

For controlled networks, you can choose direct or recurrent architecture using a variety of learning rules and design methods such as perceptron, backpropagation, Levenberg backpropagation, radial basis networks, and recurrent networks. You can easily change any architecture, learning rules or transition functions, add new ones - and all this without writing a single line in C or FORTRAN. An example of using the package for letter image recognition was given in Lesson 4. A detailed description of the previous version of the package can be found in the book.

7. Fuzzy Logic Toolbox

Fuzzy Logic Toolbox

The Fuzzy Logic application package refers to the theory of fuzzy (fuzzy) sets. Support is provided for modern methods of fuzzy clustering and adaptive fuzzy neural networks. The graphical tools of the package allow you to interactively monitor the behavior of the system.

Key features of the package:

  • definition of variables, fuzzy rules and membership functions;
  • interactive viewing of fuzzy inference;
  • modern methods: adaptive fuzzy inference using neural networks, fuzzy clustering;
  • interactive dynamic simulation in Simulink;
  • portable C code generation with Real-Time Workshop.

This example clearly shows the differences in the behavior of the model with and without fuzzy logic.

8. Symbolic Math Toolbox

Symbolic Math Toolbox

A package of application programs that give the MATLAB system fundamentally new capabilities - the ability to solve problems in a symbolic (analytical) form, including the implementation of exact arithmetic of arbitrary bit depth. The package is based on the use of the symbolic mathematics core of one of the most powerful computer algebra systems - Maple V R4. Provides symbolic differentiation and integration, calculation of sums and products, expansion in Taylor and Maclaurin series, operations with power polynomials (polynomials), calculation of polynomial roots, analytical solution of nonlinear equations, various symbolic transformations, substitutions and much more. Has direct access commands to the Maple V kernel.

The package allows you to prepare procedures with the syntax of the programming language of the Maple V R4 system and install them in the MATLAB system. Unfortunately, in terms of the capabilities of symbolic mathematics, the package is far inferior to specialized computer algebra systems, such as the latest versions of Maple and Mathematica.

9. Packages of mathematical calculations

Math Packages

MATLAB includes many extension packages that enhance the mathematical capabilities of the system, increase the speed, efficiency, and accuracy of calculations.

10.NAG Foundation Toolbox

NAG Foundation Toolbox

One of the most powerful math function libraries created by The Numerical Algorithms Group, Ltd. The package contains hundreds of new features. The names of the functions and the syntax for calling them are borrowed from the well-known NAG Foundation Library. As a result, advanced NAG FORTRAN users can easily work with the NAG package in MATLAB. The NAG Foundation library provides its functions in the form of object codes and corresponding m-files to call them. The user can easily modify these MEX files at the source code level.

The package provides the following features:

    polynomial roots and modified Laguerre method;

    calculation of the sum of a series: discrete and Hermitian-discrete Fourier transform;

    ordinary differential equations: Adams and Runge-Kutta methods;

    partial differential equations;

    interpolation;

    calculation of eigenvalues ​​and vectors, singular numbers, support for complex and real matrices;

    approximation of curves and surfaces: polynomials, cubic splines, Chebyshev polynomials;

    minimization and maximization of functions: linear and quadratic programming, extrema of functions of several variables;

    decomposition of matrices;

    solution of systems of linear equations;

    linear equations (LAPACK);

    statistical calculations, including descriptive statistics and probability distributions;

    correlation and regression analysis: linear, multidimensional and generalized linear models;

    multidimensional methods: principal components, orthogonal rotations;

    random number generation: normal distribution, Poisson, Weibull and Koschie distributions;

    nonparametric statistics: Friedman, Kruskal-Wallis, Mann-Whitney; О time series: one-dimensional and multivariate;

    approximations of special functions: integral exponent, gamma function, Bessel and Hankel functions.

Finally, this package allows the user to create FORTRAN programs that link dynamically with MATLAB.

11. Spline Toolbox

A package of applied programs for working with splines. Supports 1D, 2D, and multidimensional spline interpolation and approximation. Provides presentation and display of complex data and graphics support.

The package allows you to perform interpolation, approximation and transformation of splines from B-form to piecewise polynomial, interpolation by cubic splines and smoothing, performing operations on splines: calculating the derivative, integral and mapping.

The Spline package is equipped with the B-spline programs described in "A Practical Guide to Splines" by Carl Deboer, creator of splines and author of the Spline package. The package's features, combined with the MATLAB language and detailed user guide, make it easy to understand splines and apply them effectively to a variety of problems.

The package includes programs for working with the two most common forms of spline representation: B-form and piecewise polynomial form. The B-form is convenient at the stage of building splines, while the piecewise polynomial form is more efficient during constant work with the spline. The package includes functions for creating, displaying, interpolating, fitting and processing splines in B-form and as polynomial segments.

12. Statistics Toolbox

Statistics Toolbox

A package of applied programs on statistics that dramatically expands the capabilities of the MATLAB system in the field of implementing statistical calculations and statistical data processing. It contains a very representative set of tools for generating random numbers, vectors, matrices and arrays with different distribution laws, as well as many statistical functions. It should be noted that the most common statistical functions are included in the core of the MATLAB system (including functions for generating random data with uniform and normal distribution). Key features of the package:

    descriptive statistics;

    probability distributions;

    parameter estimation and approximation;

    hypothesis testing;

    multiple regression;

    interactive stepwise regression;

    Monte Carlo simulation;

    approximation on intervals;

    statistical process control;

    experiment planning;

    response surface modeling;

    approximation of a nonlinear model;

    principal component analysis;

    statistical charts;

    graphical user interface.

The package includes 20 different probability distributions, including t (Student's), F, and Chi-square. Fitting, graphical display of distributions, and a way to calculate best fit are provided for all types of distributions. There are many interactive tools for dynamic visualization and data analysis. There are specialized interfaces for modeling the response surface, visualization of distributions, generation of random numbers and level lines.

13. Optimization Toolbox

Optimization Toolbox

A package of applied problems - for solving optimization problems and systems of nonlinear equations. Supports the main methods for optimizing the functions of a number of variables:

    unconditional optimization of nonlinear functions;

    least squares method and non-linear interpolation;

    solution of non-linear equations;

    linear programming;

    quadratic programming;

    conditional minimization of nonlinear functions;

    minimax method;

    multicriteria optimization.

A variety of examples demonstrate the effective use of package functions. With their help, you can also compare how the same problem is solved by different methods.

14. Partial Differential Equations Toolbox

Partial Differential Equations Toolbox

A very important software package containing many functions for solving systems of partial differential equations. Gives effective means for solving such systems of equations, including stiff ones. The package uses the finite element method. The package's commands and graphical interface can be used for mathematical modeling of partial differential equations for a wide range of engineering and scientific applications, including problems of strength of materials, calculations of electromagnetic devices, problems of heat and mass transfer and diffusion. Key features of the package:

    a full-fledged graphical interface for processing partial differential equations of the second order;

    automatic and adaptive grid selection;

    setting boundary conditions: Dirichlet, Neumann and mixed;

    flexible problem statement using MATLAB syntax;

    fully automatic meshing and finite element size selection;

    nonlinear and adaptive design schemes;

    possibility of visualization of fields of various parameters and solution functions, demonstration of the adopted partition and animation effects.

The package intuitively follows the six steps of solving a PDE using the Finite Element Method. These steps and the corresponding modes of the package are: define geometry (draw mode), specify boundary conditions (boundary conditions mode), select coefficients defining the problem (PDE mode), finite element discretization (mesh mode), specify initial conditions, and solve equations (solution mode), post-processing of the solution (graph mode).

15. Packages for analysis and synthesis of control systems

Packages for analysis and synthesis of control systems

Control System Toolbox

The Control System package is intended for modeling, analysis and design of automatic control systems - both continuous and discrete. The package functions implement traditional transfer function methods and modern state-space methods. Frequency and time responses, zero and pole patterns can be quickly calculated and displayed on the screen. The package includes:

    a complete set of tools for the analysis of MIMO-systems (multiple inputs - multiple outputs) systems;

    temporal characteristics: transfer and transition functions, response to arbitrary action;

    frequency characteristics: diagrams of Bode, Nichols, Nyquist, etc.;

    feedback development;

    design of LQR/LQE controllers;

    characteristics of models: controllability, observability, lowering the order of models;

    support for latency systems.

Additional model building functions allow you to design more complex models. The time response can be calculated for a pulse input, a single step, or an arbitrary input signal. There are also functions for analyzing singular values.

An interactive environment for comparing the time and frequency response of systems provides the user with graphical controls for simultaneously displaying responses and switching between them. Various response characteristics can be calculated, such as ramp-up time and ramp-down time.

The Control System package contains tools for selecting feedback options. Among the traditional methods: the analysis of singular points, the determination of the gain and attenuation. Among modern methods: linear-quadratic regulation, etc. The Control System package includes a large number of algorithms for designing and analyzing control systems. In addition, it has a customizable environment and allows you to create your own m-files.

16. Nonlinear Control Design Toolbox

Nonlinear Control Design Toolbox

Nonlinear Control Design (NCD) Blockset implements a dynamic optimization method for designing control systems. This tool, designed for use with Simulink, automatically tunes system parameters based on user-defined timing constraints.

The package uses mouse drag and drop to change timing constraints directly on plots, allowing easy setting of variables and specifying uncertain parameters, provides interactive optimization, implements Monte Carlo simulation, supports SISO (one input, one output) and MIMO control system design , allows simulation of interference cancellation, tracking and other types of responses, supports repetitive parameter problems and control problems for systems with delay, allows selection between satisfied and unattainable constraints.

17 Robust Control Toolbox

Robust Control Toolbox

The Robust Control package includes tools for designing and analyzing multi-parameter stable control systems. These are systems with simulation errors, whose dynamics are not fully known or whose parameters may change during simulation. Powerful algorithms of the package allow you to perform complex calculations, taking into account changes in many parameters. Package features:

    synthesis of LQG controllers based on the minimization of the uniform and integral norms;

    multi-parameter frequency response;

    building a state space model;

    transformation of models based on singular numbers;

    lowering the order of the model;

    spectral factorization.

The Robust Control package builds on the features of the Control System package while providing an advanced set of algorithms for designing control systems. The package provides a transition between modern control theory and practical applications. It has many features that implement modern methods for designing and analyzing multi-parameter robust controllers.

Manifestations of uncertainties that violate the stability of systems are diverse - noise and disturbances in signals, inaccuracy of the transfer function model, non-simulated nonlinear dynamics. The Robust Control package allows you to evaluate the multi-parameter stability boundary under various uncertainties. Among the methods used: the Perron algorithm, analysis of the features of transfer functions, etc.

The Robust Control package provides various methods for designing feedbacks, including: LQR, LQG, LQG/LTR, etc. The need to reduce the order of the model arises in several cases: lowering the order of an object, lowering the order of a controller, modeling large systems. A qualitative procedure for lowering the order of a model must be numerically stable. The procedures included in the Robust Control package successfully cope with this task.

18. Model Predictive Control Toolbox

Model Predictive Control Toolbox

The Model Predictive Control package contains a complete set of tools for implementing a predictive control strategy. This strategy was developed to solve practical problems of managing complex multi-channel processes in the presence of restrictions on state variables and control. Predictive control methods are used in the chemical industry and to control other continuous processes. The package provides:

    modeling, identification and diagnostics of systems;

    support for MISO (many inputs - one output), MIMO, transient responses, state-space models;

    system analysis;

    converting models into various forms of representation (state space, transfer functions);

    providing tutorials and demos.

The predictive approach to control problems uses an explicit linear dynamic model of an object to predict the impact of future changes in control variables on the behavior of an object. The optimization problem is formulated as a quadratic programming problem with constraints, which is solved anew at each simulation step. The package allows you to create and test controllers for both simple and complex objects.

The package contains more than fifty specialized functions for the design, analysis and simulation of dynamic systems using predictive control. It supports the following types of systems: pulsed, continuous and discrete in time, state space. Various types of perturbations are processed. In addition, restrictions on input and output variables can be explicitly included in the model.

Simulation tools allow for tracking and stabilization. Analysis tools include the calculation of closed loop poles, frequency response, and other characteristics of the control system. To identify the model in the package, there are functions for interacting with the System Identification package. The package also includes two Simulink functions that allow you to test non-linear models.

19. mu - Analysis and Synthesis

(Mu)-Analysis and Synthesis

The p-Analysis and Synthesis package contains functions for designing robust control systems. The package uses uniform-norm optimization and singular parameter and. This package includes a graphical interface to simplify block operations when designing optimal controllers. Package properties:

  • designing regulators that are optimal in the uniform and integral norm;
  • estimation of real and complex singular parameter mu;
  • D-K iterations for approximate mu-synthesis;

    graphical interface for closed loop response analysis;

    means of lowering the order of the model;

    direct linking of individual blocks of large systems.

The state space model can be created and analyzed based on system matrices. The package supports work with continuous and discrete models. The package has a full-fledged graphical interface, including: the ability to set the range of input data, a special window for editing the properties of D-K iterations and a graphical representation of the frequency response. Has functions for matrix addition, multiplication, various transformations and other operations on matrices. Provides the ability to downgrade models.

20. Stateflow

Stateflow is an event-driven systems modeling package based on finite automata theory. This package is intended to be used in conjunction with the Simulink Dynamic Systems Simulation package. In any Simulink model, you can insert a Stateflow diagram (or SF diagram) that will reflect the behavior of the components of the simulation object (or system). SF-chart is animated. By its highlighted blocks and connections, one can trace all the stages of the simulated system or device and make its work dependent on certain events. Rice. 23.6 illustrates the simulation of the behavior of the car in the event of an emergency on the road. Under the car model, you can see the SF diagram (more precisely, one frame of its work).

To create SF diagrams, the package has a convenient and simple editor, as well as user interface tools.

21. Quantitative Feedback Theory Toolbox

Quantitative Feedback Theory Toolbox

The package contains functions for creating robust (stable) systems with feedback. QFT (Quantitative Feedback Theory) is an engineering technique that uses the frequency representation of models to meet various quality requirements in the presence of uncertain object characteristics. The method is based on the observation that feedback is necessary in cases where some characteristics of the object are uncertain and/or unknown perturbations are applied to its input. Package features:

    evaluation of the frequency boundaries of the uncertainty inherent in feedback;

    graphical user interface that allows you to optimize the process of finding the required feedback parameters;

    functions for determining the influence of various blocks introduced into the model (multiplexers, adders, feedback loops) in the presence of uncertainties;

    support for modeling analog and digital feedback loops, cascades and multi-loop circuits;

    resolution of uncertainty in the parameters of the object using parametric and non-parametric models or a combination of these types of models.

Feedback theory is a natural continuation of the classical frequency approach to design. Its main goal is to design simple, low order, minimum bandwidth controllers that perform well in the presence of uncertainties.

The package allows you to calculate various parameters of feedbacks, filters, test controllers both in continuous and discrete space. It has a user-friendly graphical interface that allows you to create simple controllers that meet the requirements of the user.

QFT allows you to design controllers that meet different requirements despite changes in model parameters. The measured data can be directly used to design controllers, without the need to identify complex system responses.

22. LMI Control Toolbox

LMI Control Toolbox

The LMI (Linear Matrix Inequality) Control package provides an integrated environment for setting and solving linear programming problems. The package, originally intended for designing control systems, allows you to solve any linear programming problems in almost any field of activity where such problems arise. Key features of the package:

    solving problems of linear programming: problems of compatibility of constraints, minimization of linear goals in the presence of linear constraints, minimization of eigenvalues;

    study of linear programming problems;

    graphic editor of linear programming tasks;

    setting limits in symbolic form;

    multicriteria design of regulators;

    stability test: quadratic stability of linear systems, Lyapunov stability, Popov criterion test for non-linear systems.

The LMI Control package contains modern simplex algorithms for solving linear programming problems. Uses a structural representation of linear constraints, which increases efficiency and minimizes memory requirements. The package has specialized tools for analysis and design of control systems based on linear programming.

With the help of linear programming problem solvers, you can easily check the stability of dynamic systems and systems with non-linear components. Previously, this type of analysis was considered too complex to implement. The package even allows such a combination of criteria, which was previously considered too complicated and solvable only with the help of heuristic approaches.

The package is a powerful tool for solving convex optimization problems that arise in areas such as control, identification, filtering, structural design, graph theory, interpolation and linear algebra. The LMI Control package includes two types of graphical user interface: the Linear Programming Problem Editor (LMI Editor) and the Magshape interface.LMI Editor allows you to set limits in symbolic form, and Magshape provides the user with convenient tools for working with the package.

23. System identification packages

System identification packages

System Identification Toolbox

The System Identification package contains tools for creating mathematical models of dynamic systems based on observed input and output data. It has a flexible graphical interface to help organize data and create models. The identification methods included in the package are applicable to a wide range of problems, from designing control systems and signal processing to analyzing time series and vibration. The main properties of the package:

    simple and flexible interface;

    data pre-processing, including pre-filtering, removal of trends and biases; О choice of data range for analysis;

    response analysis in the time and frequency domain;

    display of zeros and poles of the transfer function of the system;

    residual analysis when testing the model;

    construction of complex diagrams, such as the Nyquist diagram, etc.

The graphical interface simplifies data pre-processing as well as the interactive model identification process. It is also possible to work with the package in command mode and using the Simulink extension. The operations of loading and saving data, selecting a range, deleting offsets and trends are performed with minimal effort and are located in the main menu.

The presentation of data and identified models is organized graphically in such a way that the user can easily return to the previous step of work during interactive identification. For beginners, it is possible to view the next possible steps. Graphical tools allow the specialist to find any of the previously obtained models and evaluate its quality in comparison with other models.

Starting with measuring the output and input, you can create a parametric model of the system that describes its behavior in dynamics. The package supports all traditional model structures, including autoregression, Box-Jenkins structure, and others. It supports linear state-space models that can be defined in both discrete and continuous space. These models can include an arbitrary number of inputs and outputs. The package includes functions that can be used as test data for identified models. The identification of linear models is widely used in the design of control systems when it is required to create a model of an object. In signal processing problems, models can be used for adaptive signal processing. Identification methods are also successfully used for financial applications.

24. Frequency Domain System Identification Toolbox

Frequency Domain System Identification Toolbox

The Frequency Domain System Identification package provides specialized tools for identifying linear dynamic systems by their time or frequency response. Frequency methods are aimed at identifying continuous systems, which is a powerful addition to the more traditional discrete technique. The package methods can be applied to problems such as modeling electrical, mechanical, and acoustic systems. Package properties:

    periodic perturbations, crest factor, optimal spectrum, pseudorandom and discrete binary sequences;

    calculation of confidence intervals of amplitude and phase, zeros and poles;

    identification of continuous and discrete systems with unknown delay;

    model diagnostics, including modeling and calculation of residuals;

    converting models to the System Identification Toolbox format and vice versa.

Using the frequency approach, one can achieve the best model in the frequency domain; avoid discretization errors; it is easy to isolate the constant component of the signal; significantly improve the signal-to-noise ratio. To obtain disturbing signals, the package provides functions for generating binary sequences, minimizing the magnitude of the peak and improving the spectral characteristics. The package provides identification of continuous and discrete linear static systems, automatic generation of input signals, as well as a graphical representation of zeros and poles of the transfer function of the resulting system. Functions for testing the model include calculating residuals, transfer functions, zeros and poles, running the model using test data.

25. Additional MATLAB Extension Packages

Additional MATLAB Extension Packages

Communication Toolbox

A package of applied programs for building and modeling various telecommunication devices: digital communication lines, modems, signal converters, etc. It has a rich set of models for a wide variety of communication and telecommunication devices. Contains a number of interesting examples of modeling communication tools, such as a v34 modem, a modulator to provide single-sideband modulation, etc.

26. Digital Signal Processing (DSP) Blockset

Digital Signal Processing (DSP) Blockset

A package of applied programs for designing devices using digital signal processors. First of all, these are high-performance digital filters with a frequency response (AFC) specified or adapted to the signal parameters. The results of simulation and design of digital devices using this package can be used to build high-performance digital filters on modern digital signal processing microprocessors.

27 Fixed Point Blockset

Fixed Point Blockset

This special package is focused on modeling digital control systems and digital filters as part of the Simulink package. A special set of components allows you to quickly switch between fixed and floating point (point) calculations. You can specify 8-, 16-, or 32-bit word lengths. The package has a number of useful properties:

    use of unsigned or binary arithmetic;

    user selection of the position of the binary point;

    automatic setting of the position of the binary point;

    viewing the maximum and minimum ranges of the model signal;

    switching between fixed and floating point calculations;

    overflow correction and availability of key components for fixed-point operations; logical operators, one- and two-dimensional reference tables.

28. Packages for signal and image processing

Signal and Image Processing Packages

Signal Processing Toolbox

A powerful package for the analysis, modeling and design of devices for processing all kinds of signals, providing their filtering and many transformations.

The Signal Processing package provides extremely rich signal processing capabilities for today's scientific and technical applications. The package uses a variety of filtering techniques and the latest spectral analysis algorithms. The package contains modules for the development of linear systems and time series analysis. The package will be useful, in particular, in such areas as audio and video information processing, telecommunications, geophysics, real-time control tasks, economics, finance and medicine. The main properties of the package:

    modeling of signals and linear systems;

    design, analysis and implementation of digital and analog filters;

    fast Fourier transform, discrete cosine and other transformations;

    spectrum estimation and statistical signal processing;

    parametric processing of time series;

    generation of signals of various shapes.

The Signal Processing package is the perfect wrapper for signal analysis and processing. It uses field-proven algorithms selected for maximum efficiency and reliability. The package contains a wide range of algorithms for representing signals and linear models. This set allows the user to be flexible enough to create a signal processing script. The package includes algorithms for converting a model from one view to another.

The Signal Processing package includes a complete set of methods for creating digital filters with a variety of characteristics. It allows you to quickly design high- and low-pass filters, band pass and stop filters, multi-band filters, including Chebyshev, Yule-Walker, elliptical, and others.

The graphical interface allows you to design filters by specifying requirements for them in the drag and drop mode. The following new filter design methods are included in the package:

    a generalized Chebyshev method for designing filters with a non-linear phase response, complex coefficients, or arbitrary response. The algorithm was developed by Maclenan and Karam in 1995;

    constrained least squares allows the user to explicitly control the maximum error (smoothing);

    a method for calculating the minimum filter order with a Kaiser window;

    a generalized Butterworth method for designing low-pass filters with the most uniform pass and attenuation bands.

Based on the optimal Fast Fourier Transform algorithm, Signal Processing has unrivaled performance for frequency analysis and spectral estimation. The package includes functions for computing the discrete Fourier transform, discrete cosine transform, Hilbert transform, and other transforms commonly used in analysis, coding, and filtering. The package implements such spectral analysis methods as the Welch method, the maximum entropy method, etc.

The new graphical interface allows you to view and visually evaluate the characteristics of signals, design and apply filters, perform spectral analysis, exploring the effect of various methods and their parameters on the result. The graphical interface is particularly useful for visualizing time series, spectra, time and frequency responses, and zero and pole locations of system transfer functions.

The Signal Processing package is the basis for solving many other problems. For example, by combining it with the Image Processing package, 2D signals and images can be processed and analyzed. Together with the System Identification package, the Signal Processing package allows you to perform parametric modeling of systems in the time domain. In combination with the Neural Network and Fuzzy Logic packages, many tools can be created for data processing or classification extraction. The signal generation tool allows you to create pulse signals of various shapes.

29. Higher-Order Spectral Analysis Toolbox

Higher-Order Spectral Analysis Toolbox

The Higher-Order Spectral Analysis package contains special algorithms for signal analysis using higher order moments. The package provides ample opportunities for the analysis of non-Gaussian signals, as it contains algorithms, perhaps the most advanced methods for analyzing and processing signals. Key features of the package:

    evaluation of high-order spectra;

    traditional or parametric approach;

    amplitude and phase recovery;

    adaptive linear forecasting;

    harmonic recovery;

    delay estimation;

    block signal processing.

The Higher-Order Spectral Analysis package allows you to analyze signals corrupted by non-Gaussian noise and processes occurring in nonlinear systems. High order spectra, defined in terms of high order moments of the signal, contain additional information that cannot be obtained using only autocorrelation or power spectrum analysis of the signal. High-order spectra allow:

    suppress additive color Gaussian noise;

    identify non-minimum-phase signals;

    highlight the information due to the non-Gaussian nature of the noise;

    detect and analyze non-linear properties of signals.

Possible applications of high-order spectral analysis include acoustics, biomedicine, econometrics, seismology, oceanography, plasma physics, radar and locators. The core features of the package support high-order spectra, cross spectral estimation, linear prediction models, and lag estimation.

30. Image Processing Toolbox

Image Processing Toolbox

The Image Processing suite provides scientists, engineers and even artists with a wide range of tools for digital image processing and analysis. Closely linked to the MATLAB application development environment, the Image Processing Toolbox frees you from time-consuming coding and debugging of algorithms, allowing you to focus on solving the main scientific or practical problem. The main properties of the package:

    restoration and selection of image details;

    work with a selected area of ​​the image;

    image analysis;

    linear filtering;

    image conversion;

    geometric transformations;

    increase the contrast of important details;

    binary transformations;

    image processing and statistics;

    color transformations;

    palette change;

    converting image types.

The Image Processing package provides ample opportunities for creating and analyzing graphic images in the MATLAB environment. This package provides an extremely flexible interface to manipulate images, interactively develop graphics, visualize datasets, and annotate results for white papers, reports, and publications. Flexibility, combination of package algorithms with such a feature of MATLAB as a matrix-vector description make the package very well suited for solving almost any tasks in the development and presentation of graphics. Examples of using this package in the MATLAB system environment were given in lesson 7. MATLAB includes specially designed procedures to increase the efficiency of the graphical shell. In particular, the following features can be noted:

    interactive debugging when developing graphics;

    profiler to optimize the execution time of the algorithm;

    tools for building an interactive graphical user interface (GUI Builder) to speed up the development of GUI templates, allowing you to customize it for user tasks.

This package allows the user to spend significantly less time and effort on creating standard graphics and thus concentrate on the important details and features of the images.

MATLAB and the Image Processing package are maximally adapted for the development, implementation of new ideas and user methods. To do this, there is a set of interfaced packages aimed at solving all sorts of specific tasks and tasks in an unconventional setting.

The Image Processing package is currently used extensively by over 4,000 companies and universities around the world. At the same time, there is a very wide range of tasks that users solve using this package, such as space research, military development, astronomy, medicine, biology, robotics, materials science, genetics, etc.

31 Wavelet Toolbox

The Wavelet package provides the user with a complete set of programs for studying multidimensional non-stationary phenomena using wavelets (short wave packets). Relatively recently created methods of the Wavelet package extend the user's capabilities in those areas where the Fourier decomposition technique is usually used. The package can be useful for applications such as speech and audio signal processing, telecommunications, geophysics, finance and medicine. The main properties of the package:

    advanced graphical user interface and a set of commands for analysis, synthesis, filtering of signals and images;

    conversion of multidimensional continuous signals;

    discrete signal conversion;

    decomposition and analysis of signals and images;

    a wide range of basis functions, including correction of boundary effects;

    batch processing of signals and images;

    analysis of signal packets based on entropy;

    filtering with the ability to set hard and soft thresholds;

    optimal signal compression.

Using the package, you can analyze features that other signal analysis methods miss, i.e. trends, outliers, breaks in high-order derivatives. The package allows you to compress and filter signals without obvious losses, even in cases where you need to save both high and low frequency components of the signal. There are also compression and filtering algorithms for batch signal processing. Compression programs allocate the minimum number of coefficients that represent the original information most accurately, which is very important for the subsequent stages of the compression system. The following wavelet basis sets are included in the package: Biorthogonal, Haar, Mexican Hat, Mayer, etc. You can also add your own bases to the package.

An extensive user manual explains how to work with package methods, with numerous examples and a full reference section.

32. Other application packages

Other application packages

Financial Toolbox

Quite relevant for our period of market reforms is a package of applied programs for financial and economic calculations. It contains many functions for calculating compound interest, bank deposit operations, calculating profits and much more. Unfortunately, due to numerous (although, in general, not very fundamental) differences in financial and economic formulas, its use in our conditions is not always reasonable - there are many domestic programs for such calculations, for example, Accounting 1C. But if you want to connect to the databases of financial news agencies - Bloom-berg, IDC through the Datafeed Toolbox MATLAB package, then, of course, be sure to use the financial MATLAB extension packages.

The Financial package is the basis for solving many financial problems in MATLAB, from simple calculations to full-scale distributed applications. The Financial package can be used to calculate interest rates and profits, analyze derivative income and deposits, and optimize an investment portfolio. Key features of the package:

    data processing;

    dispersion analysis of the effectiveness of the investment portfolio;

    time series analysis;

    calculation of profitability of securities and evaluation of rates;

    statistical analysis and market sensitivity analysis;

    calculation of annual income and calculation of cash flows;

    depreciation and depreciation methods.

Given the importance of the date of a particular financial transaction, the Financial package includes several functions for manipulating dates and times in various formats. The Financial package allows you to calculate prices and returns when investing in bonds. The user has the ability to set non-standard, including irregular and inconsistent with each other, schedules for debit and credit operations and the final settlement when repaying bills. Economic sensitivity functions can be calculated taking into account different maturities.

Algorithms of the Financial package for calculating cash flow indicators and other data reflected in financial accounts make it possible to calculate, in particular, interest rates on loans and credits, profitability ratios, credit receipts and final accruals, evaluate and predict the value of an investment portfolio, calculate depreciation indicators etc. Package functions can be used taking into account positive and negative cash flows (cash-flow) (excess of cash receipts over payments or cash payments over receipts, respectively).

The Financial package contains algorithms that allow you to analyze the investment portfolio, dynamics and economic sensitivity factors. In particular, when determining the efficiency of investments, the functions of the package make it possible to form a portfolio that satisfies the classical problem of G. Markowitz. The user can combine the package's algorithms to calculate Sharpe ratios and rates of return. Analysis of dynamics and economic sensitivities allows the user to identify positions for straddle trades, hedging and fixed rate trades. The Financial package also provides extensive opportunities for the presentation and presentation of data and results in the form of graphs and charts traditional for the economic and financial fields of activity. Funds can be displayed in decimal, bank and percentage formats at the request of the user.

33. Mapping Toolbox

The Mapping package provides a graphical and command interface for analyzing geographic data, displaying maps, and accessing external geographic data sources. In addition, the package is suitable for working with many well-known atlases. All these tools, in combination with MATLAB, provide users with all the conditions for productive work with scientific geographic data. Key features of the package:

    visualization, processing and analysis of graphic and scientific data;

    more than 60 map projections (direct and inverse);

    design and display of vector, matrix and composite maps;

    graphical interface for building and processing maps and data;

    global and regional data atlases and interfacing with high resolution government data;

    geographic statistics and navigation functions;

    three-dimensional representation of maps with built-in highlighting and shading;

    converters for popular geographic data formats: DCW, TIGER, ETOP5.

The Mapping package includes over 60 of the most widely used projections, including Cylindrical, Pseudocylindrical, Conic, Polyconic and Pseudoconic, Azimuth and Pseudoazimuth. Front and rear projections are possible, as well as non-standard projection types specified by the user.

In the Mapping package card any variable or set of variables that reflects or assigns a numerical value to a geographic point or area is called. The package allows you to work with vector, matrix and mixed data maps. A powerful graphical interface enables interactive map manipulation, such as the ability to move the pointer over an object and click on it to get information. MAPTOOL GUI is a complete development environment for map applications.

The most widely known atlases of the world, United States, astronomical atlases are included in the package. The geographic data structure simplifies the extraction and processing of data from atlases and maps. The digital chart of the world (DCW), TIGER, TBASE and ETOP5 formats geographic data structure and external geographic data interfacing features come together to provide a powerful and flexible tool for accessing current and future geographic databases. Careful analysis of geographic data often requires mathematical methods that work in a spherical coordinate system. The Mapping package provides a subset of geographic, statistical, and navigational functions for analyzing geographic data. The navigation features provide ample opportunity to perform movement tasks such as positioning and route planning.

34. Power System Blockset

Data Acquisition Toolbox and Instrument Control Toolbox

Data Acquisition Toolbox - an extension package related to the field of data acquisition through blocks connected to the internal bus of a computer, function generators, spectrum analyzers - in a word, instruments widely used for research purposes to obtain data. They are backed by an appropriate computing base. The new Instrument Control Toolbox allows you to connect instruments and devices with a serial interface and with Public Channel and VXI interfaces.

36. Database toolbox and Virtual Reality Toolbox

Database toolbox and Virtual Reality Toolbox

The speed of the Database toolbox has been increased by more than 100 times, with the help of which information is exchanged with a number of database management systems via ODBC or JDBC drivers:

  • Access 95 or 97 Microsoft;

    Microsoft SQL Server 6.5 or 7.0;

    Sybase Adaptive Server 11;

    Sybase (formerly Watcom) SQL Server Anywhere 5.0;

    IBM DB2 Universal 5.0;

  • Computer Associates Ingres (all editions).

All data is pre-converted to a cell array in MATLAB 6.0. In MATLAB 6.1, you can also use an array of structures. The Visual Query Builder allows you to create arbitrarily complex queries in the SQL dialects of these databases, even without knowledge of SQL. Many heterogeneous databases can be opened in one session.

The Virtual Reality Toolbox package is available starting with MATLAB 6.1. Allows for 3D animation and animation, including Simulink models. Programming language - VRML - virtual reality modeling language (Virtual Reality Modeling Language). The animation can be viewed from any computer equipped with a VRML-enabled browser. Confirms that mathematics is the science of quantitative relationships and spatial forms of any real or virtual worlds.

37.Excel Link

Allows you to use Microsoft Excel 97 as a MATLAB I/O processor. To do this, just install the excllinkxla file supplied by Math Works as an add-in function in Excel. In Excel, you need to type Service > Add-Ins > Browse, select a file in \matlabrl2\toolbox\exlink directory and install it. Now, every time you start Excel, the MATLAB command window will appear, and the Excel control panel will be supplemented with getmatrix, putmatrix, evalstring buttons. To close MATLAB from Excel, just type =MLC1ose() in any Excel cell. To open after executing this command, you must either click on one of the getmatrix, putmatrix, evalstring buttons, or type in Excel Tools> Macro>Run mat! abi ni t. With a range of Excel cells selected with the mouse, you can click on getmatrix and type in the MATLAB variable name. The matrix will appear in Excel. Once you've populated a range of Excel cells with numbers, you can select the range, click on putmatrix, and enter a MATLAB variable name. The operation is thus intuitive. Unlike MATLAB, Excel Link is not case sensitive: I and i, J and j are equivalent.

Call demo examples of expansion packs.

Send your good work in the knowledge base is simple. Use the form below

Students, graduate students, young scientists who use the knowledge base in their studies and work will be very grateful to you.

Posted on http://www.allbest.ru/

  • Introduction
  • 1. Theoretical part
  • 1.1 MATLAB and its relationship with other programming languages
  • 1.2 MatLab and its main components
  • 1.3 A little about working with the MATLAB system
  • 2. Practical part
  • 2.1 Statement of the problem
  • 2.2 History of task development
  • 2.3 Formulas used
  • 2.4 Program code of the task
  • 2.5 Description of the program
  • Conclusion
  • List of sources used
  • INTRODUCTION
  • Modern computer mathematics offers a whole set of integrated software systems and software packages for automating mathematical calculations: Gauss, Derive, Mathcad, Mathematica, etc. The question arises: what place does the MATLAB system take among them?
  • MATLAB is one of the oldest, well-developed systems for automating mathematical calculations, built on advanced representation and application of matrix operations.
  • Over the years, MATLAB has evolved with a variety of users in mind. In the university environment, it was a standard tool for working in various fields of mathematics, engineering and science.
  • The programming language of the MATLAB system is very simple, it contains only a few dozen operators; a small number of operators is compensated by a large number of procedures and functions, the content of which is understandable to a user who has the appropriate mathematical and engineering background.
  • MATLAB includes computing, visualization and programming in a convenient environment where problems and solutions are expressed in a form close to mathematical. Typical uses of MATLAB are: mathematical calculations, algorithm creation, modeling, data analysis, exploration and visualization, scientific and engineering graphics, application development, including GUI creation.
  • Programs written in MATLAB are of two types -- functions and scripts. Functions have input and output arguments, as well as their own workspace for storing intermediate results of calculations and variables. Scripts share a common workspace. Both scripts and functions are not compiled to native code and are saved as text files.
  • In this work, the goal is to consider how a body (or a material point) thrown at an angle to the horizon moves. And also, based on the considered data from mechanics, writing a program that would model this movement. The work includes the creation of motion graphs, graphs of coordinates versus time, as well as the creation of a dynamic model of the motion of a body thrown at an angle to the horizon.

1. THEORETICAL PART

1.1 MATLAB AND ITS RELATIONSHIP WITH OTHER PROGRAMMING LANGUAGES

The MATLAB system was developed by specialists from MathWork Inc. (Nateik, Massachusetts, USA). Although this system was first used in the late 1970s, it became widespread in the late 80s, especially after version 4.0 hit the market. The latest versions of MATLAB are systems that contain many procedures and functions necessary for an engineer and a scientist to perform complex numerical calculations, simulate technical and physical systems, and present the results of these calculations. MATLAB (short for MATrix LABoratory - matrix laboratory) is an interactive system designed to perform engineering and scientific calculations and focused on working with data arrays. The system provides the ability to access programs written in FORTRAN, C and C++.

An attractive feature of the MATLAB system is the presence of built-in matrix and complex arithmetic. The system supports operations with vectors, matrices and data arrays, implements singular and spectral decomposition, calculates the rank and condition numbers of matrices, supports working with algebraic polynomials, solving nonlinear equations and optimization problems, integrating functions in quadratures, numerical integration of differential and difference equations, construction of various graphs, three-dimensional surfaces and level lines.

The MATLAB system provides performance of operations with vectors and matrices even in the direct calculation mode. It can be used as a powerful calculator, which, along with the usual arithmetic and algebraic operations, can use such complex operations as inverting a matrix, calculating its eigenvalues ​​and vectors, solving systems of linear algebraic equations, and many others. A characteristic feature of the system is its openness, that is, the possibility of its modification and adaptation to specific user tasks.

The MATLAB system uses its own M-language, which combines the positive features of various well-known high-level programming languages. The MATLAB system is related to the BASIC language by the fact that it is an interpreter (performs operator-by-operator compilation and program execution without forming a separate executable file), the M-language has a small number of operators, it does not need to declare the types and sizes of variables. From the Pascal language, the MATLAB system borrowed an objective-oriented orientation, that is, such a construction of the language that provides the formation of new types of computational objects based on the types of objects that already exist in the language. New types of objects (in MATLAB they are called classes) can have their own conversion procedures (they define methods of this class), and new procedures can be called using ordinary arithmetic operators and some special symbols that are used in mathematics.

The principles of saving the values ​​of variables in MATLAB are closest to those inherent in the FORTRAN language, namely: all variables are local - they act only within the boundaries of the program unit (procedure, function, or main control program) where they are assigned some specific values. When switching to the execution of another program unit, the values ​​of the variables of the previous program unit are either lost (if the executed program unit is a procedure or function) or become inaccessible (if the executed program is a control program). Unlike BASIC and Pascal, there are no global variables in MATLAB that apply to all program units. But at the same time, the MATLAB language has a feature that is not available in other languages. The MATLAB interpreter allows you to execute several independent programs in the same session, and all the variables used in these programs are common to them and form a single workspace. This makes it possible to more rationally organize complex (cumbersome) calculations by the type of overlay structures.

The above features of the MATLAB system make it a very flexible and easy-to-use computing system.

1.2 MATLAB AND ITS MAIN COMPONENTS

MATLAB is a high performance language for technical calculations. It includes calculations, visualization and programming in a convenient environment where problems and solutions are expressed in a form close to mathematical. A typical use of MATLAB is:

Mathematical calculations;

Creation of algorithms;

Modeling;

Data analysis, research and visualization;

Scientific and engineering graphics;

Application development, including the creation of a graphical interface.

MATLAB is an interactive system in which the main data element is an array. This allows you to solve various problems related to technical calculations, especially those that use matrices and vectors, several times faster than when writing programs using "scalar" programming languages ​​such as C or Fortran. mathematical programming matlab

In MATLAB, specialized groups of programs called toolboxes play an important role. They are very important to most MATLAB users because they allow you to learn and apply specialized methods. Toolboxes are a comprehensive collection of MATLAB functions (M-files) that allow you to solve particular classes of problems. Toolboxes are used for signal processing, control systems, neural networks, fuzzy logic, wavelets, simulation, etc.

The MATLAB system consists of five main parts.

1. MATLAB language. It is a high-level matrix and array language with flow control, functions, data structures, I/O, and object-oriented programming features.

2. MATLAB environment. This is a set of tools and fixtures that a MATLAB user or programmer works with. It includes tools for managing variables in the MATLAB workspace, data input and output, and creating, controlling, and debugging M-files and MATLAB applications.

3. Managed graphics. It is a MATLAB graphics system that 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 fully edit the appearance of graphics, just like when creating a Graphical User Interface (GUI) for MATLAB applications.

4. Library of mathematical functions. It is a vast collection of computational algorithms from elementary functions such as sum, sine, cosine, complex arithmetic to more complex ones such as matrix inversion, eigenvalue finding, Bessel functions, fast Fourier transform.

5. Software interface. This is a library that allows you to write C and Fortran programs that interact with MATLAB. It includes facilities for calling programs from MATLAB (dynamic link), calling MATLAB as a computing tool, and for reading/writing MAT files.

Simulink, a companion program to MATLAB, is an interactive system for simulating nonlinear dynamic systems. It is a mouse-driven environment that allows you to simulate the process by dragging blocks of diagrams on the screen and manipulating them. Simulink works with linear, non-linear, continuous, discrete, multidimensional systems.

Blocksets are add-ons to Simulink that provide block libraries for specialized applications such as communications, signal processing, and power systems.

Real-Time Workshop is a program that allows you to generate C code from block diagrams and run them on various real-time systems.

1.3 A LITTLE ABOUT WORKING WITH THE MATLAB SYSTEM

After you click on the MATLAB icon, a screen will appear in front of you, in the upper part of which there is a line with drop-down menus, a toolbar with buttons that implement the most frequently performed actions (see Fig. 1.1), and in the window itself - a query string in as two characters>>. This is the MATLAB Command Window

Riceunok1. 1 - instrumentalpacommand window box

The standard File drop-down menu contains items such as New for creating new files, Open M-file - opening an existing program file or function file for editing, checking text, or debugging. When using this item, you are offered a standard file selection window, and after selecting the required file, the m-file editor/debugger window opens.

M-files are text files with the extension .m, containing texts of script programs or texts of functions from standard or proprietary libraries. In the editor, you can correct them, set breakpoints for debugging, but remember that in order for a new, corrected version of a function or program to take effect, it is necessary in a standard way (via the File editor menu or using the corresponding button on the editor toolbar / debugger) to save the modified file.

The toolbar (see Figure 1.1) of the command window allows you to perform the required actions by simply clicking on the appropriate button. Most buttons have a standard look and perform standard actions similar to other programs - copying (Copy), opening a file (Open), printing (Print), etc. You should pay attention to the Path Browser button, which allows you to navigate to different directories and make the required directory current, as well as the Workspace Browser button, which allows you to view and edit variables in the workspace.

The help command typed in response to a prompt followed by the Enter key, or a toolbar button with a question mark, lists the functions for which online help is available. help command<имя_функции>allows you to get on-screen help for a specific function.

For example, the help eig command allows you to get online help on the eig function, a function for calculating the eigenvalues ​​of a matrix. You can get acquainted with some of the features of the MATLAB system using the demo command.

In this brief introduction, it should be noted that the main objects - variables that MATLAB works with - are rectangular matrices. This makes it possible to write programs very briefly, making programs easily visible. There are many operations performed on matrices. Of course, the notation of such operations as multiplication and addition of matrices should be memorized. It is pointless to study and memorize all the possibilities "for the future", before they are needed.

If you need to interrupt the work, but save all the variables created in the workspace, then the easiest way to do this is with the save command.<имя_файла>. All variables in binary form are stored in a file<имя_файла>.mat. Subsequently, when you restart the system, you can load the entire workspace using the load command<имя_файла>and continue the calculations from the same place. To clear the work area, use the clear command with no arguments, in which case the entire area is cleared of all variables. If the clear command is followed by a space-separated list of variables, then only the listed variables are removed.

2. PRACTICAL PART

2.1 PROBLEM STATEMENT

The main objective of this course work is: writing a program in the MATLAB system that would simulate the movement of a body thrown at an angle to the horizon.

2.2 HISTORY OF THE PROBLEM

Mechanics (from Greek MzchbnykYu is translated as the art of building machines) is a field of physics that studies the movement of material objects and the interaction between them. The most important branches of mechanics are classical mechanics and quantum mechanics.

The motion of a body thrown at an angle to the horizon must be considered as curvilinear motion, which in turn is one of the sections of mechanics.

The study of the features of such a movement began quite a long time ago, back in the 16th century, and was associated with the appearance and improvement of artillery pieces.

Ideas about the trajectory of artillery shells in those days were pretty funny. It was believed that this trajectory consists of three sections: violent movement, mixed movement and natural movement, in which the cannonball falls on the enemy soldiers from above (see Fig. 2.1).

Rice. 2.1 - Artillery projectile trajectory

The laws of the flight of projectiles did not attract much attention of scientists until long-range guns were invented that sent a projectile through hills or trees - so that the shooter did not see their flight.

At first, ultra-long-range firing from such guns was used mainly to demoralize and intimidate the enemy, and the accuracy of shooting did not play a particularly important role at first.

Close to the correct decision about the flight of cannonballs came the Italian mathematician Tartaglia, he was able to show that the greatest range of projectiles can be achieved when the shot is directed at an angle of 45 ° to the horizon. In his book The New Science, the rules of shooting were formulated, which guided artillerymen until the middle of the 17th century.

However, the complete solution of the problems associated with the movement of bodies thrown horizontally or at an angle to the horizon was carried out by the same Galileo. In his reasoning, he proceeded from two main ideas: bodies moving horizontally and not subject to other forces will maintain their speed; the appearance of external influences will change the speed of the moving body, regardless of whether it was at rest or moving before the start of their action. Galileo showed that the trajectories of projectiles, if we neglect air resistance, are parabolas. Galileo pointed out that during the actual movement of shells, due to air resistance, their trajectory would no longer resemble a parabola: the descending branch of the trajectory would go somewhat steeper than the calculated curve.

Newton and other scientists developed and improved a new theory of shooting, taking into account the increased influence of air resistance forces on the movement of artillery shells. A new science has also appeared - ballistics. Many, many years have passed, and now the projectiles are moving so fast that even a simple comparison of the type of trajectories of their movement confirms the increased influence of air resistance.

In modern ballistics, to solve such problems, electronic computing equipment is used - computers, but for now we will restrict ourselves to a simple case - the study of such a movement in which air resistance can be neglected. This will allow us to repeat Galileo's reasoning almost without any changes.

2.3 FORMULA USED

Let us study the motion of a body thrown with an initial velocity V 0 at an angle b to the horizon, considering it as a material point of mass m. At the same time, we will neglect air resistance, and consider the gravity field to be uniform (Р=const), assuming that the flight range and trajectory height are small compared to the radius of the Earth.

Let's place the origin O in the initial position of the point. Let's direct the Oy axis vertically upwards; we will place the horizontal axis Ox in the plane passing through Oy and the vector V 0 , and draw the Oz axis perpendicular to the first two axes (Fig. 2.2). Then the angle between the vector V 0 and the axis Ox will be equal to b.

Fig.2.2 - Movement of a body thrown at an angle to the horizon.

Let's depict a moving point M somewhere on the trajectory. Only the force of gravity F acts on the point, the projections of which on the coordinate axes are equal:

Substituting these quantities into differential equations and noticing that

etc. after reduction by m we get:

Multiplying both sides of these equations by dt and integrating, we find:

The initial conditions in our problem have the form:

at t=0:

Satisfying the initial conditions, we will have:

Substituting these values C 1 , C 2 And C 3 into the solution found above and replacing Vx, Vy, Vz on the

we come to the equations:

Integrating these equations, we get:

Substituting the initial data gives C 4 =C 5 =C 6 =0, and we finally find the equations of motion of the point M in the form:

It follows from the last equation that the motion occurs in the Oxy plane.

Having the equation of motion of a point, it is possible to determine all the characteristics of a given motion using kinematics methods.

Let us find the time of flight of the body from the starting point to the point of fall.

Flight time:

2.4 PROGRAM CODE FOR THE STATED TASK

clc; %clear command window

v0=36; %starting speed

g=9.81; %acceleration of gravity

k=1;

alpha=pi/3; %angle at which the body is thrown

m=(2*v0*sin(alfa))/g % flight time

while k<5

k=menu("select category", ...

sprintf("dependence of x coordinate on t"), ...

sprintf("dependence of y-coordinate on t"), ...

sprintf("graph of motion of a body thrown at an angle to the horizon"), ...

sprintf("dynamic model of motion of a body thrown at an angle to the horizon"), ...

"output");

if k == 1

t=0:0.001:m;

x=v0*t*cos(alfa);

plot(x);

title("dependence of x coordinate on t");

xlabel("x"); ylabel("y");

elseif k == 2

t=0:0.001:m;

y=v0*t*sin(alfa)-(g*t.^2)/2;

plot(y);

title("dependence of y coordinate on t");

xlabel("x"); ylabel("y");

elseif k == 3

t=0:0.001:m;

x=v0*t*cos(alfa);

y=v0*t*sin(alfa)-(g*t.^2)/2;

plot(x,y);

title("Graph of motion of a body thrown at an angle to the horizon");

xlabel("x"); ylabel("y");

elseif k == 4

t=0:0.001:m;

x=v0*t*cos(alfa);

y=v0*t*sin(alfa)-(g*t.^2)/2;

comet(x,y);

title("dynamic model of the motion of a body thrown at an angle to the horizon");

xlabel("x"); ylabel("y");

end;

end;

2.5 PROGRAM DESCRIPTION

This program contains functions and procedures such as clc, plot, menu, comet, etc., as well as variables and their values.

Let's describe the procedures and functions used in this program:

CLC. Command intended for clearing the command window.

MENU. A convenient tool for choosing one of the alternatives for future computational actions is the menu function, which creates a custom menu window. The menu function should be accessed as follows:

K=MENU("MENU TITLE","alternative 1","alternative 2","alternative n")

Such an appeal leads to the appearance of a menu window (see Fig. 2.3).

Figure 2.3 - Menu window

Program execution is temporarily suspended and the system waits for one of the alternative menu buttons to be selected. After the correct choice, the initial parameter k is assigned a value corresponding to the number of the alternative (1,2…n). In general, the number of alternatives can be up to 32.

WHILE. The loop operator with a precondition looks like this:

While <условие>

<операторы>

end

The statements inside the loop are executed only if the condition after the word while is met. At the same time, among the statements inside the loop, there must be those that change the value of one of the variables.

SPRINT. A function that on each menu button places information about the current value of the corresponding parameter.

IF. In general, the syntax of the conditional jump operator is as follows:

If < condition>

< operators1>

Else

< operators2>

End

This operator works as follows. First, a check is made to see if the specified condition is met. If the test result is positive, the program executes a set of statements <операторы1> . Otherwise, the sequence of statements is executed <операторы2>.

PLOT. The main function that provides plotting on the display screen is plot (see Figure 2.4). The general form of addressing it is as follows:

Plot(x1,y1,s1,x2,y2,s2…)

Here x1,y1 are given vectors, whose elements are arrays of argument values ​​(x1) and functions (y1) corresponding to the first curve of the graph; x2,y2 - arrays of argument values ​​and functions of the second curve, etc. It is assumed that the value of the argument is plotted along the horizontal axis of the graph, and the value of the function is plotted along the vertical axis. Variables s1,s2,… are symbolic (their specification is optional).

Figure 2.4 - Action of the plot function.

TITLE. The procedure by which the title of the graph is set.

XLABEL And YLABEL. Functions that define explanations along the horizontal and vertical axes.

COMET. The procedure comet(x, y) ("comet") builds a plot of dependence y(x) gradually in the form of a comet trajectory. At the same time, the “representing” point on the graph looks like a small comet, which smoothly moves from one point to another.

Ultimately, the program shows how the body moves, thrown at an angle to the horizon. Also in the program you can see the dependence of the body coordinates on time (see Fig. 2.5 and Fig. 2.6), the graph of the body trajectory (see Fig. 2.7) and the body movement model itself (see Fig. 2.8).

Figure 2.5 - Graph of x versus t.

Figure 2.6 - Graph of y versus t.

Figure 2.7 - Graph of the movement of a body thrown at an angle to the horizon.

Figure 2.8 - Dynamic model of the movement of a body thrown at an angle to the horizon.

CONCLUSION

The course project was completed in the MatLab 6.5 environment. The development of the project took place in several stages, consisting in the study of the subject area of ​​the problem; studying the basic laws of mechanics; development of the program itself, which allows simulating the movement of a body thrown at an angle to the horizon.

The result of the work done was a program that implements a model of the movement of a body thrown at an angle to the horizon.

The practical value of the program lies in the fact that it clearly shows how a body thrown at an angle to the horizon moves.

Also, the course work contributed to the development of skills for independent planning and implementation of research work, gaining experience in collecting and processing source material, analyzing scientific and technical literature, reference books, standards and technical documentation, acquiring skills in substantiating design decisions and professional design of project documentation.

LIST OF USED SOURCES

1. Lazarev, Yu. Modeling of processes and systems in MatLab. Training course. / Yu. Lazarev. - St. Petersburg: Peter; Kyiv: BHV Publishing Group, 2005. - 512 p.

2. Aleshkevich, V.A. Mechanics / V.A. Aleshkevich, L.G. Dedenko, V.A. Karavaev. - Academy 2004.

3. Kotkin, G.L. Cherkassky V.S., Computer modeling of physical processes using MATLAB: Proc. allowance / G.L. Kotkin, V.S. Cherkassky. - Novosib. un-t. Novosibirsk, 2001. - 173 p.

Hosted on Allbest.ru

...

Similar Documents

    General characteristics and properties of the Matlab system - a package of applied programs for solving problems of technical calculations. Development of a mathematical model in a given environment, programming of functions for a master influence. GUI design.

    term paper, added 05/23/2013

    Features of work in the command line mode in the Matlab system. Variables and assigning values ​​to them. Complex numbers and calculations in the Matlab system. Calculations using the sqrt function. Incorrect use of functions with complex arguments.

    thesis, added 07/30/2015

    Learning programming in MATLAB. Using the Save and Load commands, input and output statements to work in the command window. Debugging your own programs. MATLAB interface. Differences between a later version of MATLAB and earlier ones. Source Control Interface tool.

    test, added 12/25/2011

    Matlab - matrix laboratory - programming system for scientific and technical calculations. Features of input of vectors. Special matrices, simple commands. Simple examples illustrating the effectiveness of Matlab. Graphical way to solve equations.

    abstract, added 01/05/2010

    Mathematical basis of parallel computing. Parallel Computing Toolbox properties. Development of parallel applications in Matlab. Examples of programming parallel tasks. Calculation of a definite integral. Serial and parallel multiplication.

    term paper, added 12/15/2010

    MATLAB - matrix laboratory - the most advanced programming system for scientific and technical calculations. Variables and elements of xy-graphics. Simple examples illustrating the power of MATLAB. Systems of linear algebraic equations and polynomials.

    training manual, added 01/26/2009

    Creation and representation of symbolic variables in the Matlab program, operations on polynomials and simplification of expressions. An example of substituting a value into a function, solving equations and systems, differentiating, integrating and calculating the limits of functions.

    presentation, added 01/24/2014

    Features and syntax of MATLAB commands, program listing and loop description. The procedure for compiling a program for calculating the coefficients of an algebraic interpolation polynomial and constructing a spline function "glued" from pieces of polynomials of the 3rd order.

    laboratory work, added 07/04/2009

    Analysis of the capabilities of the MATLAB package and its extensions. System programming language. Research of the rectifier device. Simulation of a three-phase transformer. Schematic diagram of an adjustable converter. Possibilities of a flexible digital model.

    presentation, added 10/22/2013

    Numerical integration methods. Characterization of the main components of structural programming. Solution of the task in the high-level language Pascal. Building a graphical solution to the problem in the Matlab package. Problem solving in high-level language C.

Top Related Articles