Windows.  Viruses.  Laptops.  Internet.  Office.  Utilities.  Drivers

Calculating the number of dimensions of an array

Function ndims(A) returns the dimension of array A (if it is greater than or equal to two). But if the input argument is a Java array or an array of Java arrays, then regardless of the size of the array, this function will return 2. The following example illustrates the use of the function ndims:

> > M = rand(2: 3: 4: 5):

> > ndims(M)

Ans =

Calculating the size of an array dimension

To calculate the size of each dimension of the array, use the function size:

  • M = size(A.DIM) returns the size of the dimension specified by the DIM scalar as a row vector of size 2. For a two-dimensional or one-dimensional array A, size(A.l) returns the number of rows, a size(A, 2) returns the number of columns;

For N-dimensional arrays A with n>2 size(A) returns an N-dimensional row vector reflecting the page organization of the array, the last component of this vector is equal to N. The vector does not contain data on unit dimensions (those where the row vector or column vector, i.e. size(A,DIM)==l). An exception is Java's N-dimensional javaarray arrays, which return the size of the highest-level array.

In general, when the input argument size is a javaarray, the returned number of columns is always 1, and the number of rows (rows) is equal to the size (length) of the javaarray.

  • = size(A) returns the size of the first N dimensions of array A;
  • D = size (A), for an mxn matrix A, returns a two-element row vector in which the first component is the number of rows m, and the second component is the number of columns n;
  • = size(A) returns the number of rows and columns in different output parameters (output arguments in MATLAB terminology) type.

Permutations of array dimensions

If we imagine a multidimensional array in the form of pages, then their permutation is a permutation of the dimensions of the array. For a two-dimensional array, permutation often means transposition- replacing rows with columns and vice versa. The following functions generalize matrix transposition to the case of multidimensional arrays and provide permutation of the dimensions of multidimensional arrays:

  • permute (A, ORDER)- rearranges the dimensions of array A in the order determined by the permutation vector ORDER. The ORDER vector is one of the possible permutations of all integers from 1 to N, where N is the dimension of array A;
  • ipermute(A, ORDER)- operation inverse to permute: permute(permute(A. ORDER), ORDER)=A

Below are examples of the use of these functions and the function size:

> > A = [ 1 2: 3 4 ]:

> > B = [ 5 6 ; 7 8 ];

> > C = [ 9 10 ; 11 12 ];

> > D = cat(3 .A,B.C)

D(:,:, 1) =

1 2

3 4

9 10

11 12

> > size(D)

Ans =

2 2 3

> > size(permute(D.[ 3 2 1 ]))

Ans =

3 2 2

> > size(ipermute(D.[ 2 1 3 ]))

Lesson #13.

Multidimensional arrays

    The concept of multidimensional arrays

    Using the ":" operator in multidimensional arrays

    Accessing an individual element of a multidimensional array

    Removing a dimension in a multidimensional array

    Creating pages filled with constants and random numbers

    Combining Arrays

    Calculating the number of dimensions of an array and determining the size of the dimensions

    Permutations of array dimensions

    Shift of array dimensions

    Removing Unit Dimensions

In this lesson we will touch on issues related to more complex data types, which include multidimensional arrays.

The concept of multidimensional arrays

In MATLAB, a two-dimensional array is a special case of a multidimensional array. Multidimensional arrays are characterized by dimensions greater than two. Such arrays can be given a visual interpretation. Thus, a matrix (two-dimensional array) can be written on one sheet of paper in the form of rows and columns consisting of matrix elements. Then a notebook with such sheets of paper can be considered a three-dimensional array, a shelf in a closet with notebooks can be considered a four-dimensional array, a closet with many shelves can be considered a five-dimensional array, etc. In this book, almost nowhere, except for this section, will we deal with arrays, the dimension which are higher than two, but it is still useful to know about MATLAB’s capabilities in terms of specifying and using multidimensional arrays.

In our literature, the concepts of “size” and “dimension” of arrays are almost synonymous. However, they have clearly different meanings in this book and in the MATLAB documentation and literature. Under dimension arrays refers to the number of dimensions in the spatial representation of arrays, and by size - number of rows and columns (mxn) in each array dimension.

Using the ":" operator in multidimensional arrays

When specifying arrays normally (using the semicolon ";"), the number of rows (lines) of the array is 1 greater than the number of ":" characters, but the array remains two-dimensional. The ":" (colon) operator makes it easy to perform operations to increase the size of arrays. Let's give an example of forming a three-dimensional array by adding a new page. Let us be given an initial two-dimensional array M of size 3x3:

» M=

M =

1 2 3

4 5 6

7 8 9

To add a new page with the same size, you can expand M as follows:

» M(:.:.2)=

M(:.:.l) =

1 2 3

4 5 6

7 8 9

M(:.:.2) =

10 11 12

13 14 15

16 17 18

Let's see what the array M now contains when it is explicitly specified:

» M

M(:,:.1)=

1 2 3

4 5 6

7 8 9

M(:.:.2) =

10 11 12

13 14 15

16 17 18

As you can see, the numbers in the expressions M(:.:, 1) and M(:,: ,2) mean the page number.

Accessing an individual element of a multidimensional array

To call the central element first of the first and then of the second page, you need to write the following expressions:

» M(2.2,1)

Ans =

» MS2.2.2)

Ans =

