How to set up smartphones and PCs. Informational portal
  • home
  • In contact with
  • Helping Mathematicians: An Overview of MATLAB. Substituting these quantities into differential equations and noting that

Helping Mathematicians: An Overview of MATLAB. Substituting these quantities into differential equations and noting that

The MATLAB environment includes a high-level command interpreter, 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 memory (Workspace), graphic 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 for execution. The interpreter processes the input and displays the results: numeric and string data, warnings and error messages. The input line is marked with >>. The command window displays numbers, variables entered from the keyboard, and the results of calculations. Variable names must start with a letter. The = sign corresponds to an assignment operation. 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 result of the calculation will appear on the screen in the viewing area:

All variable values ​​calculated during the current session are stored in a specially reserved area of ​​computer memory called the MATLAB Workspace. The clc command can erase the contents of the command window, but it will not affect the contents of the workspace. When there is no need to store a number of variables in the current session, they can be erased from the computer memory using the clear or clear command (name1, name2, ...). The first command removes all variables from memory, and the second removes the variables named name1 and name2. The who command can display a list of all the variables currently in the workspace of the system. 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 a MATLAB session, all previously calculated variables are lost. To save the contents of the MATLAB workspace in a file on the computer disk, you need to execute the menu command File / Save Workspace As ... By default, the file name extension is mat, therefore such files are usually called MAT files. To load the workspace previously saved on the disk into the computer memory, you need to 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 specified by the mantissa and exponent, for example, 2.85093E + 11, where the letter E denotes a power base equal to 10. This basic data type is called double. MATLAB uses the short format by default for outputting real numbers, which displays only four decimal places after the decimal point.

Enter an example from the keyboard:

"Res = 5.345 * 2.868 / 3.14-99.455 + 1.274

Get the result of the calculation:

If you want a complete representation of the real number res, enter the command from the keyboard:

press Enter and get more details:

res = -93.29900636942675

Now all calculation results will be displayed with such high accuracy during this session in the MATLAB environment. If you want to return to the old accuracy 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 type double: addition +, subtraction -, multiplication *, division / and exponentiation ^. The priority in performing arithmetic operations is normal. Operations of the same priority are performed in left-to-right order, but parentheses can change that order.

If there is no need to see the result of evaluating 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, a list of input arguments (they are separated by commas and are inside parentheses following the function name) and a calculated (returned) value. A list of all the elementary mathematical functions available in the system can be obtained by using the help elfun command. Appendix 1 lists the standard real argument functions.

Evaluate an expression that includes the calculation of the arcsine function:

Make sure you get the following output:

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

MATLAB also has boolean functions, functions related to integer arithmetic (rounding to the nearest integer: round, truncating 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 the 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 that is different from the set of all real numbers.

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

Table 1


If the ratio operation is true, its value is equal to 1, and if it is false, it is 0. Relation operations have a lower priority than arithmetic operations.

Type the expression with relation operations on the keyboard and compute

"A = 1; b = 2; c = 3;

»Res = (a

You will get the following output:

Logical operations on real numbers are indicated 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 (one-operand). Logic operations 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 generates 0 (false) only if both operands are false (equal to zero). A NOT operation inverts false to true. Logical operations have the lowest priority.

Complex numbers and complex functions

Complex variables, like real ones, are automatically of type double and do not require any preliminary description. The letters i or j are reserved for writing the imaginary unit. In the case when the coefficient in front of the imaginary unit is not a number, but a variable, be sure to use the multiplication sign 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 can be computed 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 number), 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 valid). The functions of a complex variable are listed in Appendix 1.

With regard to arithmetic operations, nothing new can be said for complex numbers (in comparison with real ones). The same is true for the operations of the relation "equal" and "not equal". The rest of the relation operations produce a result based only on the real parts of these operands.

Enter the expression, get the result and explain it:

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

Logic operations treat operands as false if they are equal to 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, denoted by square brackets. Array elements are placed between parentheses and separated from each other by a space or comma:

"Al =; d =;

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

You can change the elements of an already formed array by applying 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 be equal to the arithmetic mean of the first and third elements. Writing a non-existent element is quite acceptable - it means adding a new element to an already existing array:

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

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

You can define an array by writing all of its elements separately:

"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). Enter the first number of the range, the step (increment) and the end number of the range, separated by a colon. For instance:

"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 final number of the range), type a semicolon. To find out how many elements are in an array, call the length (array name) function.

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

Enter from the keyboard:

»A =

Press ENTER, we get:

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

»A = [;;];

or by horizontal concatenation of column vectors:

»A = [,];

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

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

"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 you start writing the array elements, you 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 size of the array, after which the gradual prescription of the elements with the required 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 the formation of the array X it is necessary to change its dimensions without changing the elements of the array, you can use the reshape (X, M, N) function, where M and N are the new dimensions of the array X

