What is the programming language in matlab. Brief description of MATLAB. List expansion packs

TAMBOV STATE TECHNICAL UNIVERSITY


DEPARTMENT

"Information Processes and Management"

Methodological development

for laboratory lesson No. 1

in the discipline "Decision Making Theory"

Name of the discipline

topic name

Subject: Study of one-dimensional optimization methods

Goal of the work:

Study of one-dimensional optimization methods and methods of their algorithmic implementation in the environment of a multifunctional integrated automation system for mathematical and scientific-technical calculations MATLAB 7.1;

Comparative assessment of the amount of computational costs of methods: direct scanning, dichotomy, “golden section” and Fibonacci method.

Literature:

1. Aoki M. Introduction to optimization methods. M.: Nauka, 1977. 444 p.

2. Batishchev D.I. Optimal design methods. M.: “Radio and Communications”, 1984. 248 p.

3. Bodrov V.I., Lazareva T.Ya., Martemyanov Yu.F. Mathematical methods of decision making: Proc. allowance. Tambov: Tamb publishing house. state those. Univ., 2004. 124 p.

4. Polak E. Numerical optimization methods. M.: Mir, 1997. 376 p.

5. Himmelblau D. Applied nonlinear programming. M.: Mir, 1975. 534 p.

6. Yudin D.B. Computational methods of decision theory. M.: Nauka, 1989. 316 p.

7. Ketkov Yu. L., Ketkov A. Yu., Shultz M. M. MATLAB 7: programming, numerical methods. - St. Petersburg: BHV-Petersburg, 2005. - 752 p.

By conducting the lesson

Laboratory classes in the discipline "Decision Making Theory" are conducted with the aim of deepening and consolidating the theoretical knowledge acquired by students in various types of classes and in the process of independent study of educational material, acquiring skills in the practical implementation of mathematical methods of decision making. Based on the results of laboratory classes, students should

Theoretical material on the basis of which the modeling was carried out, as well as the essence of the physical processes formalized in the programs;

Basic methods for modeling relevant processes;

Select and evaluate the influence of the main parameters on the modeling result;

Analyze and summarize the results obtained.

Completing laboratory work includes three stages: preliminary preparation for the laboratory lesson, the lesson itself, and reporting on the laboratory lesson.

The goal of the lesson is to show the connection between theoretical material and practice and teach students to apply theory to solving practical problems.

Laboratory work is structured in such a way that it does not assume students' knowledge of MATLAB. Each lab begins with a MATLAB brief that provides the student with the background information needed to complete the activity.

Preparation for class

On the eve of class, students should:

Read the manual for this lab;

Repeat the lecture material and study the proposed literature on this topic;

Study the procedure for performing work;

Prepare to answer security questions.

Procedure for conducting the lesson

In the introductory part of the lesson, the study group is received, a connection is given with previously studied material, the topic, purpose, order and features of this lesson are announced, and the study group’s preparedness for the lesson is checked.

Next, students begin conducting research in accordance with the methodology. For any unclear questions regarding a laboratory lesson, students should contact the teacher, engineering staff, or computer lab instructor. Research results and conclusions are presented in the form of a laboratory report. The report is the student's working document and is presented to the leading teacher during the defense. Next, the reports on the laboratory lesson are defended, and at the end, the results of the lesson are summed up.

Lesson reporting

Students must receive credit for the laboratory session. The principle of reporting is individual and can be carried out orally or in writing after completing the main part of the lesson. When issuing a grade, the following are taken into account: the availability, literacy and accuracy of the report form, the quality of laboratory work, and the results of answers to test questions. Students who did not receive a credit and are absent from this laboratory lesson report on it in their own time.

Brief description of MATLAB

The MATLAB (Matrix Laboratory) system consists of a large number of special programs that allow solving a wide range of mathematical and technical problems from different fields of science. Its main element is the core of the MATLAB system. In addition to it, the system contains about 80 different sets of commands (so-called “Toolboxes”), corresponding to various sections of mathematics, mathematical physics, design, communications, economics, etc. This work uses basic MATLAB programming tools: M-files – functions, built-in functions, operators, commands, etc.

Fig.1. System desktop

