M functions. Programming m-functions. Software Development Tools

When programming parts on CNC machines in accordance with the DIN 66025 (ISO 6983) standard, formerly known as ISO 7bit, the following operators are used:

  • N - frame number;
  • G - preparatory functions;
  • X, Y, Z, A, B, C - information about movements along the axes;
  • M - additional functions;
  • S - spindle functions;
  • T - tool functions;
  • F - feed functions;
  • H - auxiliary functions (tool compensation data blocks in DIN-ISO mode). If there is a valid D number of the current tool, it is additionally displayed.

For greater clarity of the frame structure, the operators in the frame should be arranged in the following sequence: N, G, X, Y, Z, A, B, C, F, S, T, D, M, H.

The control program consists of n th number of frames, reproduced continuously or with specified pauses (when high-speed processing of parts made of high-strength aluminum alloys, even a short stop of the tool between adjacent frames is unacceptable due to the danger of overheating or melting of the processed surface due to friction). In addition, it is possible to skip individual frames and correct sizes by connecting preparatory functions. This ensures the development of control programs for standard technological processes.

Personnel control program consist of the following components:

  • commands (operators) according to DIN 66025;
  • elements of a high-level CNC programming language;
  • identifiers (defined names) for:
    • system variables;
    • user defined variables;
    • subroutines;
    • code words;
    • transition marks;
    • macros;
  • comparison operators;
  • logical operators;
  • calculation functions;
  • control structures.

Since the command set according to DIN 66025 is not enough for programming complex machining processes on modern multi-task machines, it was supplemented with elements of a high-level CNC programming language.

In contrast to commands according to DIN 66025, commands in the high-level CNC programming language consist of several address letters, for example:

  • OVR - for speed correction (percentage);
  • SPOS - for spindle positioning.

The program structure has the following form: “%” (only for programs developed on a PC), the program title “O” or “:” followed by the program number containing no more than four digits. Each line in a program is a frame.

Each program block has the structure:

  • N - sequence number of the frame (no more than four characters, numbering is carried out through 5 or 10 to make it possible to introduce additional frames when working out the program);
  • preparatory function G;
  • coordinates X, Y, Z, A, C, B;
  • additional function M;
  • spindle function S;
  • tool function T;
  • feed function F;
  • D - tool offset number;
  • H - tool compensation data blocks in DIN-ISO mode. Commands operate either modally or frame by frame.

Modally valid commands retain their significance in all subsequent blocks with a programmed value until a new value is programmed at the same address, canceling the previously valid command.

Commands that operate block by block retain their significance only in the block in which they are programmed.

Each frame ends with an LF character, the LF character does not need to be written, it is automatically created when the line is switched. The program ends with commands M2, M30 or M99. A frame can consist of a maximum of 512 characters (including comment and LF character).

The preparation functions G ensure all machine functions.

X, Y, Z - linear coordinate axes of the machine, the Z coordinate is always parallel to the axis of the machine spindle or perpendicular to the plane of the workpiece for machines with a double-rotary milling head; A, C, B - angular coordinates of rotation relative to linear coordinate axes. If the machine has more than two spindles, as well as tool heads, then additional coordinate axes X', Y', Z', A', C', B', etc. appear.

It should be noted that the preparatory functions allow you to switch to the coordinate system of the part, which in some cases allows you to abandon the use of special devices.

Additional functions M are responsible for turning on and off the spindle, pumping stations for coolant supply, the direction of rotation of the spindle, and the end of the program.

The spindle function S sets the spindle speed.

The tool function T specifies the number of the tool or tool setting.

The feed function F specifies the feed value.

Rice. 1.

The machine coordinate system and the directions of positive movements are shown in Figure 1.

Control programs can be compiled in the machine coordinate system; in this case, the machine tool equipment used must be consistent with the coordinate grid of the machine table. Coordination is achieved by the fact that the support plate of the device has a centering pin and a key. The pin fits into a bushing pressed into the center of the machine table, and the key fits into a cool groove. Thus, the working space of the machine in the plane XY is combined with the coordinate system of the device. In the coordinate system of the device, basic surfaces are made, for example, a plane and two fingers (cylindrical and cut). Consequently, positioning errors occur both when installing the fixture and when installing the part.

During intensive use in a multi-item production environment, i.e. when fixtures are frequently changed, it is necessary to double-check not only the equipment, but also the guide base surfaces of the machine table, namely the centering sleeve and the class groove.