The operation of this function can only be explained based on the way in which MATLAB stores array elements in computer memory. It stores them in a contiguous area of ​​memory ordered by columns: the elements of the first column are located 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's memory: the type of the array (for example, double), the dimension and size of the array, and other service information. This information is sufficient to determine the boundaries of the columns. It follows that to reshape the matrix by the reshape function, it is enough to change only the service information and not touch your own data.

You can swap the rows of the matrix with its columns by the transport operation, which is denoted by the sign. "(Period 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 the internal MATLAB representation is a single-element array. MATLAB allows you to do calculations with huge arrays of numbers as easily as with single numbers, and this is one of the most notable and important advantages of the MATLAB system over other software packages focused on computing and programming. In addition to the memory required to store numeric elements (8 bytes for each in the case of real numbers and 16 bytes in the case of complex numbers), MATLAB automatically allocates memory for control information when creating arrays.

Computing with arrays

In traditional programming languages, computations with arrays are performed element by element in the sense that you need to program each separate operation 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 define expressions extremely compactly, in the calculation of which a huge amount of work is actually performed.

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

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

"A =; B =;

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

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

In addition to the operation. /, Called the operation of the right element-wise division, there is also the operation of the left element-wise division. \. The difference between these operations: the expression A. / B leads to 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 problem in linear algebra - finding the roots of a system of linear equations. For example, if it is required to solve the 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, associated with finding the lengths of vectors and angles between them, with the calculation of scalar and vector products, are easily solved by various means of the MATLAB system. For example, to find the cross product of vectors, a special function cross is used, for example:

"U =; v =;

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

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

Vector length is calculated using dot product and square root function, for example:

»Sqrt (sum (u. * U))

The relations and logical operations discussed earlier for scalars are performed element by element in the case of arrays. Both operands must be of 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 by the example of arithmetic operations.

Among the functions that generate matrices with given properties, the function eye, which produces unit square matrices, as well as the widely used function rand, which generates 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 spaced from 0 to 1.

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

The determinant of a square matrix is ​​calculated using the det function. Among the functions that perform the simplest calculations on arrays, in addition to the sum function considered 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 functions max and min search for the maximum and minimum elements of the arrays, respectively. For vectors, they return a single numeric value, and for matrices, they produce a set of extreme elements calculated for each column. The sort function sorts the elements of one-dimensional arrays in ascending order, and for matrices, it does this sort for each column separately.

MATLAB has the unique ability to perform batch calculations on arrays using ordinary mathematical functions, which in traditional programming languages ​​work only with scalar arguments. As a result, with the help of extremely compact records, convenient for entering from the keyboard in the interactive mode of working with the command window of the MATLAB system, it is possible to perform a large amount of computation. For example, just two short expressions

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

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

Plotting functions

The graphics capabilities of MATLAB are powerful and varied. Let's explore the easiest-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 graphical objects in special graphical windows with the word Figure in the 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, with the cla command only the graph is deleted, bringing the coordinate axes to their standard ranges from 0 to 1).

If you need to draw the second graph "over the first graph", then before the second call of the plot graphic function, you need to execute the hold on command, which is designed to hold the current graphic window:

"X = 0: 0.01: 2; y = sin (x);

Almost the same 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 graphics window

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

The second solution to display multiple plots without conflicting coordinate ranges is to use the subplot function. This function allows you to divide the area of ​​displaying graphic information into several subareas, in each of which you can display the graphs of various functions.

For example, for previously performed calculations with sin and cos functions, plot these two functions in the first subdomain, and the plot of the exp (x) function in the second subdomain of the same graphic window (Fig. 3):

"Subplot (1,2,1); plot (x, y, x, z)

"Subplot (1,2,2); plot (x, w)

Rice. 3. Graphs of functions y = sin (x), z = cos (x) and w = exp (x), built in two subdomains of the same graphical window

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

»Subplot (1,1,1)

If the ranges of the variables along one or both axes are too large for a single plot, you can use the plotting functions in logarithmic scales. The functions semilogx, semilogy and loglog are designed for this.

You can plot the function in polar coordinates (Fig. 4) using the polar graph 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 possibilities associated with managing the appearance of charts - setting the color and style of lines, as well as placing various labels within the graphics window. For example, the commands

"X = 0: 0.1: 3; y = sin (x);

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

allow you to give the graphics the appearance of 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 drawing a line in red (letter r), and a stroke means drawing a solid line. The second style, marked as "ko", means drawing in black (letter k) circles (letter o) in place of the calculated points.

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

In general, the plot (x1, y1, s1, x2, y2, s2, ...) function allows you to combine several graphs of the 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 defines the line type (Table 3). Another marker sets the color (Table 4). The last marker sets the type of "points" to be put (Table 5). Not all three markers can be specified. Then the default markers are used. The order in which the markers are pointed is not essential, that is, "r + -" and "- + r" produce the same result.

Table 3. Markers specifying the line type