Figure 1 shows the system desktop. The menu bar (File, Edit, etc.) is in many ways similar to that of the Microsoft Word editor. The row of icons located below also perform the same operations as in the Word editor (with the exception of the last 3). The system desktop consists of several windows, the composition of which can be changed using menu commands Desktop. Figure 1 in the top window on the left shows the contents of the workspace Workspace, which contains descriptions of all constants and functions entered by the user during operation. In the lower window Command History The sequence of executed commands is given. The sizes of windows are adjusted by dragging the border with the mouse. Main desktop window - Command Window(command window). In the command window, after the ">>" sign, the command line is typed, which is executed after pressing the " key Enter".

MATLAB allows you to create program files similar to other high-level programming languages. In addition, it has the properties of a powerful programmable calculator. In this work, the software implementation of search algorithms is carried out using M - function files, and programs can be launched and initial data entered from the command window.

The number format is set by the menu File(Fig. 1) in section Preferences using the function Numeric Format. The most commonly used of the 12 possible formats are Short And Long– short and long number formats.

Some of the basic concepts of MATLAB are variables And statements .

Variable denoted by a single letter or a set of letters and numbers starting with a letter. The total number of letters and numbers in the set should not exceed nineteen. Statement has the following form:

>>variable=expression

When you enter a statement, the variable is assigned the expression that follows the equals sign, or, if it involves any mathematical operations, the result that is obtained after performing those operations. You can enter the statement in an M-file or in the MATLAB command window. The ">>" sign is a command prompt that appears on the display screen in the command window to indicate that statements can be entered.

The main arithmetic operators are given in Table 1.1. When performing calculations in the command window after pressing " Enter"the result is assigned to the parameter" ans", if the corresponding expression is not assigned a name, or its name - otherwise (names of variables, constants and functions must begin with a letter (Latin letters), may contain numbers and an underscore). To block the output of the calculation result of a certain expression after it, you must set sign; (semicolon).

Table 1.1

Let, for example, you want to evaluate the expression and assign the result to a variable X. In this case, the statement (program) will have the following form (in decimal fractions, the integer part is separated from the fractional part by a dot):

>> x=log(1+5*((log10(100))^2-0.2*pi)/sqrt(1+2.71828^3))

After introducing the statement, i.e. pressing the Enter key, the result is immediately displayed below. If the result needs to be blocked, i.e. does not need to be displayed on the display screen, then at the end of the statement you need to put the sign “; "(semicolon). The previous expression can be represented in another form:

>> a=(log10(100))^2;

>> b=sqrt(1+2.71828^3);

>> x=log(1+5*(a-0.2*pi)/b)

MATLAB has several built-in variables: pi, eps, inf, i And j. Variable pi stands for number, eps=2 -52 =2.2204*10 -16 – error for operations on floating point numbers, inf- infinity ( ), i And j– imaginary unit ( i = j= ).

When the left argument is not specified, the result of the expression is assigned to the common variable ans.

Relational operators (Table 1.2) are used in conditional statements, loop operators, etc. when implementing search algorithms using M-functions (subroutines-functions are written in files with the extension .m).

Table 1.2

So, programs in the MATLAB system are M-files of text format containing a record of programs in the form of program codes.

The MATLAB input language has only 9 operators using 14 function words. The corresponding syntactic structures are given in Table. 1.3.

Table 1.3

Operator format Explanation
var = expr Assignment operator. Calculates the values ​​of the expression expr and stores the results of the calculations in a variable var
ifcondition_1 statements_1 end Conditional operator. If condition_1 is true, then the group operators_1 is executed, if condition_2 is true, then the group operators_2, ... If all specified conditions are false, then the operators located between else and end are executed
switchexpr casevail operators_1 caseval2 operators_2 . . . . . . . . . [othervise statements] end Switch by expression value expr. If it matches the value vail , then the group operators_1 is executed, if it matches the value val2, then the group operators_2 is executed, ... If the value expr does not coincide with any of the listed values, then the operators located between othervise and end are executed
forvar=el:e3 end statements A cycle of the arithmetic progression type, in which the variable var, with each repetition of the loop body, changes from the initial value el with step e2 to the final value e3
whilecondition statements end A loop with a precondition that repeats until a specified condition is true
try statements_1 catch statements 2 end Attempting to execute group operators_1. Provided that an exception occurs as a result of their execution, control is transferred to the group operators_2 (handling of failure situations). If no error occurs, then group operators_2 is not executed
break Early exit from control structures like for , while, switch, try - catch
function f1 function f2 (x1,x2, . . .) function y=f3(xl,x2,...) function =f4(xl,x2, . . .) Function header (xl, x2, ... - input parameters; y, yl, y2, ... - output parameters)
return Exiting a function body early