Taking this into account, it is advisable to perform processing in the coordinate system of the part. The device is oriented along only one axis, and the reference to the coordinate system of the part is performed by measuring sensors. In this case, in addition to eliminating positioning errors, the requirements for the timing of rechecking equipment are reduced, moreover, it becomes possible to more widely use normalized devices or adjustments from them without reference to the coordinate system of the machine.

Preparatory functions G, additional functions M are given in tables 1, 2.

So, on milling machines, tool change is performed in the following sequence: using the T command, a tool is selected, and its change occurs only using the M6 ​​command.

For turret heads on lathes, the T command is sufficient to change tools.

The spindle function S specifies the spindle speed, the tool function T specifies the tool setting or tool number, and the feed function F specifies the feed value.

Table 1.Preparatory functions G

Instructions Description
G00Linear interpolation during rapid motion
G01Linear interpolation at feedrate
G02Circular interpolation clockwise
G03Circular interpolation counterclockwise
G04Time delay
G05Circular interpolation with access to a circular path along a tangent
G06Reducing the permissible acceleration level
G07Cancel Acceleration Reduction
G0SFeed rate control at inflection points
G09Canceling Feed Rate Control at Inflection Points
G10Accelerated movement in polar coordinates
G11Linear interpolation in polar coordinates
G12Circular interpolation clockwise in polar coordinates
G13Counterclockwise circular interpolation in polar coordinates
G14Programming the gain value based on the speed of the servo drive
G15Cancel G14
G16Programming without plane specification
G17Plane selection UX
G1SPlane selection ZX
G19Plane selection UZ
G20Specifying the pole and coordinate plane when programming in polar coordinates
G21Programming Axis Classification
G22Activating tables
G23Conditional jump programming
G24Programming an unconditional jump
G32Thread cutting in linear interpolation mode without compensating chuck
G34Corner rounding for two adjacent straight sections (with permissible deviation under address E)
G35Turn off corner smoothing
G36Switching off the deviation programmed during rounding, which becomes equal to the machine parameter
G37Programming a point to mirror or rotate coordinates
G38Activation of mirroring, rotation of coordinates, scaling
G39Cancel mirroring, rotating coordinates, scaling
G40Cancel equidistant correction
G41Equidistant correction on the left in the feed direction
G42Equidistant correction to the right in the feed direction
G53Cancel zero offset
G54-G59Initiating a zero offset
G60Program coordinate system offset
G61Precise positioning when moving at feedrate
G62Cancel precise positioning
G63Turn on 100% of the programmed speed value
G64Linking the feed rate to the point of contact between the cutter and the part
G65Linking the feed speed to the center of the cutter
G66Activation of the speed value set by the potentiometer
G67Cancel program coordinate system offset
G68Option for pairing equidistant segments along an arc
G69Option for pairing equidistant segments along the intersection trajectory of equidistant lines
G70Programming in inches
G71Cancel programming in inches
G73Linear interpolation with precise positioning
G74Exit to the origin
G75Working with the touch sensor
G76Move to a point with absolute coordinates in the machine coordinate system
G78Drill axis activation
G79Deactivating one drill axis or all at once
G80Canceling Canned Cycles
G81, G82Standard drilling cycle
G83Standard deep drilling cycle
G84Threading cycle with compensating chuck
G85, G86Standard drilling cycle
G90Programming in absolute coordinates
G91Programming in relative coordinates
G92Setting coordinate values
G93Programming the block execution time
G94Programming feed in mm/min
G95Programming feed in mm/rev
G97Cutting speed programming
G105Setting zero for linear infinite axes
G108Feed control at inflection points based on Look Ahead
G112
G113Activating Brake Advance Control
G114Activating forward speed control
G115Deactivating forward speed control
G138Enabling Workpiece Position Compensation
G139Turning off work position compensation
G145-845Activation of external correction by the programmable controller
G146Turning off external tool compensation
G147, G847Secondary compensation group for tool corrections; corrections are related to the axes
G148Cancel additional tool compensation
G153Cancel the first additive zero offset
G154-159Indication of the first additive zero offset
G160-360External zero offset
G161Accurate positioning during rapid traverse
G162Canceling fine positioning during rapid traverse
G163Accurate positioning during rapid traverse and traversing at feedrate
G164First precision positioning option
G165Second precision positioning option
G166Third precision positioning option
G167Cancel external zero offset
G168Shift of the coordinate system of the control program
G169Cancels all coordinate system offsets
G184Threading cycle without compensating chuck
G189Programming in absolute coordinates for infinite axes
G190Programming in absolute coordinates “word by word”
G191Programming in relative coordinates “word by word”
G192Setting the lower speed limit in the control program
G194Programming speed (feed, speed) with acceleration adaptation
G200Linear interpolation at rapid traverse without braking up to V= 0
G202Helical interpolation clockwise
G203Helical interpolation counterclockwise
G206Activating and storing maximum acceleration values
G228Transitions from frame to frame without slowdown
G253Cancel second additive zero offset
G254-259Initiating a second additive zero offset
G268Additive offset of the control program coordinate system
G269Cancel additive offset of the control program coordinate system
G292Setting the upper speed limit in the control program
G301Enable oscillating motion
G350Setting the oscillating motion parameters
G408Formation of smooth acceleration when moving from point to point
G500Detecting possible collisions when viewing frames ahead
G543Enabling collision management when viewing frames ahead
G544Disabling collision management when viewing frames ahead
G575Frame switching by high-speed external signal
G580Disbanding coordinate axes
G581Formation of coordinate axes
G608Formation of smooth acceleration when moving from point to point for each axis separately