Thus, multidimensional arrays use the same indexing rules as one-dimensional and two-dimensional arrays. An arbitrary element, for example, of a three-dimensional array is specified as M(1 .j.k), where 1 is the row number, j is the column number and k is the page number. This element can be output, or you can assign it a given value x: M(1,j,k)=x.

Removing a dimension in a multidimensional array

We have already noted the possibility of deleting individual columns by assigning them the values ​​of an empty column vector. This technique is easy to extend to pages and, in general, the dimensions of a multidimensional array. For example, the first page of the resulting array M can be deleted as follows:

» M(:.:.1)=

M =

10 11 12

13 14 15

16 17 18

It is easy to see that only the second page remains in this array and that the dimension of the array has decreased by 1 - it has become two-dimensional.

Creating pages filled with constants and random numbers

If there is a numeric constant after the assignment sign, then the corresponding part of the array will contain elements containing this constant. For example, let’s create from the array M (see example above) an array whose second page contains ones:

"M(:.:..2)=1

M(:.:,1) =

10 11 12

13 14 15

16 17 18

M(:.:.2) =

1 1 1

1 1 1

1 1 1

Now let’s replace the first page of the array with a page with zero elements:

"M(:.:.1)=0

M(:.:.1)=

0 0 0

0 0 0

0 0 0

M(:.:,2) =

1 1 1

1 1 1

1 1 1

Using the ones, zeros, rand, and randn functions

The functions ones (creating arrays with unit elements), zeros (creating arrays with zero elements) and rand or randn (creating arrays with elements - random numbers with a uniform and normal distribution, respectively) can also be used to create multidimensional arrays. Examples are given below:

» E=ones(3.3.2)

E(:.:.1)=

1 1 1

1 1 1

1 1 1

E(:.:,2) =

1 1 1

1 1 1

1 1 1

» Z=zeros(2,2,3) Z(:,:.l) =

Z(:.:.2) =

Z(:.:,3) =

» R=randn(3,2.2) R(:.:.l) =

1.6656-1.1465

0.1253 1.1909

0.2877 1.1892

R(:.:,2) =

0.0376-0.1867

0.3273 0.7258

0.1746 -0.5883

These examples are quite obvious and do not require special comments. Note, however, that it is easy to specify array sizes for each dimension. In addition, it should be noted that if at least one dimension of the array is zero, then the array will be empty:

» A=randn(3,3,3,0)

A =

Empty array: 3-bu-3-bu-3-by-0

As you can see from this example, an empty array is returned with an appropriate comment.

Combining Arrays

To create multidimensional arrays, use the special concatenation function cat, described earlier for matrices:

    cat(DIM,A,B) - returns the result of combining two arrays A and B along the DIM dimension;

    cat(2.A.B) - returns the array [A.B], in which the rows are combined (horizontal concatenation);

    cat(1, А.В) - returns the array [A:B], in which the columns are combined (vertical concatenation);

    B=cat(DIM.Al,A2,...) - combines multiple input arrays Al, A2,... along the DIM dimension.

The functions cat(DIM,C(:)) and cat(DIM.C.FIELD) respectively provide concatenation (merging) of cells of a cell array (see lesson 15) or structures of an array of structures (see lesson 14) containing numeric matrices into a single matrix. The following are examples of using the cat function:

» M1=

» M2=

M2 =

» catd.Ml.M2)

Ans =

5 B

» cat(2.Ml.M2)

ans=

1 2 5 6

3 4 7 8

» M-cat(3.Ml.M2) M(:,:.l) =

M(:,:,2) =

Working with Dimensions

Calculating the number of dimensions of an array

The ndims(A) function returns the size of array A (if it is greater than or equal to two). But if the input argument is a Java array or an array of Java arrays, then regardless of the size of the array, this function will return 2. The following example illustrates the use of the ndims function:

» M=rand(2:3:4:5):

» ndims(M)

Ans =

4
Calculating the size of an array dimension

To calculate the size of each dimension of an array, use the size function:

    M = size(A.DIM) returns the size of the dimension specified by the DIM scalar as a row vector of size 2. For a two-dimensional or one-dimensional array A, size(A.l) returns the number of rows, a size(A, 2) returns the number of columns;

For N-dimensional arrays A with n>2 size(A) returns an N-dimensional row vector reflecting the page organization of the array, the last component of this vector is equal to N. The vector does not contain data on unit dimensions (those where the row vector or column vector, i.e. size(A,DIM)==l). An exception is Java's N-dimensional javaarray arrays, which return the size of the highest-level array.

In general, when the input argument size is a javaarray, the returned number of columns is always 1, and the number of rows (rows) is equal to the size (length) of the javaarray.

    Si ze(A) returns the size of the first N dimensions of array A;

    D = size (A), for an mxn matrix A returns a two-element row vector in which the first component is the number of rows m, and the second component is the number of columns n;

    Size(A) returns the number of rows and columns in the various outputs (output arguments in MATLAB terminology) type.

Permutations of array dimensions

If we imagine a multidimensional array in the form of pages, then their permutation is a permutation of the dimensions of the array. For a two-dimensional array, permutation often means transposition- replacing rows with columns and vice versa. The following functions generalize matrix transposition to the case of multidimensional arrays and provide permutation of the dimensions of multidimensional arrays:

    Permute (A, ORDER) - rearranges the dimensions of array A in the order determined by the permutation vector ORDER. The vector ORDER is one of the possible permutations of all integers from 1 to N, Where N- array dimension A;

    ipermuteCA, ORDER) - the inverse operation of permute: permute(permute(A. ORDER), ORDER)=A