When writing function programs, it is required that the name of the M-file in which the program is stored must necessarily coincide with the name of the function.

All variables appearing in the body of a function, with the exception of global variables (declared by the global operator), input parameters, and output parameters, are considered local. They form a local workspace and are available only in the body of the function that generated them, and no other functions can use them.

The MATLAB language does not contain the operator goto. In this regard, there are no operator labels in the texts of m-files. To identify lines in which emergency situations occur, internal numbers are used that are assigned automatically by the system.

Those who deal with higher mathematics know very well what mathematical “monsters” they sometimes have to deal with. For example, you can spend a real lot of time, mental energy and non-recovering nerve cells on calculating some giant triple integral. Of course, it's very interesting to challenge the integral and take it. But what if instead the integral threatens to take you? Or, worse, has the cubic trinomial gotten out of control and gone berserk? You wouldn't wish this on your enemy.


Previously, there were only two options: give up on everything and go for a walk, or enter into a multi-hour battle with the integral. Well, for some it took many hours, for others it took many minutes - who studied how. But that's not the point. The twentieth century and inexorably moving progress offer us a third way, namely, they allow us to take the most complex integral “quickly”. The same applies to solving all kinds of equations, plotting graphs of functions in the form of cubic hyperboloids, etc.

For such extraordinary, but periodically occurring situations among students, there is a powerful mathematical weapon. For those who don’t already know, meet the MATLAB software package.

Matlab will solve the equation, approximate it, and build a graph of 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 program's capabilities 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, including constructing three-dimensional graphs and creating 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 simply by enthusiasts or other companies.

MATLAB as a programming language


It is also a programming language used directly when working with the program. We won’t 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 calculations are directly programmed. By the way, don’t let this word scare you - in order to work in MATLAB, you don’t need to be a professional programmer.

M-files are divided into

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

In order to clearly show how work happens in MATLAB, we give below an example of creating a function in Matlab. This function will calculate the average value of the vector.
f function y = average(x)
% AVERAGE Average value of the vector elements.
% AVERAGE(X), where X is a vector. Calculates the average of the elements of 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("Input array must be a vector')
end
y = sum(x)/length(x); % The actual calculation

The function definition line tells MATLAB that the file is an M function and also specifies the list of input arguments. Thus, the definition line for the average function looks like this:
function y = average(x)
Where:

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

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

Of course, such a powerful package is needed not only to make life easier for students. Currently, 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 them to solve many more problems than, for example, the well-known Excel. You can read more about this 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 that arise in front of you, you will have to work hard and first understand Matlab itself (how to create a file, how to create a function, etc.). And this is not so simple, because power and broad opportunities require sacrifice.

Even if we wanted to, we cannot say that MATLAB issimple program. Nevertheless, we hope that all of the above will be a sufficient argument to take up its development.

And finally. If you don’t know why everything in your life went this way and not otherwise, ask Matlab about it. Just type “why” into the command line. He will answer. Try it!

Now you know the capabilities of Matlab. In the field of 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 conducted during laboratory work. To quickly and efficiently master the basics of working with MATLAB, you can always contact us, who are ready to answer any of your questions at any time.

    Main features of the packageMatlab

    Package Tool SetsMatlab

    Structure and working windows of the packageMatlab

    Working in team mode

    Basic elements of a programming languageMatlab

1. Main features of the Matlab package

MATLAB(short for “Matrix Laboratory”) is a package of application programs for solving technical computing problems and the programming language of the same name used in this package. MATLAB is used by more than 1,000,000 engineers and scientists and runs on most modern operating systems, including Linux, Mac OS, Solaris (Solaris no longer supported as of R2010b), and Microsoft Windows.

Story. MATLAB as a programming language was developed by Cleve Moler in the late 1970s when he was dean of the computer science department at the University of New Mexico. The goal of the development was to give students of the faculty the opportunity to use the Linpack and EISPACK software libraries without the need to study Fortran. The new language soon spread among other universities and was received with great interest by scientists working in the field of applied mathematics. A 1982 version written in Fortran, distributed as open source, can still be found on the Internet. Engineer John N. (Jack) Little was introduced to the language during Cleve Mowler's visit to Stanford University in 1983. Realizing that the new language had great commercial potential, he teamed up with Cleve Mowler and Steve Bangert. Together they rewrote MATLAB in C and founded The MathWorks company in 1984 to further develop it. These libraries, rewritten in C, were known for a long time under the name JACKPAC. MATLAB was originally intended for control system design (John Little's specialty), but quickly gained popularity in many other scientific and engineering fields. It has also been widely used in education, particularly for teaching linear algebra and numerical methods.