Table 4 Markers specifying the line color

Table 5 Markers specifying the 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.


MATLAB sets the limits on the horizontal axis to the values ​​specified by the user for the independent variable. For the dependent variable along 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 the variables along the coordinate axes. This is done using the axis () function.

The xlabel, ylabel, title and text functions are used to put various labels 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 picture, use the text function. The general title for the chart 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 caption 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 within text after the \ (backslash) character.

3D graphics

Each point in space is characterized by three coordinates. A set of points belonging to a certain line in space must be specified in the form of three vectors, the first of which contains the first coordinates of these points, the second vector contains their second coordinates, and the third vector contains 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 a 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. Graph of a helix, plotted using the plot3 function

The same plot3 function can be used to plot 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);

Get a 3D plot of the function (Figure 8).

The plot3 function plots a graph as a set of lines in space, each of which is a section of a three-dimensional surface with planes parallel to the yOz plane. In addition to this simplest function, MATLAB has a number of other functions that allow you to achieve more realism in the image of three-dimensional graphs.

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


Scripts and m-files.

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

After creating the script text, 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, follow the Path / Add to path menu command.

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 work 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 to a file and use them later. The M-file editor is intended for working with M-files. Using this editor, you can create your own functions and call them, including from the command line.

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

Type the 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 now a file named mydemo.m in a subdirectory work of the main MatLab directory by selecting the item Save as menu File editor. To run all the commands contained in the file for execution, select the item Run on the menu Debug. A graphic window will appear on the screen. Figure No.1, containing graphs of functions. If you decide to plot the cosine instead of the 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 convenient 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 the left button, or with the arrow keys while holding down , the first four commands of the program and execute them from point Evaluate Selection menu Text. Please note that only one chart is displayed in the graphics window, corresponding to the executed commands. Remember that to execute some of the commands, select them and press ... Execute the remaining three program commands and monitor the state of the graphics window. Practice it yourself, type in any examples from previous labs in the M-file editor and run them.

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

% plotting sin (x) in a separate window

Multiple files can be opened in the M-file editor at the same time. The transition between files is carried out using the bookmarks 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 the editor of M-files. You can also open the file in the editor using the MatLab edit command from the command line, specifying the file name as an argument, for example:

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

2. Types of M-files

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

You created a program file (procedure file) when you read the previous subsection. All variables declared in the program file become available in the production environment after its execution. Run the file program shown in subsection 2.1 in the M? File editor and type whos in the command line to view the contents of the working environment. The 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 file programs and in commands executed from the command line. The execution of the commands contained in the file program is carried out in two ways:

  • From the M-file editor as described above.
  • From the command line or another program file, while the name of the M-file is used as a command.

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

  • Checks if the command entered is the name of any of the variables defined in the production environment. If a variable is entered, then 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 turns out to be a built-in function, then it is executed.

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

If none of the above actions led to success, then a message is displayed in the command window, for example:

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

Typically, M-files are stored in the user's directory. In order for MatLab to find them, you should set the paths indicating the location of the M-files.

Remark 2

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

3. Setting paths

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

The current directory is determined in a 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 required directory. Adding a directory with all its subdirectories is carried out by clicking on the button Add with Subfolders. MATLAB search path. The search order corresponds to the location of the paths in this field, with the directory located at the top of the list looking first. The search order can be changed or the path to a directory can be deleted altogether, for which select the directory in the field MATLAB search path and determine its position using the following buttons:
Move to Top - move to 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 duplicated by commands. The current directory is set with the cd command, for example cd c: \ users \ igor. The cd command, invoked without an argument, prints the path to the current directory. To set paths, use the path command, invoked with two arguments:

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

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

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

Remark 3

Do not delete paths to directories unnecessarily, especially those whose purpose you are not sure about. Removal may lead to the fact that some of the functions defined in MatLab will become unavailable.

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

Solution option:

1. In the root directory of the disk D the WORK_IVANOV directory is created.
2. The M-file mydemo.m under the name mydemo3.m is written to the WORK_IVANOV directory.
3. A dialog box opens. Set Path menu File working environment MatLab.
4. The 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 carried out by pressing the button Add with Subfolders. The path to the added directory appears in the field MATLAB search path.
6. To memorize the path, press the key Save dialog box Set Path.
7. Checking the correctness of all actions by typing the command mydemo3 from the command line. A graphics window will appear on the screen.

5. File functions

The above file programs are a sequence of MatLab commands, they do not have input and output arguments. To use numerical methods and when programming your own applications in MatLab, you need to be able to compose file functions that perform the necessary actions with input arguments and return the result in output arguments. In this subsection, a few simple examples are discussed to help you understand how to work with file functions. File functions, like file procedures, 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 file function once, and then call it wherever it is necessary to evaluate this function. Open a new file in the M-file editor and type in 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 shown in the listing, the function name is myfun, one input argument is x, and one output is f. The title is followed by function body(in this example, it consists of one line), where its value is calculated. It is important that the calculated value is written to f. The semicolon is included to prevent unnecessary information from being displayed on the screen.