The following are examples of using these functions and the size function:

"A=:

"B=;

» C=;

» D=cat(3.A,B.C)

D(:,:,l) =

9 10

11 12

"size(D)

Ans =

2 2 3

» size(permute(D.))

ans=

3 2 2

»size(ipermute(D.))

Ans=

2 2 3

» ipermute(permute(D,),)

Ans(:. :,2) =

ans(:.:,3) =

9 10

11 12

Shift of array dimensions

The shift of dimensions is implemented by the shiftdim function:

    B=shiftdim(X,N) - shift of dimensions in the array X by the amount N. If M>0, then the shift of dimensions located on the right is performed to the left, and the N dimensions first on the left are collapsed to the end of the array, i.e. the dimensions move in a circle counterclockwise. If M<0, сдвиг выполняется вправо, причем N первых размерностей, сдвинутых вправо, замещаются единичными размерностями;

    Shiftdim(X) - Returns array B with the same number of elements as array X, but with the initial unit dimensions removed. The output parameter NSHIFTS shows the number of dimensions removed. If X is a scalar, the function does not change X, B, NSHIFTS.

The following example illustrates the use of the shiftdim function:

» A=randn(1.2.3,4):

" =shiftdim(A)

B(:.:.l) =

2.1707-1.01060.5077

0.05920.6145 1.6924

B(:.:,2) =

0.5913 0.3803 -0.0195

0.6436-1.0091-0.0482

B(:.:.3) =

0.0000 1.0950 0.4282

0.3179-1.87400.8956

B(:.:,4) =

0.7310 0.0403 0.5689

0.5779 0.6771 -0.2556

Removing Unit Dimensions

The squeeze(A) function returns an array with all unit dimensions removed. A dimension in which size(A. dim) == 1 is called unit. But if

A is a one-dimensional or two-dimensional array (matrix or vector), then the function will return the same array A. The following example explains how squeeze works:

» A=randn(1.2.1.3.1):

"B=squeeze(A)

0.6145 1.6924 -0.6436

0.5077 0.5913 0.3803

Notice that the five-dimensional array A becomes a 2-dimensional array with a size of 2x3.

What new have we learned?

In this lesson we learned:

    Create multidimensional arrays.

    Use the “:” operator in multidimensional arrays.

    Access individual elements of multidimensional arrays.

    Remove dimensions from a multidimensional array.

    Create arrays filled with constants and random numbers.

    Concatenate arrays.

    Calculate the number of dimensions of an array and determine the size of each dimension.

    Rearrange, shift and delete unit dimensions in multidimensional arrays.

Elements of the same class can often be combined into arrays (with a few rare exceptions, such as using functions). Numeric scalars, by default of class double , can be stored in a matrix.

>> A = A = 1.0e+04 * 0.0001 -0.0002 0.0003 0.0001 1.5625 0.0003 Inf Inf NaN -Inf

Characters that have the class char in MATLAB can also be stored in an array using a similar syntax. Such an array is similar to a string in many other programming languages.

>> s = ["MATLAB ","is ","fun"] s = MATLAB is fun

Note that even though they both use [ and ] brackets, the result classes are different. Therefore, the operations that can be done on them are also different.

>> whos Name Size Bytes Class Attributes A 2x5 80 double s 1x13 26 char

The s array is not actually an array of the strings "MATLAB", "is" and "fun", it is just one string - an array of 13 characters. You would get the same results if they were defined by one of the following:

>> s = ["MAT","LAB ","is f","u","n"]; >> s = ["M","A","T","L","A","B," ","i","s"," ","f","u", "n"];

A regular MATLAB vector does not allow you to store a combination of variables from different classes or multiple different strings. This is where the cell array comes in handy. This is an array of cells, each of which can contain some MATLAB object, the class of which can be different in each cell if necessary. Use curly braces ( and ) around elements to store in a cell array.

>> C = (A; s) C = "MATLAB is fun" >> whos C Name Size Bytes Class Attributes C 2x1 330 cell

Standard MATLAB objects of any class can be stored together in a cell array. Note that cell arrays require more memory to store their contents.

The contents of a cell are accessed using curly braces ( and ) .

>> C(1) ans = 1.0e+04 * 0.0001 -0.0002 0.0003 0.0001 1.5625 0.0003 Inf Inf NaN -Inf

Note that C(1) is different from C(1) . Whereas the latter returns the contents of a cell (and has a double example), the former returns a cell array that is a submatrix of C. Similarly, if D were a 10 by 5 cell array, then D(4:8,1: 3) will return a submatrix D whose size is 5 by 3 and whose class is cell . And the C(1:2) syntax does not have one returned object, but rater it returns 2 different objects (similar to a MATLAB function with multiple return values):

>> = C(1:2) x = 1 -2 3.14 0.8 15625 3.14159265358979 Inf Inf NaN -Inf y = MATLAB is fun

TOPIC 5. SOFTWARE IMPLEMENTATION OF MATHEMATICAL MODELS
Modern mathematical models are complex and to perform calculations on them it is necessary to use a computer. Therefore, the algorithms or calculation methods given in the previous chapter should be translated into some programming language. Currently, languages ​​such as FORTRAN, C, and PASCAL are popular for scientific development. But for a wide range of users, these languages ​​are considered complex and therefore systems such as EXCEL, MATLAB, MATHCAD, MAPLE, etc., which are more understandable to specialists in the subject area, have become widespread. We will focus on the MATLAB system, which is used in the laboratory work of this training course.
^ 5.1 Brief characteristics of MATLAB
The MATLAB system (short for MATrix LABoratory) was developed by The MathWorks, Inc. (USA, Natick, Massachusetts) and is an interactive system for performing engineering and scientific calculations, which is focused on working with data arrays and allows access to programs written in Fortran, C ++. The system supports operations with vectors, matrices and data arrays, supports working with algebraic polynomials, solving differential and difference equations, solving nonlinear equations and optimization problems, etc., as well as constructing various types of graphs, three-dimensional surfaces and level lines.

The operating environment of the MATLAB system includes a command window, a toolbar, subsystems for viewing the workspace and access paths, an M-file editor/debugger, etc. The user can write programs himself using the M-file editor, which are formatted as M-files (M-files). files have extension .m). Each program must be created, edited (i.e. adjusted) and executed (i.e. calculated).