Description of the MATLAB language. MATLAB language is high level interpreted programming language, including those based on matrices data structures, a wide range of functions, an integrated development environment, object-oriented capabilities and interfaces to programs written in other programming languages.

Programs written in MATLAB are of two types - functions And scripts.

Functions have input and output arguments, as well as their own workspace for storing intermediate calculation results and variables.

Scripts use a common workspace. Both scripts and functions are not compiled into machine code and are saved as text files.

It is also possible to save so-called pre-parsed programs - functions and scripts processed into a form convenient for machine execution. In general, such programs run faster than regular ones, especially if the function contains graphing commands.

The main feature of the MATLAB language is its wide capabilities for working with matrices, which the creators of the language expressed in the slogan “think vectorially.” Think vectorized).

Application of MATLAB.

Mathematics and calculations. MATLAB provides the user with a large number (several hundred) functions for data analysis, covering almost all areas of mathematics, in particular:

    Matrices and linear algebra - matrix algebra, linear equations, eigenvalues ​​and vectors, singularities, matrix factorization and others.

    Polynomials and interpolation - roots of polynomials, operations on polynomials and their differentiation, interpolation and extrapolation of curves and others.

    Mathematical statistics and data analysis - statistical functions, statistical regression, digital filtering, fast Fourier transform and others.

    Data processing - a set of special functions, including plotting, optimization, zero search, numerical integration (in quadratures) and others.

    Differential equations - solving differential and differential-algebraic equations, delay differential equations, constrained equations, partial differential equations and others.

    Sparse matrices are a special data class of the MATLAB package used in specialized applications.

    Integer arithmetic - performing integer arithmetic operations in MATLAB.

Development of algorithms. MATLAB provides convenient tools for developing algorithms, including high-level ones, using object-oriented programming concepts. It has all the necessary tools of an integrated development environment, including a debugger and a profiler. Functions for working with entire data types make it easy to create algorithms for microcontrollers and other applications where needed.

Data visualization. The MATLAB package has a large number of functions for creating graphs, including three-dimensional ones, visual data analysis and creating animated videos.

The embedded development environment allows you to create graphical user interfaces with various controls such as buttons, input fields and others.

Independent Applications. MATLAB programs, both console and GUI, can be compiled using components MATLAB Compiler into MATLAB-independent executable applications or dynamic libraries, which, however, require the installation of a freely redistributable environment to run on other computers MATLAB Compiler Runtime(MCR).

External interfaces. MATLAB includes various interfaces for accessing external routines written in other programming languages, data, clients and servers communicating through Component Object Model or Dynamic Data Exchange technologies, and peripheral devices that communicate directly with MATLAB. Many of these capabilities are known as the MATLAB API.

COM. MATLAB provides access to functions that allow you to create, manipulate, and delete COM objects (both clients and servers). ActiveX technology is also supported. All COM objects belong to a special COM class of the MATLAB package. All programs that have automation controller functions (English) Automation controller) can access MATLAB as an automation server. Automation server).

.NET. MATLAB on Microsoft Windows provides access to the .NET Framework. It is possible to load .NET assemblies and work with .NET class objects from the MATLAB environment. MATLAB version 7.11 (R2010b) supports .NET Framework versions 2.0, 3.0, 3.5, and 4.0.