Note. For each control system, some preparatory function values ​​may have different meanings depending on the machine manufacturer. It should be noted that in order to expand the technological capabilities of equipment, manufacturers of CNC systems have a tendency to increase preparatory functions.

Table 2.Additional M functions

Instructions Description
MOStopping the program
M1Request stop
M2End of the program
M3Enable spindle rotation clockwise
M4Enable spindle rotation counterclockwise
M5Spindle stop
M2=3Power tool turned clockwise
M2=4Power tool turned counterclockwise
M2=5Power Tool Off
M6Automatic tool change
M7Turning on airflow
MSTurn on coolant
M9Turning off cooling
M1ODisabling airflow
M11Tool clamp
M12Tool release
M13Turning on the spindle clockwise together with turning on the coolant
M14Turning on the spindle counterclockwise together with turning on the coolant
M15Turning on coolant to flush out chips
M17End of subroutine
M19Spindle orientation
M21 X
M22Enable program mirroring along an axis U
M23Disable program mirroring
M29Enabling Rigid Threading Mode
M3OEnd of program with the possibility of simultaneously turning off the machine power
M52Move the magazine one position to the right
M53Moving the magazine one position to the left
M7OStore initialization
M71Lowering the active magazine pocket
M72Rotate the manipulator 60°
M73Tool release
M74Rotate the manipulator 120°
M75Tool clamp
M76Rotate the manipulator 180°
M77Raising the active magazine pocket
M98Calling a subroutine
M99Return to main program

Noteworthy. For different control systems and machine types, additional functions may have different meanings, for example, activate the movement of the tailstock, functions boot device, lunette, etc.

When creating an NC program, the programming itself, i.e. the conversion of individual work steps into the NC language, is often only a small part of the programming work.

Before programming, it is necessary to plan and prepare work transitions. The more precisely the beginning and structure of the CNC program is planned, the faster and easier the programming itself will be and the more clear and less error-prone it will be. ready-made program CNC.

The advantage of visual programs is particularly evident when changes need to be made later.

Since not every program has the same structure, it makes no sense to work according to a standard template. However, for most cases it is advisable to follow the following sequence.

1. Preparation of a part drawing consists of:

  • a) in determining the zero point of the part;
  • b) in drawing a coordinate system;
  • c) in the calculation of possibly missing coordinates.

2. Definition of processing process:

  • a) When will they be used, which tools and for processing which contours?
  • b) In what sequence will the individual elements of the part be manufactured?
  • c) Which individual elements are repeated (perhaps rotated) and must be stored in a subroutine?
  • d) Do other part programs or subroutines have part outlines that can be reused for the current part?
  • e) Where are datum offsets, rotation, flip, scaling (frame concept) useful or necessary?

3. Creation of a technological map. Determine one by one all the machining processes of the machine, for example:

  • a) rapid movements for positioning;
  • b) tool change;
  • c) determination of the processing plane;
  • d) free play for additional measurement;
  • e) turning on/off the spindle, coolant;
  • f) call up tool data;
  • g) submission;
  • h) trajectory correction;
  • i) supply to the circuit;
  • j) outlet from the circuit, etc.