To create a new program in the menu ^File option is selected New and then M-File; As a result, the M-file editor window opens. The text of the program is typed in this window. After this text has been typed, you should save the program with a name (for this, in the menu File option is selected Save as).

To run the program, go to the command window and in the command line, indicated on the screen by the symbols >> enter the M-file name.

To edit an already created M-file, you need to return from the command window to the editor window with the program text.

^

Formation of arrays in MATLAB

In MATLAB, the main object is arrays (matrices and vectors), for which dimensions are not required to be explicitly specified. To form a numeric array, numbers are indicated inside square brackets, the separator between numbers is spaces. The symbol is used to separate rows of matrices ; . Example.

The matrix A = of 3 lines and 2 columns is written as: A = .

The symbol is used to form arrays : . Example.

Set vector WITH, consisting of numbers from 0 to 0.5 in increments of 0.1: C = 0: 0.1: 0.5. The line will appear on the screen:

C = 0 0.1 0.2 0.3 0.4 0.5

If the step is 1, then it is not specified, for example, to specify a vector B consisting of the numbers 3, 4, 5, 6, 7, you can write: B = 3: 7. Then the screen will appear:

B = 3 4 5 6 7
Symbol : is also used to select subblocks of an array. Example. Select the first column of the matrix A =: A ( : , 1).
Arrays can be combined. Let x= 1, 2, 3, 4, a y= 5, 6, 7, 8. Then a fragment of the program for forming the combined array z will be the following:

x = 1:4;

y = 5:8;

z = [x; y]

the following will appear on the screen: z =

Arithmetic operations. Arithmetic addition operators are used + , subtraction , multiplication * , divisions / , exponentiation ^.

p1) . ′ element-wise transposition (rows are replaced by columns, for complex

complex conjugation is not performed for matrices).

For example, let A = , then A . ′ = .

p1) .^ element-wise exponentiation, A . ^B.

For example, let A = , then A . ^2 =
.

p1) ′ - matrix transposition. For complex matrices, the transpose is complemented

complex conjugation.

For example, let A = , then A′ =
.

p1) ^ raising a matrix to a power, A^p (only for square matrices and for integers p). For example, let matrix A =
. Then A^2 =

p2) .* element-wise multiplication of two arrays of the same size.
For example, let A =
B=
, then A . *B =

All elements of the array are multiplied by a scalar, for example, let A = . Calculate F =3*A. We get F =
.
p2) * matrix multiplication, A*B.

For example, let A = B = . Then A * B =
.
p2) ./ element-wise division of arrays. The arrays must be the same size or the array is divided by a scalar. For example, let A = . Then B ./ 3 = .
p3) + addition and - subtraction for scalars, vectors and matrices.

For example, let A =
and B =
. Then A - B =
.

PS: Operations of type p1 are executed before p2, and p2 before p3. Within each level, the priority is the same, calculations are performed from left to right. You can use parentheses to determine the required order of operations

^

Some special characters

() - indication of the sequence of operations. Examples:

a) set an array x from 0 to 3 in increments of 0.1 and presented as a column: x=(0: 0.5: 2)′

b) calculate
: y=(x+0.5)/2
- formation of arrays (see section “Formation of arrays in the MATLAB system”)
% - comments begin with this symbol. They can be on separate lines or follow any of the commands.
; this symbol is used: a) to suppress the display of calculation results; b) to separate rows of matrices.
: - this symbol is used to form vectors, as well as to select rows or columns of an array.
pi - number π = 3.141592653897
ans - the result of the operation if the output variable is not specified (in this case, MATLAB uses the variable ans).
inf - this symbol appears on the screen when, during a calculation, the bit grid (“actual” ∞) overflows in one of the cells. For example, when performing a division by zero operation.
NaN - a special variable to indicate an undefined value, the result of operations like: 0/0, inf/inf etc.

^

Basic Math Functions

abs- absolute value, for example, let x= [-2 4 –8.5], then abs( x) = .

sin, cos, tan etc. – trigonometric functions, arguments (angles) are specified in radians. For example, t= cos( x);

exp- exponential function ( e x), For example: y= exp( x);

log- natural logarithm, for example: c= log( d);

log10– decimal logarithm, for example, z= log10( y);