DDE. MATLAB contains functions that allow it to access other Windows applications, and for those applications to access MATLAB data, through Dynamic Data Exchange (DDE) technology. Each application that can be a DDE server has its own unique identification name. For MATLAB this name is - Matlab.

Web services. In MATLAB, it is possible to call web service methods. The custom function creates a class based on the web service API methods.

MATLAB interacts with the web service client by accepting messages from it, processing them, and sending a response. The following technologies are supported: Simple Object Access Protocol (SOAP) and Web Services Description Language (WSDL).

COM port. MATLAB's serial port interface provides direct access to peripheral devices such as modems, printers, and scientific equipment that connect to a computer through a serial port (COM port). The interface works by creating a special class object for the serial port. The available methods of this class allow you to read and write data to a serial port, use events and event handlers, and write information to the computer disk in real time. This is necessary when conducting experiments, simulating real-time systems, and for other applications.

MEX files. The MATLAB package includes an interface for interacting with external applications written in C and Fortran. This interaction is carried out through MEX files. It is possible to call routines written in C or Fortran from MATLAB as if they were built-in functions of the package. MEX files are dynamic link libraries that can be loaded and executed by the interpreter built into MATLAB. MEX procedures also have the ability to call built-in MATLAB commands.

DLL. The MATLAB generic DLL interface allows you to call functions found in common dynamic link libraries directly from MATLAB. These functions must have a C interface.

In addition, MATLAB has the ability to access its built-in functions through a C interface, which allows the functions of the package to be used in external applications written in C. This technology in MATLAB is called C Engine.

Alternative packages. There are a large number of software packages for solving numerical analysis problems. Many of these packages are free software.

Compatible with MATLAB at the programming language level:

Similar in functionality:

    APL and its descendants: for example J

    Python, when used with the Python(x,y) software package, as well as with libraries such as NumPy, SciPy, and matplotlib, implements similar capabilities.

    IDL(English) Interactive Data Language, an interactive data description language), once a commercial competitor of MATLAB, now remains a serious competitor in many application areas, although its market share in numerical analysis software has fallen sharply.

    Fortress, a programming language created by Sun Microsystems, is a descendant of Fortran, but is not compatible with it.

    If it is necessary to develop large projects for numerical analysis, it is possible to use general-purpose programming languages ​​that support static typing and modular structure. Examples include Modula-3, Haskell, Ada, Java. In this case, it is recommended to use specialized libraries known in the scientific and engineering environment.

2. Matlab toolboxes

In Matlab, an important role is given to specialized groups of programs called toolboxes. Toolboxes are a comprehensive collection of functions (m-files) written in MATLAB to solve a specific class of problems. Mathworks provides toolkits that are used in many areas, including the following:

    Digital signal, image and data processing: DSP Toolbox, Image Processing Toolbox, Wavelet Toolbox, Communication Toolbox, Filter Design Toolbox- sets of functions that allow solving a wide range of problems of signal and image processing, design of digital filters and communication systems.

    Control systems: Control Systems Toolbox, µ-Analysis and Synthesis Toolbox, Robust Control Toolbox, System Identification Toolbox, LMI Control Toolbox, Model Predictive Control Toolbox, Model-Based Calibration Toolbox- sets of functions that facilitate the analysis and synthesis of dynamic systems, design, modeling and identification of control systems, including modern control algorithms, such as robust control, H∞-control, LMN-synthesis, µ-synthesis and others.

    The financial analysis: GARCH Toolbox, Fixed-Income Toolbox, Financial Time Series Toolbox, Financial Derivatives Toolbox, Financial Toolbox, Datafeed Toolbox- sets of functions that allow you to quickly and efficiently collect, process and transmit various financial information.

    Analysis and synthesis of geographical maps, including three-dimensional ones: Mapping Toolbox.

    Collection and analysis of experimental data: Data Acquisition Toolbox, Image Acquisition Toolbox, Instrument Control Toolbox, Link for Code Composer Studio- sets of functions that allow you to save and process data obtained during experiments, including in real time. A wide range of scientific and engineering measurement equipment is supported.

    Visualization and presentation of data: Virtual Reality Toolbox- allows you to create interactive worlds and visualize scientific information using virtual reality technologies and the VRML language.

    Development Tools: MATLAB Builder for COM, MATLAB Builder for Excel, MATLAB Builder for NET, MATLAB Compiler, Filter Design HDL Coder- sets of functions that allow you to create independent applications from the MATLAB environment.

    Interaction with external software products: MATLAB Report Generator, Excel Link, Database Toolbox, MATLAB Web Server, Link for ModelSim- sets of functions that allow you to save data in such a way that other programs can work with it.

    Database: Database Toolbox- tools for working with databases.

    Science and Math Packs: Bioinformatics Toolbox, Curve Fitting Toolbox, Fixed-Point Toolbox, Fuzzy Logic Toolbox, Genetic Algorithm and Direct Search Toolbox, OPC Toolbox, Optimization Toolbox, Partial Differential Equation Toolbox, Spline Toolbox, Statistic Toolbox, RF Toolbox- sets of specialized mathematical functions that allow solving a wide range of scientific and engineering problems, including the development of genetic algorithms, solving partial derivative problems, integer problems, system optimization and others.

    Neural networks: Neural Network Toolbox- tools for synthesis and analysis of neural networks.

    Fuzzy logic: Fuzzy Logic Toolbox- tools for constructing and analyzing fuzzy sets.

    Symbolic calculations: Symbolic Math Toolbox- tools for symbolic calculations with the ability to interact with the symbolic processor of the Maple program.

In addition to the above, there are thousands of other MATLAB toolkits written by other companies and enthusiasts.

Features Overview

MatLab from English. Matrix Laboratory is both a package of application programs for solving problems of engineering and technical calculations, and the programming language of the same name used in this package.

MatLab is adapted for use on most modern operating systems, including Linux, Mac OS, Solaris and Microsoft Windows.

MATLAB as a programming language was developed by Cleve Moler in the late 1970s. The goal of the development was to give students of the faculty the opportunity to use the Linpack and EISPACK software libraries without the need to study Fortran. Later, Mowler, in collaboration with J. Little and S. Bangert, rewrote MATLAB in C and founded The MathWorks company in 1984 to further develop it. MATLAB was originally intended for control system design, but quickly gained popularity in many other scientific and engineering fields. It has also been widely used in education, particularly for teaching linear algebra and numerical methods.

Modern MatLab is an interactive system in which the main data element is an array. This allows you to programmatically implement numerical methods that intensively use operations on matrices and vectors, several times faster than when writing similar programs in “scalar” programming languages ​​like C, C++, Fortran, etc.

An important advantage of MatLab is the openness of the function code, which allows experienced users to change the code, improving it or adapting it to their tasks. As a programming language, MatLab combines the simplicity of Fortran and the flexibility of C, although from a formal point of view MatLab is interpreter. It should be noted that the MatLab API communicates with programs written in C and Fortran, which allows you to call MatLab functions from C\Fortran code and vice versa.

MatLab has extensive capabilities for visualizing 2- and 3-dimensional data. High-level graphics functions and a graphical interface reduce user effort to a minimum while providing high-quality images. There is also access to low-level functions for “advanced” users, which further expands the graphical capabilities of the system.

The MatLab package was created by Math Works more than ten years ago. The work of hundreds of scientists and programmers is aimed at constantly expanding its capabilities and improving the underlying algorithms. Currently, MatLab is a powerful and universal tool for solving problems arising in various areas of human activity.
The working environment MatLab 6.x, MatLab 7 has a convenient interface for accessing many auxiliary elements of MatLab.
When you start MatLab 6.x, the working environment appears on the screen , shown in Fig. 1.

Rice. 1. Working environment of the MatLab 6.x package

This lesson teaches the basics of working (introduction) in matlab.

The work environment contains the following elements:

Menu;
- toolbar with buttons and drop-down list;
- window with tabs Launch Pad And Workspace from which you can easily access the various ToolBox modules and the contents of the work environment;
- window with tabs Command History And Current Directory, intended for viewing and re-calling previously entered commands, as well as for setting the current directory;
- command window Command Window with a command line containing a blinking cursor;
- status bar.