4. Translation of transitions into a programming language: recording each transition as an NC block (or NC blocks).

5. Connecting all individual transitions into an operation, usually in one program. Sometimes, especially when processing large parts in a program, the transitions of roughing, semi-finishing and finishing can be highlighted. This took place with the limited memory capacity typical of legacy CNC systems. For modern systems program control The amount of memory practically does not limit the technological capabilities of the machines.

Modern program control systems widely use standard processing cycles. Their use significantly reduces programming time.

Some cycle constants for control systems used in the WIN NC SINUMERIK software are listed below:

  • CYCLE81 ​​- drilling, centering;
  • CYCLE82 - drilling, countersinking;
  • CYCLE83 - drilling deep holes with twist drills;
  • CYCLE84 - internal thread cutting without compensating chuck;
  • CYCLE840 - internal thread cutting with compensating tap chuck;
  • CYCLE85 - boring 1;
  • CYCLE86 - boring 2;
  • CYCLE87 - boring 3;
  • CYCLE88 - boring 4;
  • CYCLE89 - boring 5;
  • CYCLE93 - groove;
  • CYCLE94 - internal groove;
  • CYCLE95 - allowance removal cycle;
  • CYCLE96 - threaded recess;
  • CYCLE97 - thread cutting cycle.

It should be noted that high-level program control systems are open, which allows expanding the library of standard cycles for processing standard surfaces characteristic of production of this type products and thereby reduce production preparation time.


Rice. 2.

The use of CAM systems has led to the need for each program control system to develop postprocessors, without which the equipment cannot understand programs without translating them into machine codes (Fig. 2).

Programming of modern CNC systems is carried out in accordance with the ISO 6983 (DIN 66025) standard, which is more than 50 years old and which, according to programmers, allegedly slows down the development of CNC technologies. The term “CNC technology”, according to the author, is not legal; processing of parts on CNC machines is subject to all the laws of mechanical engineering technology and metal cutting or other shaping methods.

Violation of the laws of technological sciences leads to:

  • to increased warping of parts;
  • to a decrease in the accuracy of linear dimensions;
  • to an increase in the labor intensity of processing parts, etc.

The main difference for multi-purpose machines is the extremely pronounced concentration of operations, not only characteristic of this type of equipment, but also implemented by driven tools and special spindle equipment, as well as methods for ensuring accuracy using machine measuring systems. The standard supports simple commands for basic movements and logical operations. Currently, to solve complex geometric and logical problems in program control systems, in addition to machine codes in accordance with DIN 66025 (ISO 7bit), high-level programming languages ​​are used. Control programs in the ISO 6983 standard contain a small amount of information obtained at the level of CAD-CAM systems. However, a more serious drawback, according to developers of program control systems, is the inability to exchange information two-way with these systems, which means that any changes to the control program cannot be reflected upstream. information flow to CAD-CAM systems. It should be noted that this is not practical for all industries. So, for example, smoothing the smooth conjugation of theoretical contours with splines is acceptable, but the conjugation of two surfaces requires an analysis of possible methods of their shaping; for a number of structural materials there may be technological limitations, for example, the minimum permissible radii of conjugation of structural elements of parts made of high-strength aluminum alloys, etc. .

In contrast to DIN 66025 (ISO 6983), the STEP-NC ISO 14649 standard being developed (not all of its modules have been developed at this time) defines a special structure of the CNC control program - program structure, which is used to construct logical blocks within the framework of structured processing programming. The structure of the control program is not a list of typical processed forms (features); it defines an operation plan (workplan), which is a sequence of executables. STEP-NC involves a wide exchange of information between engineering services, including preparation and production planning, as well as the shop level.

The structure of the proposed information exchange is shown in Figure 3.

The structure of the planned information exchange raises a lot of questions:

  • the insufficient level of formalization of engineering work makes it difficult to create knowledge bases;
  • a large number of cutting tool catalogs, which provide insufficient information for choosing a tool for processing special materials and the conditions of its use, which in most cases requires experimental verification;
  • equipment catalogs often lack information about the positional accuracy of the machine’s controlled axes, the dynamic characteristics of the drives, etc.;
  • outdated technological reference books, developed for universal equipment and systematically republished with virtually no updating of technological information;
  • lack of systematic information about advanced technological equipment.