sqrt - square root, for example: b= sqrt( a);
Some graphics functions
figure- function to open a graphic window on the screen
xlabel, ylabel- functions for naming the x and y axes
title- function for placing a title above the graph
plot(x,y)- function for constructing a two-dimensional dependence graph y = f(x) in Cartesian coordinates (marker type, color and line type on the graph are selected automatically);
plot(x1, y1, LineSpec1, x2, y2, LineSpec2,...)- a function for constructing several dependencies on the graphic window, specifying a marker, color and line type for each line.
polar(x,y)– function for building dependency y = f(x) in polar coordinates.
meshgrid(x, y)- the function specifies a rectangular mesh on the plane ( x, y) in the form of two-dimensional arrays, which are defined by given vectors x And y.

Example: [ X,Y] = meshgrid(1:0.5:2,10:14). As a result we get:

X = 1 1.5 2 Y = 10 10 10

1 1.5 2 11 11 11

1 1.5 2 12 12 12

1 1.5 2 13 13 13

1 1.5 2 14 14 14
mesh(x,y,z)- the function displays a three-dimensional mesh constraint surface z = f(x, y).

surf(x,y,z)- the function displays a continuous mesh constraint surface z = f(x, y).

^

Online access to help information and documentation


There are several ways to obtain information about MATLAB system functions.

1 . Team help function_name. Typed directly into the MATLAB Command Window. For example: help sin.

2 . Menu HELP command window. This menu provides complete help information about the MATLAB system, containing more details and examples than the help command. The user can view the complete documentation for the MATLAB system (Contents submenu), or open a list of all functions in alphabetical order (Index submenu), or organize a search by name (Search submenu). It is also possible to open a list of functions by category (MATLAB Functions Listed by Category), open a list of examples by category (Index of Documentation Examples) and other features.
^

Examples:

a) Find linear algebra functions. Open the sequence of windows:

HELP – MATLAB Help - Finding Functions and Properties - Matlab Functions Listed by Category – Mathematics –- Linear Algebra

b) Find graphical functions for plotting:

HELP – MATLAB Help - Finding Functions and Properties - Matlab Functions Listed by Category- Graphics – Basic Plots and Graphs.
3 . Another way to obtain information about the MATLAB system is to access the Web server of The MathWorks company.

^

5.2 Linear algebra problems, calculating functions and plotting graphs

The MATLAB system is oriented towards working with arrays and the main problems of linear algebra are represented in this system in an economical form. Some typical linear algebra problems and their software implementation are discussed below.

Example1. Multiply vector
to vector
.

As you know, when multiplying vectors, the first vector must be a row, and the second must be a column vector, and they must have the same dimensions. Therefore, the solution is written in the form
a =

b =

c = a*b
Or
a =

b = ′

c = a*b
% Answer: With = 12.
PS: If you write it down b= , then the calculation is not performed, because b will be interpreted as a row vector.
Example2. Multiply matrix
to the matrix
.

To perform this operation correctly, the number of elements in the rows of matrix A must be equal to the number of elements in the columns of matrix B. The program will be written in the form:
a = ;

b = ;

The following will appear on the screen:

Example3. Solve a system of linear equations

In matrix form, this system will take the form: A*x = B, where:

Then the solution will be written as:
^A= % we set the matrix of coefficients for unknowns

B= % set the vector of free terms

X=A\B% system solution (Answer: X 1 =5, X 2 = 3, x 3 = 2)
Symbol \ used to solve systems of linear equations AX=B.
Example 4. For matrix A(see example 3) find the determinant and inverse matrix ( A-1) and count the product E=A A-1 . Solution:
A=

C = det(A) %det – the function calculates the determinant of the given matrix

D = inv(A) %inv - the function calculates the matrix inverse of the given one

Answer: C = -6; E = 1.0000 0 0

0.0000 1.0000 0.0000

0.0000 -0.0000 1.0000

In mathematical models, it is often necessary to evaluate the values ​​of expressions like y = f(x) at different values x and then represent these dependencies in graphical form. In MATLAB, such problems are easily solved. Below are examples.
^

Example 5. In the interval X= calculate values:

y = e x And z = 1 + x + x 2 /2 + x 3 /6 + x 4 /24

for evenly spaced 31 points. Build dependencies y = f(x) And z = f(x) on one graph (Cartesian coordinates). Values x, y, z do not display on the screen.

The solution will be written in the form:
x = (0: 0.1: 3)"; set the values X in the range from 0 to 3 in increments of 0.1

y = exp(x); calculate the vector values at

z = 1.0 +x + (x.^2)/2 + (x.^3)/6 - (x.^4)/24; calculate the vector values z

figure open the graphics window

plot(x,y," –g ",x,z," –k ") plot the function y = cos(x)

xlabel(" coordinata x ") give the name for the axis x