All commands described in this lab must be typed at the command prompt. The symbol itself, indicating the command line prompt, given in the examples, does not need to be typed. To view the work area, it is convenient to use scroll bars or keys , to move left or right and , To move up or down. About using keys , , , will be said further. If suddenly, after moving around the work area of ​​the command window, the command line with the blinking cursor disappears, just click .
It is important to remember that typing any command or expression must end with a key press in order for the MatLab program to execute this command or evaluate the expression.

Note 1

If some of the described windows are missing in the MatLab 6.x working environment, then you should go to the menu View select the appropriate items: Command Window, Command History, Current Directory, Workspace, Launch Pad.

2.1. Arithmetic calculations

MatLab's built-in math functions allow you to find the meaning of various expressions. MatLab provides the ability to control the output format of the result. Commands for evaluating expressions have the form characteristic of all high-level programming languages.

2.1.1. Simple calculations

Type 1+2 at the command line and press . As a result, the MatLab command window displays the following:

» 1+2
ans =
3
» |

What did the MatLab program do? First, she calculated the sum 1+2, then wrote the result to a special variable ans and displayed its value, equal to 3, in the command window. Below the response is a command line with a blinking cursor, indicating that MatLab is ready for further calculations. You can type new expressions on the command line and find their meanings.

If you need to continue working with the previous expression, for example, calculate (1+2)/4.5, then the easiest way is to use the existing result, which is stored in the ans variable. Type ans/4.5 at the command line (a dot is used when entering decimals) and press , it turns out:

» ans/4.5
ans =
0.6667
» |

Note 2

The form in which calculation results are output depends on the output format set in MatLab. The following explains how to set basic output formats.

2.1.2. Calculation result output formats

The required output format of the result is determined by the user from the MatLab menu. Select from menu File paragraph Preferences A dialog box will appear on the screen Preferences To set the output format, make sure that the item is selected in the list of the left panel Command Window. The format is set from the drop-down list Numeric format panels Text display.
For now, we will analyze only the most commonly used formats. Select short in the dropdown list Numeric format in MatLab 6.x. Close the dialog box by clicking OK. The short floating-point format for outputting calculation results is now set to short, which displays only the four digits after the decimal point on the screen. Type 100/3 at the command line and press .
The result is output in short format:

» 100/3
ans =
33.3333

This output format will be retained for all subsequent calculations unless a different format is set. Please note that in MatLab it is possible that when displaying a number that is too large or small, the result does not fit into the short format. Calculate 100000/3, the result is printed in exponential form:

» 100000/3
ans =
Z.ZZZZe+004

The same thing will happen when finding 1/3000:

» 1/3000
ans =
Z.ZZZZe-004

However, the initial format setting is retained during further calculations; for small numbers, the result will again be output in the short format.

In the previous example, the MatLab package output the calculation result in exponential form. The entry 3.3333e-004 means 3.3333*10-4 or 0.00033333. Similarly, you can type numbers in expressions. For example, it is easier to type 10e9 or l.0e10 than 1000000000, and the result will be the same. A space between numbers and the symbol e is not allowed when entering, because this will result in an error message:

» 10 e9
??? 10 e9

If you want to get the calculation result more accurately, you should select from the drop-down list long. The result will be displayed in long floating point format with fourteen digits after the decimal point. Formats short e And long e are designed to display the result in exponential form with four and fifteen digits after the decimal point, respectively. Information about formats can be obtained by typing help at the command line with the format argument:

A description of each format appears in the command window.

You can set the output format directly from the command line using the format command. For example, to set the long floating-point format for outputting calculation results, enter the format long e command on the command line:

» format long
» 1.25/3.11
ans =
4.019292604501608е-001

Note that the help format command displays the format names in capital letters. However, the command that must be entered consists of lowercase letters. This feature of the built-in help takes some getting used to. MatLab distinguishes between uppercase and lowercase letters. Trying to type a command in capital letters will result in an error:

» FORMAT LONG E
??? FORMAT LONG.
Missing operator, comma, or semi-colon.

For a more convenient perception of the result, MatLab displays the result of calculations one line after the calculated expression. However, sometimes it is convenient to place more lines on the screen, for which you should select the radio button compact (File, Numeric display) from the drop-down list. Adding blank lines is provided by selecting loose from the dropdown list Numeric display.