Now save the file in your working directory. Please note that the selection of the item 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

Own functions can be called from a program file and from another file function.

Warning

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

The file function shown in the listing has one significant drawback. Attempting to compute function values ​​from an array results in an error, not an array of values, as happens 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 studied working with arrays, then eliminating this shortcoming will not cause difficulties. You just need to use element-wise operations when calculating the value of a function.
Modify the body of the function as shown in the following listing (do not 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 to the myfun function can be either a number or a vector or a 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 a file program:

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

MatLab provides one more opportunity to work with file-functions - using them as arguments to some commands. For example, a special function fplot is used for plotting a plot, which replaces the sequence of commands shown above. When calling fplot, the name of the function whose graph you want to plot is enclosed in apostrophes, the plotting limits are specified in a two-element row vector

fplot ("myfun",)

Plot myfun plots with plot and fplot on the same axes with hold on. Please note that the plot plotted with fplot more accurately reflects the behavior of the function, since fplot itself selects the step of the argument, decreasing it in the areas of rapid change of the displayed function. Report the results in the lab report.

5.2. File functions with multiple input arguments

Writing file functions with several input arguments is practically the same as in the case of one argument. All input arguments are placed in a comma-separated list. For example, the following listing contains a file function that calculates the length of the radius vector of a point in three-dimensional space
Listing of a file function with several 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 when evaluating functions that return multiple values ​​(in mathematics, they are called vector functions). Output arguments are added to the list of output arguments, separated by commas, and the list itself is enclosed in square brackets. A good example is a function that converts a time in seconds into hours, minutes, and seconds. This file function is shown in the following listing.

Listing of the function for converting seconds into 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 several output arguments, the result should be written into a vector of the appropriate length:

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

6. Fundamentals of programming in MatLab

The file functions and the 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 necessary to write programs in which actions are performed cyclically or, depending on certain conditions, various parts of the programs are executed. Let's consider the main operators that set the sequence of execution of MatLab commands. Operators can be used both in file procedures and in functions, which allows you to create programs with a complex branched structure.

6.1. Loop operator for

The operator is designed to perform a specified 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 the loop variable, start is its initial value, final is the final value, and step is the step by which count is incremented each time the loop is entered. The loop ends as soon as 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 use of the for loop operator using 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 file procedure in the M-file editor and save it in the FORdem1.m file, and run it (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 offers to place statements inside the loop, indented from the left edge. Use this opportunity for the convenience of working with the text of the program.

As a result of FORdem1 execution, a graphic window will appear, which 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. at first the sum is equal to zero ( S= 0), then into a variable k 1 is entered, 1 / is calculated k! is added to S and the result is again entered into S... Further k increases by one, and the process continues until the last term becomes 1/10 !. The file program Fordem2, shown in the following listing, calculates the required amount.

Listing of Fordem2 file program for calculating the sum

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

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

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 program file S contained without semicolon to output the value of the variable S

Note that the rest of the lines in the program file, which could have caused the display of intermediate values, are terminated with a semicolon to suppress the 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 the ones that are displayed when the user, using the help command from the command line, receives information about what Fordem2 is doing.

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

When writing file programs and file functions, do not neglect comments!
All variables used in the program file become available in the production environment. They are so called global variables. On the other hand, all variables entered in the working environment can be used in a program file.

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 starting the program, you must define the variable x at 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-by-element operations were used to accumulate the sum in the file-program Fordem2.

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

Listing of the file function for calculating the sum

function S = sumN (x, N)
% file-function for calculating the sum
% x / 1! + x ^ 2/2! +… + x ^ N / N!
% usage: S = sumN (x, N)

% zeroing S to accumulate the 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 learn about using the sumN function by typing help sumN at the command line. The command window will display the first three lines with comments, separated from the text of the file-function by an empty line.

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

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

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

6.2. While loop statement

Let's 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(series expansion):
.

The sum can be accumulated as long as the terms are not too small, say more in modulus. The for loop is indispensable here, since the number of terms is not known in advance. The way out is to use a while loop, which runs as long as the loop condition is met:

while loop condition
MatLab commands
end

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

Listing of mysin file function calculating sine by series expansion

function S = mysin (x)
% Calculate 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

Note that the while loop, unlike for, does not have a loop variable, so we had to assign zero before the loop began, and inside the loop we increased k by one.
The while loop condition can contain more than only the> sign. To set the conditions for the execution of the cycle, other operations of the relation are also allowed, given 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

Logical "AND"

and (x< 3, k == 4)

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

Logical "OR"

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

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

Denying "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 members 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 on the number of terms to the condition of the while loop of the mysin file function:

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

or in 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 loops makes the program simple and understandable; however, it is often required to execute one or another block of commands depending on certain conditions, i.e. use algorithm branching.

6.3. Conditional if statement

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

The if statement can be used in its simple form to execute a block of commands when a certain condition is satisfied, or in an if-elseif-else construct to write branching algorithms.
Let the expression be evaluated. Suppose you are performing calculations in the realm area and you want to display a warning that the result is a complex number. Before evaluating the function, you should check the value of the argument x, and print a warning in the command window if the module x does not exceed one. Here it is necessary to use the conditional operator if, the application of which in the simplest case looks like this:

if condition
MatLab commands
end

If the condition is met, then 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 occurs. When recording a condition, the operations shown in table are used. one.

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

Listing of the Rfun file function that checks the value of the argument

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

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

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

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

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

6.4. Branching operator if-elseif-else

In general, the application of the branch operator if-elseif-else is as follows:

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 another of N conditions, the corresponding branch of the program runs if none of the N conditions, then the MatLab commands placed after else are implemented. After execution of any of the branches, the operator exits. There can be as many branches as you want, or only two. In the case of two branches, the trailing else is used and the elseif is skipped. The statement must always end with end.
An example of using the if-elseif-else operator is shown in the following listing.

function ifdem (a)
% example of using the operator if-elseif-else

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

6.5. Branch operator switch

The 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 branching operator switch 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 (NM value + 1, NM value + 2, ...)
otherwise
MatLab commands
end

In this operator, the value of switch_expression is first evaluated (it can be a scalar numeric value or a character string). This value is then compared with the following 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 after the corresponding case keyword are executed. Otherwise, MatLab commands located between the otherwise and end keywords are executed.

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

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

The following example illustrates the use of switch:

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 interrupt statement break

When organizing cyclic computations, care should be taken to avoid errors inside the loop. For example, suppose you are given an array x consisting of integers, and you need to form a new array y according to the rule y (i) = x (i + 1) / x (i). Obviously, the task can be accomplished using a for loop. But if one of the elements of the original array is equal to zero, then 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 equal to zero. The following code snippet demonstrates the use of the break statement to interrupt a loop:

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

As soon as z becomes 0, the loop is aborted.

The break statement allows you to prematurely interrupt 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.

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 Problem development history
  • 2.3 Used formulas
  • 2.4 The program code of the task
  • 2.5 Program description
  • 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 MATLAB take among them?
  • MATLAB is one of the oldest, well-developed systems for automating mathematical calculations, built on the advanced representation and application of matrix operations.
  • Over the years MATLAB has evolved with a variety of users in mind. In a university setting, 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; the small number of operators here is compensated by a large number of procedures and functions, the content of which is understandable to the user who has the appropriate mathematical and engineering background.
  • MATLAB includes computing, visualization, and programming in an easy-to-use environment where problems and solutions are expressed in a form that is close to mathematical. Typical uses of MATLAB are: mathematical computing, algorithm creation, modeling, data analysis, exploration and visualization, scientific and engineering graphics, application development, including GUI creation.
  • There are two types of programs written in MATLAB - functions and scripts. Functions have input and output arguments, as well as their own workspace for storing intermediate calculation results and variables. Scripts share a common workspace. Both scripts and functions are not compiled to machine code and are saved as text files.
  • In this work, the goal is to consider how a body (or material point) moves, thrown at an angle to the horizon. And also, based on the considered data from mechanics, writing a program that would simulate 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. (Natick, Massachusetts, USA). Although this system was first used in the late 1970s, it became widespread in the late 1980s, especially after the release of version 4.0 on the market. The latest versions of MATLAB are systems that contain many procedures and functions necessary for an engineer and a scientist to carry out complex numerical calculations, simulate technical and physical systems, and formulate the results of these calculations. MATLAB (short for MATrix LABoratory) is an interactive system designed for performing engineering and scientific calculations and focused on working with data sets. The system provides the ability to access programs written in FORTRAN, C and C ++.

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

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

MATLAB uses its own M-language, which combines the positive properties of various well-known high-level programming languages. The MATLAB system has in common with the BASIC language that it is an interpreter (it compiles and executes the program one by one without forming a separate executable file), the M-language has a small number of operators, there is no 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 already existing in the language. New types of objects (in MATLAB they are called classes) can have their own conversion procedures (they define the methods of this class), and new procedures can be called using ordinary signs of arithmetic operations and some special characters that are used in mathematics.

The principles of storing the values ​​of variables in MATLAB are closest to those inherent in the FORTRAN language, namely: all variables are local - they operate only within the boundaries of that 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 unattainable (if the executed program is a control program). Unlike BASIC and Pascal, MATLAB does not have global variables that affect all program units. But at the same time, MATLAB 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 technical computing language. It includes computing, visualization and programming in a convenient environment, where problems and solutions are expressed in a form close to mathematical. Typical uses for MATLAB are:

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 makes it possible to solve various problems associated with technical calculations, especially in which matrices and vectors are used, 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 as they allow you to learn and apply specialized techniques. 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, modeling, 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. It is a collection of tools and fixtures that a MATLAB user or programmer works with. It includes tools for manipulating variables in the MATLAB workspace, data input and output, and creating, monitoring, and debugging M-files and MATLAB applications.

3. Guided 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 completely edit the appearance of graphics, just like when you create 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, and fast Fourier transform.

5. Programming interface. It is a library that allows you to write C and Fortran programs that interact with MATLAB. It includes facilities for invoking programs from MATLAB (dynamic linking), invoking MATLAB as a computational 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 a process by dragging and dropping blocks of diagrams on the screen and manipulating them. Simulink works with linear, nonlinear, continuous, discrete, multidimensional systems.

Blocksets are add-ons to Simulink that provide block libraries for specialized applications such as communications, signal processing, 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 MATLAB

After you clicked on the MATLAB icon, a screen will appear in front of you, at the top 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 line in as two characters >>. This is the MATLAB command window

Riceunok1. 1 - Instrumentalnanel command window

The standard File drop-down menu contains items such as New to create new files, Open M-file - to open 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-files editor / debugger window opens.

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

The toolbar (see Fig. 1.1) of the command window allows you to perform the required actions by simply clicking on the appropriate button. Most of the buttons have a standard appearance and perform standard actions similar to other programs - these are copying (Copy), opening a file (Open), printing (Print), etc. You should pay attention to the Path Browser button, which allows you to lay paths 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 query, terminated by pressing the Enter key, or the toolbar button with a question mark, provides a list of functions for which online help is available. Help command<имя_функции>provides on-screen help for a specific function.

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

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

If you need to interrupt the work, but save all the variables created in the workspace, then the easiest way to do this is using the save command<имя_файла>... All variables in binary are stored in a file<имя_файла>.mat. Subsequently, when rebooting the system, you can load the entire workspace using the load command<имя_файла>and continue 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 STATEMENT OF THE PROBLEM

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 PROBLEM DEVELOPMENT

Mechanics (from the Greek. MzchbnykYu 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 sections of mechanics are classical mechanics and quantum mechanics.

The movement of a body thrown at an angle to the horizon must be considered as a curvilinear movement, which in turn is one of the branches 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 emergence and improvement of artillery pieces.

The ideas about the trajectory of movement 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 nucleus falls on the enemy soldier from above (see Fig. 2.1).

Rice. 2.1 - Trajectory of movement of artillery shells

The laws of the flight of projectiles did not receive much attention from scientists until long-range weapons were invented that sent a projectile through hills or trees so that the shooter could not see them fly.

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

The Italian mathematician Tartaglia came close to the correct decision on the flight of cannonballs, 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 "New Science" were formulated the rules of fire, which guided the gunners until the middle of the seventeenth 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 basic ideas: bodies moving horizontally and not being influenced by other forces will maintain their speed; the appearance of external influences will change the speed of a moving body, regardless of whether it was at rest or moving before the beginning of their action. Galileo showed that the trajectories of the projectiles, if we neglect the air resistance, are parabolas. Galileo pointed out that with the real movement of the shells, due to air resistance, their trajectory will no longer resemble a parabola: the descending branch of the trajectory will go somewhat steeper than the calculated curve.

Newton and other scientists developed and improved a new theory of firing, taking into account the increased influence of air resistance forces on the movement of artillery shells. A new science 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 computers are 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 with almost no changes.

2.3 USED FORMULAS

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. In this case, the air resistance will be neglected, and the gravity field will be considered uniform (P = const), assuming that the flight range and trajectory height are small compared to the Earth's radius.

Place the origin O at the starting position of the point. Let's direct the Oy axis vertically up; the horizontal Ox axis is located in the plane passing through Oy and the vector V 0, and the Oz axis is drawn perpendicular to the first two axes (Figure 2.2). Then the angle between the vector V 0 and the Ox axis will be equal to b.

Figure 2.2 - The movement of a body thrown at an angle to the horizon.

Draw a moving point M somewhere on the trajectory. The point is acted upon only by the force of gravity F, the projections of which on the coordinate axes are equal:

Substituting these quantities into differential equations and noting 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 are as follows:

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:

Substitution of 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:

From the last equation it follows 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 the methods of kinematics.

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

Flight time:

2.4 PROGRAM CODE OF THE SUPPLIED PROBLEM

clc; % clear command window

v0 = 36; %starting speed

g = 9.81; %acceleration of gravity

k = 1;

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

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

while k<5

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

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

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

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

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

"exit");

if k == 1

t = 0: 0.001: m;

x = v0 * t * cos (alfa);

plot (x);

title ("dependence of the 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 the 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 the movement 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 DESCRIPTION OF THE PROGRAM

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 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 like this:

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

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

Figure 2.3 - Menu window

The program is temporarily suspended and the system waits for one of the menu buttons with alternatives to be selected. After correct selection, 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. A loop operator with a precondition looks like this:

While <условие>

<операторы>

end

The statements inside the loop are executed only if the condition written after the word while is fulfilled. Moreover, among the operators inside the loop, there must necessarily be those that change the value of one of the variables.

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

IF... In general, the syntax of the conditional branch 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 result of the check is positive, the program executes a set of statements <операторы1> ... Otherwise, the sequence of statements is executed <операторы2>.

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

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

Here x1, y1 are given vectors, the elements of which are arrays of values ​​of the argument (x1) and functions (y1) corresponding to the first curve of the graph; х2, у2 - arrays of values ​​of the argument 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 along the vertical axis. The 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 chart is set.

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

COMET... The comet (x, y) procedure ("comet") plots the dependence of y (x) gradually in the form of the trajectory of a comet. In this case, the "representing" point on the graph looks like a small comet, which smoothly moves from one point to another.

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

Figure 2.5 - Graph of dependence of x on t.

Figure 2.6 - Graph of dependence of y on t.

Figure 2.7 - Graph of 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 carried out in the MatLab 6.5 environment. The development of the project took place in several stages, consisting in studying 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 the 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 is moving when it is thrown at an angle to the horizon.

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

LIST OF USED SOURCES

1. Lazarev, Y. Modeling of processes and systems in MatLab. Training course. / Yu. Lazarev. - SPb .: Peter; Kiev: Publishing group BHV, 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: Textbook. allowance / G.L. Kotkin, V.S. Cherkassky. - Novosib. un-t. Novosibirsk, 2001 .-- 173 p.

Posted on Allbest.ru

...

Similar documents

    General characteristics and properties of the Matlab system - a package of applied programs for solving technical computing problems. Development of a mathematical model in a given environment, programming functions for the reference action. GUI interface 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 the later version of MATLAB and earlier versions. Source Control Interface tool.

    test, added 12/25/2011

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

    abstract, added 01/05/2010

    The mathematical basis for parallel computing. Parallel Computing Toolbox properties. Development of parallel applications in Matlab. Examples of programming parallel tasks. Calculation of a definite integral. Sequential 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 to illustrate the effectiveness of MATLAB. Systems of linear algebraic equations and polynomials.

    manual, added 01/26/2009

    Creation and representation of symbolic variables in Matlab, 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 third-order polynomials.

    laboratory work, added 07/04/2009

    Analysis of the capabilities of the MATLAB package and its extensions. System programming language. Study of the rectifier device. Modeling a three-phase transformer. Schematic diagram of an adjustable converter. Flexible digital model capabilities.

    presentation added on 10/22/2013

    Numerical integration methods. Characteristics of the main components of structured programming. Solving the problem in high-level language Pascal. Building a graphical solution to the problem in the Matlab package. Solving the problem in high-level language C.

Instructions

There are several modes of operation in the MATLAB environment. The easiest is to enter commands directly into the command window ( Command Window).
If it is not visible in the program interface, then you need to open it. You can find the command window through the menu Desktop -> Command Window.
For example, let us enter the commands "x =; y = sqrt (x); plot (y);" into this window one after the other, and press the "Enter" key ( Enter). The program will instantly create the X variables, create the Y variable and calculate its values ​​according to the given function, and then plot its graph.
Using the "Up" and "Down" keyboard arrows in the command window, we can switch between all entered commands, immediately change them if necessary, and by pressing Enter again send the MATLAB environment for execution.
Conveniently? Undoubtedly. And most importantly - very quickly. All these actions take a few seconds.
But what if you need more complex team organization? If you need a cyclic execution of some commands? Entering commands manually one at a time and then looking for them in history for a long time can be quite tedious.

To make life easier for a scientist, engineer or student, the editor window ( Editor). Let's open the editor window via the menu Desktop -> Editor.
Here you can create new variables, build graphs, write programs (scripts), create components for exchange with other environments, create applications with a user interface (GUI), and edit existing ones. But we are currently interested in writing a program that contains functions for reuse in the future. Therefore, we go to the menu File and choose New -> M-File.

Let's write a simple program in the editor field, but let's complicate it a little:

function draw_plot (x)
y = log (x); % Set the first function
subplot (1, 2, 1), plot (x, y); % We build the first graph
y = sqrt (x); % Set the second function
subplot (1, 2, 2), plot (x, y); % We build the second graph

We have added a second function and will display two graphs at once next to each other. A percent sign indicates comments in MATLAB.
Let's not forget to save the program. The standard file extension with the Matlab program is * .m.
Now close the editor and the graph window that we built earlier.

Go back to the command window.
You can clear the command history so that unnecessary information does not distract us. To do this, right-click on the command entry field and select the item Clear Command Window.
The X variable remained after the previous experiment, we did not change or delete it. Therefore, you can immediately enter into the command window:
draw_plot (x);
You will see that MATLAB will read our function from the file and execute it by drawing a graph.

Those who deal with higher mathematics know very well what kind of mathematical "monsters" you sometimes have to face. For example, calculating some giant triple integral can take a lot of time, mental strength and non-regenerating nerve cells. Of course, it's very interesting to challenge the integral and take it. But what if the integral threatens to take you instead? Or worse, was the cubic trinomial spinning out of control and raging? You wouldn't wish that on an enemy either.


Previously, there were only two options: to spit on everything and go for a walk, or to engage in a multi-hour battle with the integral. Well, to whom many hours, to whom many minutes - who studied how. But that's not the point. The twentieth century and the inexorably moving progress offer us a third way, namely, they allow us to take the most complex integral "in a quick way". The same goes for solving all kinds of equations, plotting function graphs in the form of cubic hyperboloids, etc.

For such extraordinary, but periodically occurring situations among students, there is a powerful mathematical weapon. Meet those who don't know yet - the MATLAB software package.

Matlab will both solve the equation, and approximate, and plot the function. Do you understand what this means, friends?

This means that it is one of the most powerful data processing packages available today. The name stands for MatrixLaboratory. Matrix Laboratory, if in russian . The capabilities of the program cover almost all areas of mathematics. So, using matlab, you can:

  • Perform all kinds of operations on matrices, solve linear equations, work with vectors;
  • Calculate the roots of polynomials of any degree, perform operations on polynomials, differentiate, extrapolate and interpolate curves, build graphs of any functions;
  • Conduct statistical analysis of data using digital filtering, statistical regression;
  • Solve differential equations. In partial derivatives, linear, nonlinear, with boundary conditions - it doesn't matter, matlab will solve everything;
  • Perform integer arithmetic operations.

In addition to all this, MATLAB's capabilities allow you to visualize data up to the construction of three-dimensional graphs and the creation of animated videos.

Our description of matlab, of course, is far from complete. In addition to the capabilities and functions provided by the manufacturer, there are a huge number of matlab tools written by simply enthusiasts or other companies.

MATLAB as a programming language


It is also a programming language used directly when working with the program. We will not go into details, let's just say that programs written in MATLAB come in two types: functions and scripts.


The main working file of the program is the M-file. This is an endless text file, and it is in it that the actual programming of calculations takes place. By the way, don't be intimidated by this word - you don't need to be a professional programmer to work in MATLAB.

M-files are divided into

  • M-scripts. An M script is the simplest type of M file and has no input or output arguments. This file is used to automate repetitive calculations.
  • M-functions. M-functions are M-files that allow input and output arguments.

In order to clearly show how work is done in MATLAB, we will give an example of creating a function in matlab below. This function will calculate the average of the vector.
f unction y = average (x)
% AVERAGE Average value of vector elements.
% AVERAGE (X), where X is a vector. Calculates the average of the elements in a vector.
% If the input argument is not a vector, an error is generated.
= size (x);
if (~ ((m == 1) | (n == 1)) | (m == 1 & n == 1))
error ("The input array must be a vector")
end
y = sum (x) / length (x); % The actual calculation

The function definition line tells the MATLAB system that the file is an M-function and also defines a list of input arguments. So, the definition line of the average function looks like this:
function y = average (x)
Where:

  1. function is a keyword defining an M-function;
  2. y is the output argument;
  3. average - function name;
  4. x is an input argument.

So, to write a function in matlab, you need to remember that every function in MATLAB contains a function definition line like the one below.

Of course, such a powerful package is needed not only to make life easier for students. At present, MATLAB, on the one hand, is very popular among specialists in many scientific and engineering fields. On the other hand, the ability to work with large matrices makes MATLAB an indispensable tool for financial analysts, allowing you to solve many more problems than, for example, the well-known Excel. You can read more about that in the review article.

Disadvantages of working with MATLAB


What are the difficulties in working with MATLAB? There is perhaps only one difficulty. But fundamental. In order to fully reveal the capabilities of MATLAB and easily solve the problems facing you, you will have to sweat and first deal with the matlab itself (how to create a file, how to create a function, etc.). And this is not so easy, because power and wide possibilities require sacrifices.

With all the will, one cannot say that MATLAB is -simple program. Nevertheless, we hope that all of the above will be a sufficient argument in order to start mastering it.

And finally. If you do not know why everything in your life has gone this way and not otherwise, ask the matlab about it. Just type “why” at the command line. He will answer. Try it!

Now you know the possibilities of Matlab. In education, MATLAB is often used in teaching numerical methods and linear algebra. Many students cannot do without it when processing the results of an experiment carried out in the course of laboratory work. For quick and high-quality mastering of the basics of working with MATLAB, you can always turn to, at any time ready to answer any of your questions.

Top related articles