ylabel(" coordinata y ’) give a name for the axis y

title(" y=exp(x) "); give a title for the graph
Example 6. In the interval X = calculate values y = 0.5 ln (x+1) for evenly spaced 101 points. Build dependency y = f(x) in polar coordinates.
x= (0: pi/10: 10*pi)’;

y = 0.5*log( x + 1);

polar( x, y); build a graph of a function y = 0.5ln(x+1)
MATLAB allows you to easily create three-dimensional plots, i.e. type dependencies z = f(x, y), as shown in the following example.

Example 7. Build surface
at X= -1 to +1 in steps of 0.2 and at y= -1 to +1 in steps of 0.2.

The solution of the problem:
[x, y]=meshgrid([-1:0.2:1]);

z=x.*exp(- x.^2 - y.^2);

mesh( x,y,z);

surf( x,y,z);

PS: Graphics features are described above in the “Some Graphics Features” section.

^ 5.3. Solving nonlinear algebraic equations and approximating functions
The MATLAB system makes it much easier than in known programming languages ​​to solve systems of nonlinear (algebraic equations) and approximate table-specified functions.

Example 8. Solve the equation
with initial approximation x 0 = 5 and with iterations displayed on the screen:

The solution of the problem:
function ex1

options = optimset(" Display "," iter ");

Fzero(@f, 5, options)

function y = f(x)

y = x.^3-2*x-5;
PS: The first 3 statements are the main program, the last 2 statements are the function that defines the dependency
at different values X.

Below are brief descriptions of the MATLAB functions used to solve the problem.
fzero (@function name, x 0 ,options)– search for the zero of a function of one variable. The solution is sought in the vicinity of a given point x 0 by finding the interval where the function changes sign. If such an interval is not found, it returns Inf or NaN. Parameter options can set the display of intermediate results (iterations) on the screen and the accuracy of the calculation.
optimset(“Display”, “iter”) – a function for displaying iterations on the screen.
- displays the desired solution and the function value corresponding to this solution.
You can learn more about the functions used in HELP MATLAB.
Example 9. Solve the system of equations:

(5.1)

with initial approximations x 0 = 2,5; y 0 = 0.5 and with iterations displayed on the screen.

To solve, we move the right-hand sides of the equations to the left-hand sides

, (5.2)

so that there are zeros on the right-hand sides. Then we look for the minimum of a function consisting of the sum of these equations squared: . Since the sum of squares is always a positive number, the minimum of the function cannot be less than 0, and reaching the value f= 0 means that the values x And y, corresponding to this value, achieve the desired solutions of system (5.2).

The solution of the problem:
function ex2

options = optimset("Display","iter");

Fminsearch (@eq1, , options)

function f = eq1(x)

f = (x(1).^2 + x(2).^2 - 9).^2 + (x(1) + sin(x(2)) - 3).^2
PS: There is a correspondence between the unknowns in equations (5.1) and the program variables: x = x(1), y = x(2).

MATLAB function used to solve the problem:
fminsearch (@function name, [ initial approximations of variables ], options)– a function for finding the minimum value of a function of many variables.
^ Function approximation

Approximation of a table-specified function by a polynomial of the nth degree is performed using the least squares method (see paragraph 2.4).
Example 10. Perform approximation of a given point function x= 0 to 0.7 in steps of 0.1, y= 0.22 0.428 0.604 0.74 0.84 0.91 0.95 0.98 polynomial of the 2nd degree. Construct graphs of a given point function and an approximating polynomial:
The solution of the problem:
x=(0:0.1:0.7)" % array x consists of 8 numbers

y=" % array y consists of 8 numbers

p=polyfit(x,y,2)

table=

plot(x,y,"k*",x,f,"-g")

xlabel("coordinate x")

ylabel("coordinate y')

title( "Grafiki y(x), f(x)")
PS: Number of numbers in arrays x And y must be the same; table– the name of an array formed from 4 vectors: x, y, f And ( y-f). There are 8 4 = 32 numbers in this array. Array f also contains 8 numbers
polyfit (x, y, polynomial degree) - the function finds the coefficients a i polynomial p(x) degrees n, which approximates a given function y(x):
p(x) = a 1 x n + a 2 x n – 1 + … + a n x+a n+1
polyval(p, x) - function for calculating the values ​​of the polynomial p at given points x.

^ 5.4 Solving ordinary differential equations and calculating integrals
MATLAB easily solves ordinary differential equations (Cauchy problem) and calculates definite integrals using standard functions.

Example 11. Solve the differential equation using the standard ode45 function:

(5.3)
in the interval x= 0 to 30 at y(0)= 2 for a = 0,24.

Let us first represent equation (5.3) as a system of equations:

(5.4)

at initial values: y 1 (0) = 0; y 2 (0) = 2 to exclude the independent variable from the right side of (5.3) x.
The solution of the problem.
function ex_eqdif

Ode45(@dif1,,);

function dy=dif1(t,y)

% pravie parts difderensial. uravneniy

dy(2)=cos(y(1))-sin(y(1))-alfa*y(2);
PS: The function dif1(t,y) determines the right-hand sides of equations (5.4). There is a correspondence between the unknowns in equations (5.4) and the program variables: x = y(1), y = y(2).
ode45 (@ function name , [ integration interval ], [ initial conditions ] ) - the function is used to solve ordinary non-rigid differential equations using the 4th order Runge-Kutta method.
zeros(m,n)- the function generates an array of zeros of size
(Where m– number of equations, n=1).
global– the operator declares global variables. If instead of the variable alfa you substitute a number on the right-hand side, then you do not need to enter a global variable.
Example 12. Solve the Lotka-Volterra system of equations using the ode23 function:

(5.5)
at X=0 to 10 and initial conditions: y 1 (0) = 1; y 2 (0) = 1. Parameters = 0.01 and = 0.02 set as global values. Graph functions y 1 (x), y 2 (x)).
The solution of the problem.
function Lotka_Volterra

global alpha beta

alpha=0.01; beta=0.02;

Ode23(@lotka,,);

plot(t,y); %Graphing y 1 (t) And y 2 (t)

function dy=lotka(t,y)

global alpha beta

dy(1)=y(1)-alpha*y(1)*y(2);

dy(2)=-y(2)+beta*y(1)*y(2);
PS: The function lotka(t,y) determines the right-hand sides of equations (5.5). There is a correspondence between the unknowns in equations (5.5) and the program variables: y 1 = y(1), y 2 = y(2).
ode23 (@ function name , [ integration interval ], [ initial conditions ] ) - the function is used to solve ordinary non-stiff differential equations using the low order Runge-Kutta method.
^ Calculation of integrals
Example 13. Calculate the integral:

(5.6)
using Simpson's method (standard quad function) and plot the integrand function in the interval X= in increments of 0.1.

The solution of the problem:
function int1

y=1./(x.^3-2*x-5);

plot(x,y); %Building a graph y(x)

Q = quad(@myfun,0,2)

function y = myfun(x)

y = 1./(x.^3-2*x-5);
PS: The integrand function is calculated in the function myfun(x) for various values X
quad(@subintegral_function_name, a, b)- numerical calculation of the integral using the adaptive Simpson method, where: a and b are the limits of integration.

Example 14. Calculate the integral:

(5.7)
by Simpson's method (standard quad function) with y= 10 o (convert degrees to radians). For value y use a global variable in the program.
The solution of the problem.
function int2

Q = quad(@myfun,0,pi/2);

function y = myfun(x)

y=1./sqrt(1-(sin(teta)*sin(x)).^2);
PS: Size y the program corresponds to a global variable theta. The value of the integral is obtained in the variable Q.

^

Control questions

1. What is a scalar, vector, matrix? Give definitions and examples.
2. What actions can be performed with vectors and matrices? Give examples.
3. How are arrays formed in MATLAB: one-dimensional and two-dimensional? Give examples.
4. Define transposed vector and transposed matrix. How are they formed in MATLAB? Give examples.
5. Define determinant and inverse matrix. How are they calculated in MATLAB? Give examples.
6. Elementary functions and their recording in MATLAB. Give examples.
7. Perform the following manually (without the help of a computer):

Multiply vector P by vector Y;

Multiply matrix G by vector Y;

Multiply matrix G by matrix F,


8. Write a program in MATLAB to perform the actions specified in question 7.

9. Given a matrix
. Determine its inverse matrix without the help of a computer - A -1 .

10. Find the determinant of the matrix without the help of a computer
.

11. Given a system of linear equations:
(1P)

or in matrix form Cּ X= B.

Create a MATLAB program for solving this system with determining the determinant of the matrix WITH.
12. Using MATLAB, find the matrix inverse of a matrix WITH(from question 11). How to use a matrix WITH-1 find unknowns x 1 , x 2 , x 3 , x 4 from the system (1P)?
13. Solve a system of equations using MATLAB
(2P)

Find the reason for failure if the system (2P) is not solved. Determine the determinant of the coefficient matrix for unknowns.
14.For the conditions of question 7, write a program in MATLAB:

Multiplying the 1st row of matrix G by the 2nd column of matrix F;

Multiplying the 2nd row of matrix F by the 2nd column of matrix G.
15. Using MATLAB to determine the braking distance length ^S(m) as a function of speed V f(m/s):

where the speed is specified in the interval V f= 10…40 (velocity step is 2m/s), plot dependencies: S = f(V f ) And V f = φ(S).
16. Solve graphically (using MATLAB) the equation:

(3P)

in the interval x= 0…10π in steps of 0.1π. How many roots does equation (3P) have?
17. Using MATLAB in Cartesian coordinates, construct a circle with a center at a point x = 1, y= 1 and radius equal to 1. Along the axis x select step Δ x= 0,05.
18. Using MATLAB to build a dependency y = ln(x + 1) in Cartesian coordinates in the interval x= 0…4π with a step of 0.2π, as well as the dependence r = ln(φ + 1) in polar coordinates in the same interval and with the same step along φ .
19. Using MATLAB on one graph in polar coordinates with steps
= 0.1 in the interval, construct dependencies (spirals with 3 turns):
A) r = 0,4φ + 0,03φ 2 (4P)