Note 3

MatLab performs all intermediate calculations with double precision, no matter what output format is set.

2.2. Using Elementary Functions

Suppose you want to evaluate the following expression:

Enter this expression on the command line according to the MatLab rules and press :

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

The response is displayed in the command window:

ans =
-3.2105

When entering an expression, MatLab's built-in functions are used to calculate the exponent, natural logarithm, square root, and trigonometric functions. What built-in elementary functions can be used and how to call them? Type the command help eifun on the command line, and a list of all built-in elementary functions with their brief description will be displayed in the command window. Function arguments are enclosed in parentheses, and function names are typed in lowercase letters. To enter a number l just type pi on the command line.

Arithmetic operations in MatLab are performed in the usual order typical of most programming languages:

Exponentiation ^;
- multiplication and division *, /;
- addition and subtraction +, -.

To change the order in which arithmetic operators are executed, use parentheses.
If you now want to evaluate the value of an expression similar to the previous one, for example

then it is not necessary to type it again on the command line. You can take advantage of the fact that MatLab remembers all entered commands. To re-enter them into the command line, use the keys , . Evaluate this expression using the following steps.

1. Press the key<­>, and the previously entered expression will appear on the command line.
2. Make the necessary changes to it, replacing the minus sign with a plus sign and the square root with squaring (to move along the line with the expression, use the keys , , , ).
3. Evaluate the modified expression by clicking .

It turns out

»exp(-2.5)*log(11.3)^0.3+((sin(2.45*pi)+cos(3.78*pi))/tan(3.3))^2
ans =
121.2446

If you need to get a more accurate result, you should run the format long e command, then press the key<­>until the required expression appears on the command line, and calculate it by pressing .

» format long
» exp(-2.5)*log(11.3)^0.3+((sin.(2.45*pi)+cos(3.78*pi))/tan(3.3))^2
ans =
1.212446016556763e+002

You can output the result of the last found expression in a different format without recalculating it. You should change the format with the short command, and then look at the value of the ans variable by typing it in the command line and pressing :

» format short
» ans
ans =
121.2446

In the MatLab 6.x working environment, there is a convenient tool for calling previously entered commands - a window Command History with team history. The command history contains the time and date of each session of working with MatLab 6.x. To activate a window Command History You must select the tab with the same name. The current command in the window is shown on a blue background. If you click on any command in the window with the left mouse button, then this command becomes the current one. To execute it in MatLab, you need to double-click the mouse or select the line with the command using the keys , and press the key . The extra command can be removed from the window. To do this, you need to make it current and delete it using the key . You can select several consecutive commands using a keyboard shortcut +, +and execute them using or delete with the key . Selecting sequential commands can be done with the left mouse button while simultaneously holding down the key . If the commands do not follow one another, then to select them you should use the left mouse button while holding the key .

When you right-click on a window area Command History A pop-up menu appears. Select an item Sora causes the command to be copied to the Windows buffer. With help Evaluate Selection you can execute the marked group of commands. To delete the current command, use the item Delete Selection. D To delete all commands before the current one - Delete to selection, to delete all commands - Delete Entire History.

There may be some exceptions in calculations, such as division by zero, which in most programming languages ​​result in an error. When dividing a positive number by zero in MatLab the result is inf (infinity), and when dividing a negative number by zero the result is -inf (minus infinity) and a warning is issued:

» 1/0
Warning: Divide by zero.
ans =
Inf

Dividing zero by zero results in NaN (not a number) and also generates a warning:

» 0/0
Warning: Divide by zero.
ans =
NaN

When calculating, for example sqrt(-1) , no error or warning occurs. MatLab automatically moves into the realm of complex numbers:

»sqrt(-1.0)
ans =
0 + l.0000i

How do you know which built-in primitive functions can be used and how to call them? Type the command on the command line help eifun, and a list of all built-in elementary functions with their brief description is displayed in the command window.

Continuing the topic:
Modems

Construction of the White Sea-Baltic Canal, connecting the White Sea and Lake Onega, began in 1931 on the initiative of Joseph Stalin. To build a canal under the Council...