Rice. 3. Planned exchange of information between engineering services and the shop level

Additionally, it should be noted that there are no standard methods for optimizing machine programming by parameters that allow you to select the best machine or group of machines to perform a particular technological operation or process.

These problems have been pointed out many times by users of various machine tools involved in the STEP-NC standardization process. Equipment Manufacturers and Developers software try to take into account user requirements and implement some of the specified functions in its products. However, their work is often not subject to a single standard, which, according to existing opinion, can slow down the updating of industrial systems. It is also impossible not to mention that manufactured equipment rarely uses all modern technologies and, as a result, the production base is not so efficient and perfect. Taking this into account, manufacturers of programmable control systems have chosen a compromise option that allows them to work according to both DIN 66025 (ISO 6983) and ISO 14649 (Fig. 4).

Rice. 4. Mixed CNC system architecture supporting DIN 66025 (ISO 6983) and ISO 14649 (STEP-NC) standards

All this indicates that in addition to improving program control systems and programming methods, it is necessary to engage in the preparation of technological information on a systematic basis:

  • a tool that provides intensification of processing modes;
  • recommendations for the use of various tool designs;
  • dependencies for cutting calculations;
  • dependencies for calculating the components of cutting forces;
  • databases on CNC equipment and their technological capabilities, including in cases of equipment different systems management;
  • algorithms for calculating cutting modes for machines where electric spindles are used as the main movement drive;
  • strategy for processing various structural elements of parts on CNC machines;
  • databases on the use of commercially produced equipment for CNC machines;
  • measuring systems for machine tools, including zero reference and measuring sensors;
  • production instructions for assembling tool settings and balancing them;
  • technological regulations for checking the accuracy of CNC machines, rechecking spindle equipment, especially HSK type mandrels and bushings and much more.
Currently, many programming languages ​​are used to program CNC systems, based on the universal ISO 7-bit language. However, each manufacturer brings its own features, which are implemented through preparatory (G-codes) and auxiliary (M-codes) functions.

Functions with address G- are called preparatory, they determine the operating conditions of the machine associated with programming the geometry of the tool movement. A detailed description of G-codes can be found in the chapter ISO 7 bit code.

In this chapter we will consider in detail the purpose of auxiliary functions.

Functions with address M- are called auxiliary(from English: Miscellaneous) and are designed to control various modes and devices of the machine.

Auxiliary functions can be used alone or in conjunction with other addresses, for example the block below installs tool number 1 into the spindle.

N10 T1 M6, where

T1– tool number 1;
M6– tool change;

In this case, under the M6 ​​command on the CNC stand there is a whole set of commands that ensure the process of tool replacement:

Moving the tool to the change position;
- turning off spindle speed;
- moving the installed tool in the store;
- tool replacement;

The use of M-codes is allowed in frames with tool movement, for example in the line below the cooling will turn on (M8) simultaneously with the start of the cutter movement.

N10 X100 Y150 Z5 F1000 M8

M-codes that turn on any machine device have a paired M code that turns off that device. For example,

M8– turn on cooling, M9– turn off the cooling;
M3– turn on the spindle speed, M5– turn off the speed;

It is allowed to use several M commands in one frame.

Accordingly, the more devices a machine has, the more M commands will be involved in its control.

Conventionally, all auxiliary functions can be divided into standard And special. Standard auxiliary functions are used by CNC manufacturers to control the devices found on each machine (spindle, cooling, tool change, etc.). Whereas special programs program modes on one specific machine or group of machines of a given model (on/off the measuring head, clamping/unclamping the rotary axes).

The picture above shows the rotating spindle of a multi-axis machine tool. To increase rigidity during positional processing, the machine is equipped with rotary axis clamps, which are controlled by M codes: M10/M12– enable clamps for axes A and C. M11/M13– turn off the clamps. On other equipment, the machine manufacturer can configure these commands to control other devices.

List of standard M commands

M0 – program stop;
M1 – stop on demand;
M2 – end of the program;
M3 – turn on the spindle rotation clockwise;
M4 – turn on the spindle rotation counterclockwise;
M5 – spindle stop;
M6 – automatic tool change;
M8 – turn on cooling (usually coolant);
M9 – turn off the cooling;
M19 – spindle orientation;
M30 – ending the program (usually with resetting all parameters);
M98 – subroutine call;
M99 – return from the subroutine to the main one;