b) dependence (4P), but twisted in the opposite direction.
20. Using MATLAB, construct a 3-dimensional surface:

in area [ x, y] = [-1:0,1:1] [-2:0,1:2].
21. Using MATLAB, construct a 3-dimensional surface:

in area [ x, y] = .
22. Using MATLAB using the program fzero
x 0 = 2km; x f= 8 km.
27. A tabular dependence of fuel consumption (for a passenger car) on operating time is given.

polyfit, polyval) find the approximating dependence G = f(t) polynomial of the 3rd degree and determine the average approximation error.
28. A tabular dependence of the cost of a passenger car on the operating time is given.


t(year)

0

1

2

3

5

7

10

C ($)

11500

8700

7200

6000

5500

5000

4600

Using the MATLAB package (functions polyfit, polyval) find approximating dependencies C = f(t) polynomials of 2nd and 3rd degree and compare the maximum approximation errors.
29. Using MATLAB (function ode45

(5P)
in the interval x= 0…2 at initial conditions: x 0 = 0, y 0 = 1. First transform equation (5P) into a system of 2 differential equations.
30. Using MATLAB (function ode23) solve the ordinary differential equation:

(6P)
in the interval x= 0…5 at initial conditions: x 0 = 0, y 0 = 2. First transform equation (6P) into a system of 2 differential equations.
31. Using MATLAB (function ode45

in the interval t= 0…8π at initial conditions: t =0; x 0 = 1; y 0 = 1.
32. Using MATLAB (function ode45) solve the system of ordinary differential equations:

in the interval = 0.3…4 at initial conditions: = 0,3; x 0 = 1; y 0 = 0.
33. Using MATLAB (function ode23) solve the ordinary differential equation:

(7P)

in the interval t= 0…3s at initial conditions: t = 0, r 0 = 0,
and ω = 2π (rad/s). First, transform equation (7P) into a system of first-order differential equations.

Arrays are the main objects in the system MATLAB : in versions 4.x only allowedone-dimensional arrays- vectors - and two-dimensional arrays - matrices; in version 5.0 it is possible to use multidimensional arrays - tensors. Below we describe the functions of forming arrays and matrices, operations on matrices, special matrices within the system MATLAB versions 4.x.

Formation of special type arrays

  • ZEROS - formation of an array of zeros
  • ONES - formation of an array of units
  • EYE - formation of a unit matrix
  • RAND - formation of an array of elements distributed according to a uniform law
  • RANDN - formation of an array of elements distributed according to the normal law
  • CROSS - vector product
  • KRON - formation of a tensor product
  • LINSPACE - formation of a linear array of equally spaced nodes
  • LOGSPACE - formation of logarithmic grid nodes
  • MESHGRID - formation of nodes of two-dimensional and three-dimensional meshes
  • : - formation of vectors and submatrices

Operations on matrices

  • DIAG - formation or extraction of matrix diagonals
  • TRIL - formation of a lower triangular matrix (array)
  • TRIU - formation of an upper triangular matrix (array)
  • FLIPLR - rotation of the matrix relative to the vertical axis
  • FLIPUD - rotation of the matrix relative to the horizontal axis
  • ROT90 - matrix rotation 90 degrees
  • RESHAPE - matrix size conversion

Special matrices

  • COMPAN - accompanying matrix of the characteristic polynomial
  • HADAMARD - Hadamard matrix
  • HANKEL - Hankel matrix
  • HILB, INVHILB - Hilbert matrix
  • MAGIC - magic square
  • PASCAL - Pascal matrix
  • ROSSER - Rosser matrix
  • TOEPLITZ - Toeplitz matrix
  • VANDER - Vandermonde matrix
  • WILKINSON - Wilkinson matrix

CONV, DECONV

Convolution of one-dimensional arrays

Syntax:

Z = conv(x, y)
= deconv(z, x)

Description:

If specified one-dimensional arraysx and y are of length m = length(x) and n = length(y), respectively, then the convolution z is a one-dimensional array of length m + n -1, the kth element of which is determined by the formula

The function z = conv(x, y) computes the convolution z of two one-dimensional arrays x and y.

Considering these arrays as samples of two signals, we can formulate the convolution theorem in the following form:
If X = fft() and Y = fft() are size-matched Fourier transforms of signals x and y, then the relation conv(x, y) = ifft(X.*Y) is valid.

In other words, convolution of two signals is equivalent to multiplication of the Fourier transforms of these signals.

The function = deconv(z, x) performs the inverse operation of convolution. This operation is equivalent to determining the impulse response of the filter. If the relation z = conv(x, y) is true, then q = y, r = 0.

Related Features: Signal Processing Toolbox.

1. Signal Processing Toolbox Users Guide. Natick: The MathWorks, Inc., 1993.

Setting the template of matrices and vectors (Matrix...)

The Matrix... operation provides the definition of vectors or matrices. As is known, a matrix is ​​an object specified by its name in the form of an array of data MathCAD uses one-dimensional arraysvectors and two-dimensional matrices themselves

A matrix is ​​characterized by the number of rows (Rows) and the number of columns (Columns). Thus, the number of matrix elements or its dimension is equal to Rows x Columns The elements of matrices can be numbers, constants, variables and even mathematical expressions. Accordingly, matrices can be numerical and symbolic

If you use the Matrix... operation, then a small window will appear in the current window, allowing you to set the dimension of a vector or matrix (see Figure 515 on the right). To do this, you need to specify the number of rows Rows and the number of columns Columns By pressing the Enter key or pointing the mouse cursor at the image of the key Insert in the window, you can display a matrix or vector template (the vector has one of the dimension parameters equal to 1)

The template contains border brackets and small dark rectangles to indicate where you can enter values ​​(numeric or character) for the vector or matrix elements. One of the rectangles can be made active (by marking it with the mouse cursor). At the same time, it is enclosed in a corner. This indicates that the values ​​of the corresponding element will be entered into it. Using the cursor keys, you can move horizontally through all the rectangles and enter all the elements of the vector or matrix.


Rice. 5. 15 Outputting vector and matrix templates and filling them in

While elements of vectors or matrices are being entered, empty templates are displayed without any comments. However, if you finish entering before the templates are completely filled, the system will display an error message: an unfilled template will turn red. The output of a non-existent matrix or erroneous indication of its indices is also displayed in red.

If you use the Insert operation when the matrix template is already output, the matrix is ​​expanded and its size increases. The Delete button allows you to remove the expansion of the matrix by deleting a row or column from it.

Each matrix element is characterized by an indexed variable, and its position in the matrix is ​​indicated by two indices: one indicating the row number, the other the column number. To set an indexed variable, you first need to enter the name of the variable, and then go to the set of indexes by pressing the key that enters the symbol]. The row index is specified first, followed by the column index, separated by commas. Examples of output of indexed variables (elements of matrix M) are also given in Fig. 5.14.

A matrix degenerate into one row or one column is a vector. Its elements are indexed variables with one index. The lower limit of the indexes is set by the value of the ORIGIN system variable. Typically its value is set to 0 or 1.

If you notice an error, select a piece of text and press Ctrl+Enter
SHARE: