• MATLAB: tool of the future or an expensive toy. Matlab program description

    Most developers have difficulty understanding both its syntax and capabilities. The thing is that the language is directly related to a popular software product, the cost of which can reach amazing values. So, the main question is: is the Matlab language itself so good? And can it be useful for you?

    Usage

    Let's start not with a standard excursion into history and a discussion of the pros and cons of the language, but with the MATLAB/Simulink software environment - the only place where the hero of this text can be useful. Just imagine graphic editor, in which you can realize any of your ideas without having several years of experience and relevant education behind you. And having created a diagram of interaction between tools once, you will get a high-quality script for repeated use.

    MATLAB is just such an editor in the data world. The scope of its application is infinitely wide: IoT, finance, medicine, space, automation, robotics, wireless systems and much, much more. In general almost unlimited possibilities on data collection and visualization, as well as forecasting, but only if it is possible to purchase the appropriate package.

    As for the price, there is almost no upper limit, but the lower limit is around $99. To snatch such a powerful product for relatively little money, you need to be a university student. And of course you will get a rather limited product.

    Features of the language

    The MATLAB language is a tool that ensures the interaction of an operator (often not even a programmer) with all available opportunities analysis, collection and presentation of data. It has obvious pros and cons characteristic of a language living in a closed ecosystem.

    Flaws:

      A slow and overloaded language with operators, commands, and functions, the main purpose of which is to improve visual perception.

      Narrowly focused. There is no other software platform where MATLAB is useful.

      High cost of software. If you are not a student, either get ready to empty your pockets or cross the line of the law. And even if you are a student, the price is decent.

      Low demand. Despite the great interest in MATLAB in almost every field, only a few actually and legally use it.

    Advantages:

      The language is easy to learn and has a simple and understandable syntax.

      Huge opportunities. But this is rather an advantage of the product as a whole.

      Frequent updates, usually noticeable positive transformations occur at least a couple of times a year.

      The software environment allows you to convert it into “fast” code in C, C++.

    Target Audience

    Of course, not everyone needs MATLAB. Despite its wide range of applications, it is difficult to imagine that the average application developer would need knowledge of this language. MATLAB is extremely useful in areas that require particularly robust data processing, such as autopilot systems in automobiles or aircraft avionics systems.

    That is, if you are not much of a programmer, but one way or another your profession is related to the need software processing data, then a MATLAB/Simulink product with the appropriate language can greatly simplify your everyday tasks.

    Literature

    We conclude the review of the language, as always, with a list of educational literature. Of course, among them you will not find books exclusively on the language, but this will only make the perception of the language easier:

    Do you have experience with MATLAB? And which one?

    For those who want to become a programmer - .

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

    Calculations are carried out in the command window in dialog mode. The user enters commands or executes text files in MATLAB. The interpreter processes the input and produces results: numeric and string data, warnings and error messages. The input line is marked with >>. The command window displays numbers and variables entered from the keyboard, as well as calculation results. Variable names must begin 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 calculation result will appear on the screen in the viewing area:

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

    After finishing a session with MATLAB, all previously calculated variables are lost. To save the contents of the MATLAB system 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, which is why such files are usually called MAT files. To load a workspace previously saved on disk into the computer’s memory, you need to execute the menu command: File / Load Workspace ....

    Real numbers and double data type

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

    Enter an example from the keyboard:

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

    Get the calculation result:

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

    press Enter and get more detailed information:

    res = -93.29900636942675

    Now all calculation results will be displayed with such high accuracy during a given session in the MATLAB system environment. If you want to return to the old precision of the visual representation of real numbers in the command window before terminating the current work 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 double variables: addition +, subtraction -, multiplication *, division / and exponentiation ^. Priority in execution arithmetic operations ordinary. Operations of the same priority are performed in left-to-right order, but parentheses can change this order.

    If there is no need to see the result of calculating a certain expression in the command window, then at the end of the entered expression you should 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 (listed separated by commas and placed inside parentheses following the function name) and a calculated (returned) value. A list of all elementary mathematical functions available in the system can be obtained using the help elfun command. Appendix 1 lists standard real argument functions.

    Evaluate an expression involving the evaluation of the arcsine function:

    Make sure you get the following result:

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

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

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

    Table 1


    If a relational operation is true, its value is 1, and if false, its value is 0. Relational operations have a lower priority than arithmetic operations.

    Type an expression with relational operations from the keyboard and calculate

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

    » res=(a

    You will get the following result:

    Logical operations on real numbers are 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 is unary (one-operand). Logical operations treat their operands as either “true” (not equal to zero) or “false” (equal to zero). If both operands of the AND operation are true (not equal to zero), then the result of this operation is 1 (“true”); in all other cases, the AND operation produces the value 0 (“false”). The OR operation produces 0 (“false”) only if both operands are false (zero). The "NOT" operation converts "false" to "true". Logical operations have the lowest priority.

    Complex numbers and complex functions

    Complex variables, like real ones, are automatically of double type 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, a multiplication sign must be used between them. So, complex numbers can be written as follows:

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

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

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

    The result will be:

    1.8009 - 1.91901

    The following functions are specifically 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 real). The functions of a complex variable are listed in Appendix 1.

    With regard to arithmetic operations, nothing new can be said for complex numbers (compared to real numbers). The same applies to the relational operators “equal” and “not equal”. The remaining relational operations produce results based only on the real parts of these operands.

    Enter an expression, get the result and explain it:

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

    Logical operations treat operands as false if they are zero. If a complex operand has at least one part (real or imaginary) that is not zero, then such an operand is treated as true.

    Numeric Arrays

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

    "al=; d=;

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

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

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

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

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

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

    The same action - “extending array a1” - can be performed using the concatenation operation:

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

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

    However, this creation method 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). Separated by a colon, enter the first number of the range, the step (increment) and the final number of the range. For example:

    " diap=3.7:0.3:8.974;

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

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

    Enter from the keyboard:

    "a=

    Press ENTER, we get:

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

    » a=[;;];

    or horizontal concatenation of column vectors:

    » a=[,];

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

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

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

    However, it will be much more efficient if, before writing array elements, you create an array of the required size using the functions ones (m,n) or zeros(m,n), filled with ones or zeros (m is the number of rows, n is the number of columns). When these functions are called, memory is first allocated for the specified size of the array; after that, gradually assigning the elements with the required values ​​does not require restructuring the memory structure allocated for the array. These functions can also be used when specifying arrays of other dimensions.

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

    The operation of this function can only be explained based on the way the MATLAB system stores array elements in computer memory. It stores them in a contiguous memory area, ordered by columns: the elements of the first column are located first, followed by the elements of the second column, etc. In addition to the data itself (array elements), the computer memory also stores control information: array type (for example, double), array dimension and size, other service information. This information is sufficient to determine the boundaries of the columns. It follows that to reformat a matrix using the reshape function, it is enough to change only the service information and not touch your own data.

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

    "A=;

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

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

    Array Calculations

    In traditional programming languages, array calculations are done element-by-element, in the sense that you need to program each individual operation on a separate element of the array. The M-language of the MATLAB system allows powerful group operations on the entire array at once. It is the group operations of the MATLAB system that make it possible to extremely compactly define expressions, the calculation of which actually involves a huge amount of work.

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

    Specify matrices A and B and perform matrix addition operation:

    "A=; B=;

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

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

    In addition to the operation./, called the operation of right element-wise division, there is also the operation of 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 assigned in the MATLAB system to the solution of a rather complex linear algebra problem - finding the roots of a system of linear equations. For example, if you need to solve a system of linear equations Ay = b, where A is a given square matrix of size N´N, b is a given column vector of length N, then to find the unknown column vector y it is enough to calculate the expression A\b (this is equivalent to the operation : A -1 B).

    Typical problems of analytical geometry in space related to finding the lengths of vectors and angles between them, with the calculation of 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 cross function is used, for example:

    "u=; v=;

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

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

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

    » sqrt(sum(u.*u))

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

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

    produces an array random numbers 3x3 in size with elements evenly distributed in the interval from 0 to 1.

    If you call this function with two arguments, for example R=rand(2,3), you will get a 2x3 matrix R of random elements. Calling the rand function 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 simple calculations on arrays, in addition to the one discussed above sum functions, the prod function is also used, which is in every way similar to the sum function, only it calculates not the sum of the elements, but their product. The max and min functions search for the maximum and minimum elements of arrays, respectively. For vectors they return a single numeric value, and for matrices they 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 performs such a sort for each column separately.

    MATLAB has the unique ability to perform batch calculations on arrays using ordinary mathematical functions that in traditional programming languages ​​only work with scalar arguments. As a result, with the help of extremely compact entries that are 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 volume of calculations. For example, just two short expressions

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

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

    Graphing functions

    MATLAB's graphics capabilities 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 graphics windows that have 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 graphic window (in this case, the old coordinate axes and the graph disappear - this can also be achieved with the clf command; the cla command deletes only the graph with the coordinate axes brought to their standard ranges from 0 to 1).

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

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

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

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

    » plot(x,y,x,z)

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

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

    A second solution to display multiple plots without conflicting axis ranges is to use the subplot function. This function allows you to divide the graphical information output area into several subareas, into each of which you can display graphs of various functions.

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

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

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

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

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

    » subplot(1,1,1)

    If for a single graph the range of changes in variables along one or both coordinate axes is too large, then you can use the functions for plotting graphs on logarithmic scales. The functions semilogx, semilogy and loglog are designed for this purpose.

    You can build a graph of a function in polar coordinates (Fig. 4) using the polar graphic function.

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

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

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

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

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

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

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

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

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

    Table 3. Markers that specify the line type

    Table 4 Markers that set the line color

    Table 5 Markers specifying the type of point

    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 a dependent variable along the vertical axis, MATLAB independently calculates the range of changes in the function values. If you need to abandon this feature of scaling when plotting graphs in the MATLAB system, then you need to explicitly impose your limits on the change of variables along the coordinate axes. This is done using the axis() function.

    To put various inscriptions on the resulting picture, use the functions xlabel, ylabel, title and text. The xlabel function creates a label for the horizontal axis, the ylabel function also creates a label for the vertical axis (and 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 graph is created by the title function. In addition, using the grid on command, you can apply a measurement grid to the entire plotting area. For example (Fig. 6):

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

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

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

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

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

    The text function places an inscription 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 - their second coordinates, the third vector - the third coordinates. After that, these three vectors can be fed to the input of the plot3 function, which will project the corresponding three-dimensional line onto the plane and construct 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. Helix graph plotted using the plot3 function

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

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

    » =meshgrid(u,v);

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

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

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

    Rice. 8. Graph of a surface in space, constructed 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 complex algorithms need to be implemented, then MATLAB m-files (the file extension consists of a single letter m) should be used. script-m-file (or script) is a text file containing instructions in MATLAB to be executed in automatic batch mode. It is more convenient to create such a file using the MATLAB system editor. It is called from the MATLAB command window with the menu command File/New/M-file (or the leftmost button on the toolbar, which shows a blank white sheet of paper). Commands written in script files will be executed if you enter the name of the script file (without extension) in the command line. Variables defined in the command window and variables defined in scripts constitute a single workspace of the MATLAB system, and variables defined in scripts are global; their values ​​will replace the values ​​of the same variables that were used before calling this script file.

    After creating the 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 calls up the directory path viewer dialog box. To add a new directory to the list of access paths, you must then execute the Path/Add to path menu command.

    Scripts

    Along with working on the command line, there is another way to execute commands. This is writing programs.

    Script is a sequence of MATLAB commands written in a file with the extension “.m”. These are ordinary text files. You can use any text editor to write them.

    To create a script, in general, it is enough to have a regular text editor at hand. We will use the editor built into the MATLAB environment. Use the New Script button in the top left corner to create a new script. After clicking this button, a text editor window will appear (Figure 5).

    Figure 5. MATLAB code editor Let's create a small program:

    fprintf("Hello World!\n")

    Now you need to save this script, to do this you need to click on the “Save” button in the left top corner, after which MATLAB will offer to save it in the current directory (“Current Folder”). Let's give the script the name "Example1.m" and save it. It is advisable that the script be saved in the current directory, so MATLAB will look for scripts to run

    in folders that are listed in the internal MATLAB path variable. This list also includes the current directory, displayed in the MATLAB environment on the right in a special floating area. By default, the script will be saved to the current directory, so you can call it immediately. You can run the script by entering its name (the name of the m-file in which it was saved) in the command line and pressing “Enter” or the “Run” button in the code editor. In both cases, the command window displays the following output:

    >> Example1 Hello World!

    Let's look at another example. There is a script:

    x = 0:0.02:2*pi; a = 0.3;

    y = a * sin(x) + b * cos(x); plot(x, y)

    Let's save it to the file Example2.m and run it. As a result, MATLAB will calculate and display the graph of the function y = a sin(x)+ b cos(x).

    We also note that after executing the script, the variables x, a, b and y appeared in the “Workspace” window. To explain why this happened, consider the very important concept in MATLAB of the workspace.

    Workspace in MATLAB

    The MATLAB system work area is the memory area in which system variables are located. There are two types of workspaces in MATLAB:

    base workspace - base workspace;

    function workspace - function workspace.

    All variables in a workspace exist in the workspace from the time they are declared when working with the workspace until they are explicitly removed using the clear command or until the end of the workspace's life, such as closing MATLAB for the base workspace.

    When the script is launched, it does not create a new workspace, but works with the workspace from which it was called.

    When we call a script from the command window, it works with the base workspace, so all the variables that we created before calling the script are available to it. Also, if the script creates more variables, they will remain available after

    its completion.

    Comments

    Good tone in writing program code is considered to be comments on the code you write. Comments do not affect the operation of the program in any way and serve to provide additional information. Comments will help other people understand your algorithm and help you remember the essence of what you wrote after some period of time when you have already forgotten what you programmed. MATLAB uses the "%" symbol to indicate the start of a comment.

    % Generating Uniformly Distributed Random Numbers

    % Calculating the mathematical expectation of generated numbers

    % Displaying data on a graph

    % 50 random numbers

    % Generate and assign a vector of random

    values ​​of the variable r

    % Display the generated vector on the graph

    % Draw a line

    through (0, m) and (n, m)

    % Calculate the arithmetic mean of the values

    vector r

    plot(,)

    title("Mean of Random Uniform Data") % Chart title

    Functions

    Another variety MATLAB programs- functions. Unlike scripts, when called, a function creates a new workspace, so variables declared outside its code will not be visible inside the function. Therefore, input and output parameters are used to communicate the function with external code. Let's look at the general syntax for declaring a function:

    function = function_name(x1,...,xM) operator_1 operator_2

    operator_n end

    The function is contained in a separate m-file.

    A function starts with the keyword function followed by square

    names of output variables are separated by commas in parentheses. Next comes the “=” sign and the name of the function. The function name follows the same rules as variable names. We also note that the name of the function must match the name of the file in which it is defined. After the function name, the names of the input parameters are separated by commas in parentheses.

    The following lines contain the body of the function (any valid MATLAB expressions).

    At the end the function ends keyword end, however it is optional and can be omitted.

    Also note that if a function returns only one parameter, then it does not have to be enclosed in square brackets, for example:

    function s = triaArea(a, b)

    % calculating the area of ​​a right triangle

    % a, b - legs of the triangle

    s = a * b / 2; end

    If a function does not return parameters at all, then immediately after the function keyword comes the name of the function, for example:

    function hellowWorld()

    % example of a function without input and output parameters disp("Hello world!");

    The following syntax is used to call a function:

    Function_name(z1,...,zM)

    where k1, ..., kN are the variables where the output values ​​of the function will be written, az1,..., zM are the arguments of the function.

    If the function returns only one parameter, then the square brackets can be omitted, for example:

    s = triaArea(1,2)

    Actual and formal parameters of the function

    It is important to distinguish between actual and formal parameters of a function:

    actual parameter - the argument passed to the function when it is called;

    formal parameter - an argument specified when declaring or defining a function.

    Let us explain this difference with an example.

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

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

    Enter 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)

    Now save the file called mydemo.m in a subdirectory work main MatLab directory by selecting Save as menu File editor. To run all commands contained in the file, select Run in the menu Debug. A graphic window will appear on the screen Figure No.1, containing graphs of functions. If you decide to plot cosine instead of sine, then simply change the line g = sin(x) in the M-file to g = cos(x) and run all the commands again.

    Note 1

    If an error is made while typing and MatLab cannot recognize the command, then the commands up to the incorrectly entered one are executed, 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 using the mouse while holding the left button, or using the arrow keys while holding down the key , the first four commands of the program and execute them from point Evaluate Selection menu Text. Please note that only one graph corresponding to the executed commands was displayed in the graphics window. Remember that to execute some commands you must select them and press . Execute the remaining three program commands and monitor the state of the graphics window. Practice on your own, type some examples from previous labs in the M-file editor and run them.

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

    % plotting sin(x) in a separate window

    The M-file editor can have multiple files open at the same time. The transition between files is carried out using 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 M-file editor. 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 appear in this and subsequent labs are best typed and saved in M-files, supplemented with comments, and executed from the M-file editor. The use 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-function(Function M-Files), which describe user-defined functions.

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

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

    Variables defined in one file program can be used in other file programs and in commands executed from the command line. Execution of commands contained in a file program is carried out in two ways:

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

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

    • Checks whether the command entered is the name of any of the variables defined in the runtime. If a variable is entered, its value is displayed.
    • If the input is not a variable, then MatLab looks 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 neither a variable nor a built-in function is entered, then MatLab begins 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 looks through the directories installed in search paths(Path). The found M-file is executed in MatLab.

    If none of the above actions resulted in success, 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 to MatLab system could find them, you should set the paths indicating the location of the M-files.

    Note 2

    Keep own M-files outside the main MatLab directory follows for two reasons. First, when you reinstall MatLab, files that are contained in subdirectories of the main MatLab directory may be destroyed. Secondly, when MatLab is launched, all files in the toolbox subdirectory are placed in the computer’s memory in some optimal way so as to increase performance. If you wrote the M-file to this directory, you can use it only after restarting MatLab.

    3. Setting paths

    In MatLab versions 6 .x the current directory and search paths are determined. Setting these properties is done either using the corresponding dialog boxes or using commands from the command line.

    The current directory is determined in the dialog box Current Directory working environment. The window is present in the work environment if the option is selected Current Directory menu View working environment.
    The current directory is selected from the list. If it is not in the list, you can add it 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 catalog, click the button Add Folder Browse for Path select the required directory. Adding a directory with all its subdirectories is done by clicking on the button Add with Subfolders. MATLAB search path. The search order corresponds to the location of the paths in this field; the directory whose path is located at the top of the list is searched first. You can change the search order or even remove the path to a directory by selecting 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 list;
    Move Down - move down one position;
    Move to Bottom - place at the bottom of the list.

    4. Commands for setting paths.

    Steps to set paths in MatLab 6 .x are duplicated by teams. The current directory is set with the cd command, for example cd c:\users\igor. The cd command, issued without an argument, prints the path to the current directory. To set paths, use the path command, called 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 directory c:\users\igor with the highest search priority.

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

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

    Note 3

    Do not delete directory paths unnecessarily, especially those whose purpose you are not sure of. Removal may result in some of the functions defined in MatLab becoming 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 there under the name mydemo3.m. Set file paths and demonstrate file accessibility from the command line. Provide the results in your laboratory report.

    Solution option:

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

    5. File functions

    The file programs discussed above are a sequence of MatLab commands; they do not have input or output arguments. To use numerical methods and when programming your own applications in MatLab, you must be able to create file functions that perform the necessary actions with input arguments and return the result in output arguments. This subsection contains several simple examples to help you understand how to work with file functions. File functions, as well as 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 this function needs to be calculated. Open a new file in the M-file editor and type the listing text

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

    The word function on the first line specifies that this file contains a function file. The first line is function header, which houses 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 argument is f. After the title comes 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 selecting an item Save or Save as menu File causes a dialog box to save the file to appear, in the field File name which already contains the name myfun. Don't 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 file program and from another file function.

    Warning

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

    The file function given in the listing has one significant drawback. Trying to evaluate function values ​​from an array results in an error rather than 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 learned how to work with arrays, then eliminating this shortcoming will not be difficult. You just need to use element-wise operations when calculating the value of a function.
    Modify the function body as shown in the following listing (remember 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 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 myfun function on a segment from the command line or using a file program:

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

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

    fplot("myfun", )

    Plot myfun graphs using plot and fplot on the same axes, using hold on. Please note that the graph constructed using fplot more accurately reflects the behavior of the function, since fplot itself selects the argument step, reducing it in areas of rapid change in the displayed function. Provide the results in your laboratory report.

    5.2. File functions with multiple input arguments

    Writing file functions with multiple input arguments is practically no different from writing with one argument. All input arguments are placed in a list separated by commas. 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 appended 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 time specified in seconds into hours, minutes and seconds. This file function is shown in the following listing.

    Listing of the function for converting seconds to hours, minutes and seconds

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

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

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

    6. Basics of programming in MatLab

    The file functions and program file used in the previous subsections are the most simple examples programs, All MatLab commands contained in them are executed sequentially. To solve many more serious problems, you need to write programs in which actions are performed cyclically or, depending on some conditions, different parts of the programs are executed. Let's look at the main operators that specify 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 complex branched structures.

    6.1. Loop operator for

    An operator is designed to perform a specified number of repeated actions. The simplest use of the for statement is as follows:

    for count = start:step:final
    MatLab commands
    end

    Here count is a loop variable, start is its initial value, final is its final value, and step is the step by which count is increased each time the loop is entered. The loop ends as soon as count becomes greater than final. A loop variable can take not only integer values, but also real values ​​of any sign. Let's look at the use of the for loop operator using some typical examples.
    Let it be necessary to derive a family of curves for , which is specified 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 file FORdem1.m, and run it for execution (from the M-file editor or from the command line by typing the FORdem1 command in it and pressing ):

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

    Note 4

    The M-file editor automatically suggests placing statements inside the loop, indented from the left edge. Use this feature to make it easier to work with program text.

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

    Write a file program to calculate the sum

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

    Listing of the Fordem2 file program for calculating the amount

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

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

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

    Please note that the remaining lines of the file program that could result in output to the screen intermediate values, terminated with a semicolon to suppress output to the command window.

    It is no coincidence that the first two lines with comments are separated by a blank line from the rest of the program text. They are the ones that are displayed when the user uses the help command from the command line to obtain 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 file program become available in the working environment. They are so-called global variables. On the other hand, the file program can use all the variables entered in the work environment.

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

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

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

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

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

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

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

    Listing of the file function for calculating the sum

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

    % reset S to accumulate amount
    S = 0;
    % accumulation of amount in 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 first three lines with comments will be displayed in the command window, separated from the text of the file function by an empty line.

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

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

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

    6.2. While loop operator

    Let's consider an example of calculating a sum, similar to the example from the previous paragraph. You need 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, let's say more modulo. A for loop is not enough here, since the number of terms is unknown in advance. The solution is to use a while loop, which runs while the loop condition is satisfied:

    while loop condition
    MatLab commands
    end

    In this example, the loop condition stipulates that the current term is greater than . To write this condition, use the greater than sign (>). The text of the file function mysin, which calculates the sum of a series, is given in the following listing.

    Listing of the file-function mysin, which calculates sine by series expansion

    function S = mysin(x)
    % Calculation of sine by series expansion
    % Usage: y = mysin(x), -pi

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

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

    Table 1. Relational operations

    Setting more complex conditions is done using logical operators. For example, the condition consists in the simultaneous fulfillment of two inequalities and , and is written using 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 entry

    Logical "AND"

    and(x< 3, k == 4)

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

    Logical "OR"

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

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

    Negation "NOT"

    When calculating the sum of an infinite series, it makes sense to limit the number of terms. If a series diverges because its terms do not tend to zero, then the condition for the small value of the current term may never be satisfied and the program will go into a loop. Perform the summation by adding a limit on the number of terms to the while loop condition 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 repeated actions in the form of cycles makes the program simple and understandable, but it is often necessary 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 MatLab operators or commands runs.

    The if statement can be used in its simplest form to execute a block of commands when some condition is satisfied, or in an if-elseif-else construct to write branching algorithms.
    Suppose we need to evaluate the expression . Suppose you are performing a calculation in the real number domain and want to display a warning that the result is a complex number. Before calculating the function, you should check the value of the argument x, and display a warning in the command window if the modulus of x does not exceed one. Here you need to use a conditional if statement, the use of which in the simplest case looks like this:

    if condition
    MatLab commands
    end

    If the condition is met, then the MatLab commands located between if and end are implemented, and if the condition is not met, then the transition to the commands located after end occurs. When writing a condition, the operations given in table are used. 1.

    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 an argument

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

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

    Now calling Rfun from an argument less than one will result in a warning message being displayed in the command window:

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

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

    6.4. Branch operator if-elseif-else

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

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

    Depending on the implementation 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 executing any of the branches, the operator exits. There can be as many branches as you like or just 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 statement is given in the following listing.

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

    if (a == 0)
    warning("a is equal to zero")
    elseif a == 1
    warning("a is equal to one")
    elseif a == 2
    warning("a is equal to two")
    elseif a >= 3
    warning("a, 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

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

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

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

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

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

    The use of switch is illustrated by the following example:

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

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

    6.6. Loop break operator break

    When organizing cyclic calculations, care should be taken to ensure that no errors occur within the loop. For example, suppose you are given an array x consisting of integers, and you want to generate a new array y according to the rule y(i) = x(i+1)/x(i). Obviously, the problem can be solved using a for loop. But if one of the elements of the original array is 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 zero. The following program fragment 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 the variable z becomes 0, the loop is terminated.

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

    When the break statement is used in a nested loop, it only exits the inner loop.

    Instructions

    The MATLAB environment has several operating modes. The simplest 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’s enter the commands “x = ; y = sqrt(x); plot(y);” into this window sequentially one after another and press the “Enter” key ( Enter). The program will instantly create variables X, create variable Y and calculate its values ​​​​for a given function, and then build 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 them to the MATLAB environment for execution.
    Comfortable? Undoubtedly. And most importantly - very quickly. All these actions take a few seconds.
    But what if you need a more complex team organization? If you need cyclic execution of some commands? Entering commands manually one at a time and then searching through the 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 through 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 user interface(GUI), as well as edit existing ones. But we are currently interested in writing a program that contains functions for reuse in the future. So let's go to the menu File and choose New -> M-File.

    In the editor field we will write a simple program, but complicate it a little:

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

    We have added a second function and will display two graphs next to each other. The percentage sign denotes comments in MATLAB.
    Don't forget to save the program. The standard file extension for the Matlab program is *.m.
    Now close the editor and the window with the graph that we built earlier.

    Let's 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 input field and in the opened context menu select item Clear Command Window.
    We still have variable X from 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, drawing a graph.