The machine manufacturer describes special auxiliary functions in the corresponding technical documentation.

Auxiliary functions (or M-codes) are programmed using the address word M. Auxiliary functions are used to control the program and electrical automation of the machine - turning on/off the spindle, coolant, changing tools, etc.

Table 3.

Designation

Purpose

M00

Programmable stop

M01

Stop with confirmation

M02

End of the program

M03

Spindle rotation clockwise

M04

Spindle rotation counterclockwise

M05

Spindle stop

M06

Tool change

M08

Turn on cooling

M09

Cooling off

M17

Return from subroutine

M18

Positioning the spindle at a given angle

M19

Spindle orientation

M20

End of a repeating program section

M30

Stop and go to the beginning of the control program

M99

Continue execution of the first frame

Auxiliary functions that perform the inclusion of any operations ( M03, M04 And M08), are executed at the beginning of the block before movement commands. The remaining auxiliary functions are executed at the end of the block.

In table 3 is a list of commonly used helper functions.

2.1. Programmable stop (M00)

Unconditional stop of the control program after executing the movement contained in the current block. The state of the program does not change until the button is pressed again START on the control panel or keys TO THE BEGINING, to return to the beginning of the current program.

2.2. Stop with confirmation (M01)

Stopping the control program after executing the movement contained in the current block, provided that the mode is set “Stop with confirmation” from the control panel of the control system (see document MSHAK-CNC Operator's Manual).

Example:

X-2 X-4.

M1 ; Stop program execution on this block if

; mode set “Stop with confirmation” from the operator's console

2.3. End of program (M02)

Determines the end of the control program execution, stops the supply of coolant and stops the spindle rotation.

Example:

G0X20Z50 Z.5

G0 X0Z0 M2

2.4. Spindle rotation clockwise (M03)

Starts spindle rotation clockwise using the current value specified by word.

Example:

G54 G0 X-20 Z30 S500M3

2.5. Spindle rotation counterclockwise (M04)

Starts spindle rotation counterclockwise using the current value specified by word.

Example:

G54 G0 X-20 Z30 S1500M4

2.6. Spindle stop (M05)

Stops spindle rotation. Executed after the movements contained in the frame.

Example:

G28 X0 Z0 M5

G4 P2 M2

2.7. Tool change (M06)

Performs tool changes between the spindle and the tool magazine. According to this function the following occurs:

· Positioning along the axes to the tool change point;

· Spindle rotation stop and spindle orientation;

· Tool change.

Example:

T5; start searching for tool 5 in the store

X50 Z60 ; continuation of the program

M6; tool change

2.8. Enable cooling (M08)

Turns on the supply of cutting fluid (coolant).

Example:

S300M3X20Z30G0

G1X50Z44M8 ; Turn on coolant

G0Z-100

2.9. Cooling off (M09)

Turns off the supply of cutting fluid (coolant).

Example:

S300M3X20Z30G0 G1X50Z44 M9M5G0Z-100

2.10. Return from subroutine (M17)

Defines the end of a subroutine when it is called with an address word L.

Example:

X5Z5

; Main program

L10 ; Calling a subroutine starting from block N10 X2Z8

N10Z2; Subroutine with block mark N10 X10

M17; End of subroutine and return to main program

2.11. Spindle positioning (M18)

Using this function you can rotate the spindle to a specified angle

Format:

M18 Pnnn

Where: nnn – rotation angle +/- 360 degrees.

The rotation angle is measured relative to the spindle position to which the spindle is set using function M19.

Example:

M18 P45 ; spindle rotation 45 degrees

2.12. Spindle orientation (M19)

Helper function M19 stops the spindle rotation and performs its orientation.

2.13. End of a repeating program section (M20)

Determines the end of a repeating segment of a program when it is called by a word with an address H.

Example:

N10 H2; execute the program section up to M20 2 times

2. Syntax for defining and calling M-functions .

The text of the M function must begin with header, followed by function body.

The header defines the "interface" of the function (the way to interact with it) and is structured as follows:

function [ RetVal1, RetVal2, ] = FunctionName(par1, par2,)

Here a function is declared (using the immutable "function" keyword) named FunctionName, which takes input parameters par1, par2,, and produces (calculates) output (return) values ​​RetVal1, RetVal2…

In other words they say that function arguments are the variables par1, par2,.., and function values (they need to be calculated) are the variables RetVal1, RetVal2,.

The function name specified in the header (in the example given - FunctionName) should serve as the name of the file in which the function text will be written. For this example, this will be the file FunctionName.m (the name extension must still consist of only one letter m).

Mismatch between the function name and the file name is not allowed!

The body of the function consists of commands that calculate the return values. The function body follows the function header.

The function head plus the function body together constitute the function definition.

Both input parameters and return values ​​can be in general arrays (in a particular case - scalars) of various dimensions and sizes. For example, the function MatrProc1

function [ A, B ] = MatrProc1(X1, X2, x)

A = X1 .* X2 * x;

B = X1 .* X2 + x; is designed to “receive” two arrays of identical (but arbitrary) sizes and one scalar. These arrays in the body of the function are first multiplied element by element, after which the result of such multiplication is also multiplied by a scalar. This creates the first of the output arrays.

Same sizes input arrays X1 and X2 guarantee the feasibility of their element-wise multiplication. The second output array (named B) differs from the first in that it is obtained by addition with a scalar (rather than multiplication). Call carried out from the command window of the MATLAB system (or from the text of any other function) in the usual way: the name of the function is written, after which the following are listed in parentheses, separated by commas actual inputs , with the values ​​of which calculations will be performed. Actual parameters can be specified by numbers (arrays of numbers), variable names that already have specific values, and expressions.

If the actual parameter is given by the name of some variable, then the actual calculations will be performed on a copy of that variable (rather than on itself). It is called transfer parameters by value .

Below is a call from the MATLAB command window to the MatrProc1 function we previously created for the example.

Here, the names of the actual input parameters (W1 and W2) and the variables in which the calculation results are written (Res1 and Res2) do not match the names of similar variables in the definition of the MatrProc1 function. Obviously, a match is not required, especially since the third input actual parameter has no name at all! To emphasize this possible difference, the names of the input parameters and output values ​​in a function definition are called formal.

In the considered example of calling the MatrProc1 function, from two input 2 x 2 square matrices, two output matrices Res1 and Res2 are obtained of exactly the same sizes:

Res1 =
9 6
6 6

Res2 =
6 5
5 5

By calling the function

MatrProc1 = MatrProc1([ 1 2 3; 4 5 6 ], [ 7 7 7; 2 2 2 ], 1);

with two input arrays of size 2x3, we get two output matrices of size 2x3. That is, the same MatrProc1 function can process input parameters of various sizes and dimensions! You can apply this function to scalars instead of arrays (these are still 1x1 arrays).

Now let's consider the question of whether this function can be used as part of expressions in the same way as is done with functions that return a single value? It turns out that this can be done, and the first value returned by the function is used as the function value used for further calculations. The following MATLAB window illustrates this point:

When called with parameters 1,2,1, the MatrProc1 function returns two values: 2 and 3. For use as part of an expression, the first of them is used.

Since calling any function can be done by writing an arbitrary expression in the MATLAB command window, you can always make a mistake associated with a mismatch of the types of actual and formal parameters.

MATLAB does not perform any checks on this topic, but simply passes control to the function. As a result, erroneous situations may arise. To avoid (if possible) the occurrence of such erroneous situations, it is proposed in the text of the M-functions to check the input parameters. For example, in the MatrProc1 function it is easy to identify the situation when the sizes of the first and second input parameters are different. Writing such code requires control constructs that we have not yet explored. It's time to start studying them!

Now the capabilities of the system significantly exceed the capabilities of the original version of the Matrix Laboratory. Today's MATLAB, the brainchild of The MathWorks, Inc., is a highly efficient language for engineering and scientific computing. He supports

mathematical calculations

, scientific graphics visualization and programming using an easy-to-learn operating environment. The most famous areas of application of the MATLAB system:

Mathematics and Computing;

Algorithm development;

Computational experiment, simulation modeling, prototyping;

Data analysis, research and visualization of results;

Scientific and engineering graphics;

Application development, including graphical user interface. MATLAB is an interactive system whose main object is an array, for which the dimension does not need to be specified explicitly. This makes it possible to solve many computational problems associated with vector-matrix formulations. Version MATLAB 6.1 is the penultimate achievement of the developers (the last was MATLAB 6.5).

The MATLAB system is both an operating environment and a programming language. One of the system's greatest strengths is that reusable programs can be written in MATLAB. The user can write specialized functions and programs himself, which are compiled in the form of M-files. That's why packages The operating environment of the MATLAB 6.1 system is a set of interfaces that support communication of this system with the outside world through dialogue with the user via the command line, M-file editor, interaction with external systems Microsoft Word, Excel, etc.

After starting the MATLAB program, its main window appears on the computer display, containing menu, tool ruler with buttons and client side of the window with an invitation sign. This window is usually called command window MATLAB systems (Fig. 1).

Menu File(Fig. 2) combines the usual functions: Edit responsible for changing content Window commands (undo, repeat, cut, copy, paste, select all, delete, etc.) and for clearing some MATLAB windows; menu View– for the design of the desktop; Web menu – launches Web pages from the Internet; menu Window– works with the M-file editor/debugger (closes all M-files, makes one of them current); menu Help– Works with reference documentation and demos.


The option deserves special consideration Preferences... (selection of characteristics), which, when selected, opens a window that includes a tree of objects on the left (Fig. 3), and their possible characteristics on the right.

Dashboard The command window of the MATLAB system allows for easy access to operations on M-files: creating a new M-file; opening an existing M-file; deleting a fragment; copying a fragment; inserting a fragment; restoring only the completed operation, etc.

IN client side MATLAB command window, after the prompt, you can enter various numbers, variable names, and operation signs, which together make up some expressions. Pressing the Enter key causes MATLAB system evaluate the expression or, if it does not evaluate, repeat it. Although the sign ";" at the end of the line suppresses the output of the result (echo output).

Thus, in the client part of the MATLAB command window, the user can immediately write commands that form individual calculations or an entire program.

So, the structural parts of the MATLAB command window were analyzed. But besides them, there are several more MATLAB elements that help when working:

Teams- a window containing previously entered commands in the Command Window (“command history”).

Workspace is an area of ​​MATLAB memory in which system variables are located. The contents of this area can be viewed from command line using commands who(only displays variable names) and whos(displays information about the sizes of arrays and the type of variable) or in a separate window under the same name. In it you can perform the following operations: load a data file, save the Workspace as (commands allow you to open and save the contents of the workspace in a binary MAT file), delete selected variables; open the selected variables (where you can change their value). In addition, in the Edit menu you can clear both the Command Window and Command History, as well as the Workspace (or run the command in the Command Window: clear).

To save and launch the Workspace, you can use the load and save commands.

Example.

Saving to: matlab.mat

>> save my.mat

>> load my.mat

>> save my2

>> load my2

Current catalog– a window that is a kind of “guide” through MATLAB catalogs.

Launch Editor– a window reflecting a tree of structural elements of MATLAB and other installed with it software, which can be launched by double-left clicking the mouse. For example, this window might look like Figure 9.

M-file editor/debugger– one of the most important structural parts of MATLAB, which can be opened by selecting the appropriate option in the main menu, on toolbar or called from the command line with the edit or edit command<имя М-файла>and allows you to create and edit M-files.

The editor/debugger supports the following operations: creating a new M-file; opening an existing M-file; saving the M-file on disk; deleting a fragment; copying a fragment; inserting a fragment; help; set/delete control point; continue execution, etc.

GUIDE is a graphical user interface in which complete applications are created.

Interactive work session. M-files. Interactive mode is a user mode for entering commands and expressions from the keyboard, the execution of which produces the necessary numerical results that can be easily and quickly visualized using the built-in graphical tools of the MATLAB package. But using this mode to create and save a specific program is not possible. Therefore, the creators of MATLAB, in addition to the Command Window, in which the interactive mode is implemented, highlighted special files, containing MATLAB language codes, and called M-files (*.m). To create an M-file, use text editor(M-file editor/debugger).

Working in the M-file editor. Working from the MatLab command line becomes difficult if you need to enter a lot of commands and change them frequently. The most convenient way to execute 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. To work with M- the editor is intended for files M-files. Using the editor, you can create your own functions and call them, including from the command line.

Expand the File menu of the main MatLab window and in the New item select the M-file sub-item. New file opens in editor window M-files (Fig. 10). Let's write to a file a program for calculating the arithmetic mean

variable a and b, then save it with the name fun1.m. Compare the methods for solving the problem presented in the table.

Instructions