Syms matlab что это
Перейти к содержимому

# Syms matlab что это

## Syms matlab что это

Symbolic variables in MATLAB are variables that store a literal, such as x, \$, as a symbol. This means that whatever a symbolic variable stores are not a value the computer can compute until it is assigned a numeric value. It is just a symbolic representation. To understand the same, see the following case.
If a user needs to display an equation like follows:

This can be done with the usage of symbolic variables. One would make a symbolic variable, say x and assign them values x + 1. Then, typing the following will display the above equation.

Now, we shall see how to create variables, functions, and matrix symbolic variables with an example of each.

## Matlab Syms

By Priya Pedamkar ### Introduction to Matlab Syms

In MATLAB, syms is used as a shortcut to the inbuilt function sym. This function can be used to create symbolic variables. The Symbolic variables used in MATLAB are not constants like the regular variables; we do not assign values to them. These are used to solve various expressions with the help of functions available in Symbolic Math Toolbox. The syms function creates a symbolic object that is automatically assigned to a MATLAB variable with the same name.

## Символьные вычисления в MATLAB

В MATLAB входит пакет-расширение символьной математики Symbolic Mathematics Toolbox, позволяющий выполнять символьные вычисления и вычисления с переменной точностью.

При символьных операциях задания на вычисление определяются в виде символьных (формульных) выражений и результаты вычислений также получаются в символьном виде. Такие вычисления называют также компьютерной алгеброй. Примерами подобных символьных операций являются дифференцирование, интегрирование, вычисление пределов, решение уравнений и др.

Перечень входящих в пакет символьных команд и функций можно получить с помощью команды help symbolic.

MATLAB в символьных вычислениях использует специальный тип данных, называемых символьными объектами Символьные переменные создаются с помощью заключения их имен в апострофы, например >> x=sym(‘х’);

или команды вида >> syms х у w;

X=sym(’а л 2+2*а*Ь+Ь л 2′)

создает символьное представление переменной X.

Для численного вычисления значений символьных выражений может использоваться функция subs.

Пример:

Пример:

» diff(cos(х Л 3)) ans =

Интегрирование функции одной переменной, т. е. вычисление вида 7= Г/(х)б7х , выполняет функция I = int

Пример: » syms х » I=int(1/(sqrt(1-х А 2)),х) I = asin(x).

Функция I = Mf x, a, b) вычисляет определенный интеграл от функции f по переменной х в пределах от а до b .

Разложение в ряд Тейлора выполняется с помощью функции r=taylor(f п, х), где f — функция, х — переменная, п — порядок разложения.

» taylor(sin(х),7,х) ans = х-1/6*х А 3+1/120*х Л 5

Функция х, а) позволяет определить предел функцииfix) при

» limit(sin(х)/х, х, 0) ans = 1.

Функция г = simplify(S) упрощает символическое выражение (массив) S.

Пример: » syms х >> г = simplify(sin(х) A 2+cos(х) Л 2) г = 1.

Функция г = solfe(eq) выполняет символьное решение уравнения eq.

» syms а b с х » x=solve(а*х А 2+Ь*х+с) х =

Функция г = solve(eql, eq2. eqn) позволяет решить систему уравнений п переменных, если такое решение аналитически разрешимо.

Функции F = fourier(f), L = laplacetf), Z = ztrans(f) вычисляют преобразование Фурье, преобразование Лапласа и Z-преобразование в символьном виде.

Соответственно функции f = ifourier(F), f = ilaplace(L), f = = iztrans(Z) используются для вычисления обратных преобразований.

X = s/ (s A 2+w /s 2)

• 2 2
• s + w

Использование символьных преобразований предполагает четкое понимание задачи вычислений и определенный уровень математической культуры.

## MATLAB Programming/Advanced Topics/Toolboxes and Extensions/Symbolic Toolbox

### Introduction to the Symbolic Math Toolbox [ edit | edit source ]

The symbolic toolbox is a bit difficult to use but it is of great utility in applications in which symbolic expressions are necessary for reasons of accuracy in calculations. The toolbox simply calls the MAPLE kernel with whatever symbolic expressions you have declared, and then returns a (usually symbolic) expression back to MATLAB. It is important to remember that MAPLE is not a numeric engine, which means that there are certain things it doesn’t let you do that MATLAB can do. Rather, it is useful as a supplement to provide functions which MATLAB, as a numerical engine, has difficulty with.

The symbolic math toolbox takes some time to initialize, so if nothing happens for a few seconds after you declare your first symbolic variable of the session, it doesn’t mean you did anything wrong.

The MATLAB student version comes with a copy of the symbolic math toolbox.

### Symbolic Variables [ edit | edit source ]

You can declare a single symbolic variable using the ‘sym’ function as follows.

You can create arrays of symbolic expressions like everything else:

Symbolic variables can also be declared many at a time using the ‘syms’ function. By default, the symbolic variables created have the same names as the arguments of the ‘syms’ function. The following creates three symbolic variables, a b and c.

### Symbolic Numbers [ edit | edit source ]

Symbolic numbers allow exact representations of fractions, intended to help avoid rounding errors and representation errors. This section helps explain how to declare them.

If you try to add a number into a symbolic array it will automatically turn it into a symbolic number.

Symbolic numbers can also be declared using the syntax a(3) = sym(‘number’). The difference between symbolic numbers and normal MATLAB numbers is that, if possible, MAPLE will keep the symbolic number as a fraction, which is an exact representation of the answer. For example, to represent the number 0.5 as a fraction, you can use:

Here, of course, MATLAB would normally return 0.5. To make MATLAB change this back into a ‘double’, type:

Other class conversions are possible as well; for instance, to change it into a string use the ‘char’ function. There is no function to directly change a symbolic variable into a function handle, unfortunately.

A caveat: Making a symbolic variable of negative exponentials can create problems if you don’t use the correct syntax. You cannot do this:

MAPLE is thus more picky about what operators you can use than MATLAB.

### Symbolic Functions [ edit | edit source ]

You can create functions of symbolic variables, not just the variables themselves. This is probably the most intuitive way to do it:

If you do it this way, you can then subsequently perform substitution, differentiation, and so on with respect to any one of these variables.

If you want to create an actual function, it’s not much harder:

#### Substituting Values into Symbolic Variables [ edit | edit source ]

Substitutions can be made into functions of symbolic variables. Suppose you defined the function f = a + b + c and wish to substitute a = 3 into f. You can do this with the following syntax:

Notice the form of this function call. The first argument is the name of the function you wish to substitute into. The second can be either the name of the symbolic variable you want to plug in for or its present value, but if you want to avoid confusion they should be the same anyway. The third argument is the value you want to plug in for that variable.

The value you’re plugging in need not be a number. You can also plug in other variables (including those already present in the function) by using strings. Using the same f:

If x is already a symbolic variable you can omit the quotes (but if it’s not you’ll get an undefined variable error):

Multiple substitutions are allowed; to do it, just declare each of them as an array. For example, to plug in 1 for a and 2 for b use:

Finally, if you substitute for all of the symbolic values in a function MATLAB automatically changes the value back into a double so that you can manipulate it in the MATLAB workspace.

#### Using Functions with Symbolic Matrices as Inputs [ edit | edit source ]

Unfortunately, symfun does not seem to allow using a symbolic matrix as a function input. You can manually add each element of the matrix to the list of input variables, or even use subs to iteratively substitute the input values if you’re just using a symbolic expression, but both solutions would require typing out all of the indexing. Instead, the simplest path is to declare an anonymous function:

#### Algebraic Function Manipulations [ edit | edit source ]

The symbolic math toolbox allows you several different ways to manipulate functions. First off you can factor a function using ‘factor’ and multiply it out using ‘expand’:

The ‘collect’ function does the same thing as the ‘expand’ function but only affects polynomial terms. ‘Expand’ can also be used to expand trigonometric and logarithmic/exponential functions with the appropriate identities.

The Horner (nested) representation for a function is given by ‘horner’:

This representation has a relatively low number of operations required for its evaluation compared to the expanded version and is therefore helpful in making calculations more efficient.

A common problem with symbolic calculations is that the answer returned is often not in its simplest form. MATLAB’s function ‘simple’ will perform all of the possible function manipulations and then return the one that is the shortest. To do this do something like:

### Algebraic Equations [ edit | edit source ]

The symbolic math toolbox is able to solve an algebraic expression for any variable, provided that it is mathematically possible to do so. It can also solve both single equations and algebraic systems.

#### Solving Algebraic Equations With a Single Variable [ edit | edit source ]

MATLAB uses the ‘solve’ function to solve an algebraic equation. The syntax is solve(f, var) where f is the function you wish to solve and var is the variable to solve for. If f is a function of a single variable you will get a number, while if it is multiple variables you will get a symbolic expression.

First, let us say we want to solve the quadratic equation x^2 = 16 for x. The solutions are x = -4 and x = 4. To do this, you can put the function into ‘solve’ directly, or you can define a function in terms of x to solve and pass that into the ‘solve’ function. The first method is rather intuitive:

Either of these two syntax works. The first must be in quotes or you get an ‘invalid assignment’ error. In the second, x must be defined as a symbolic variable beforehand or you get an ‘undefined variable’ error.

For the second method you assign a dummy variable to the equation you want to solve like this:

Note that since MATLAB assumes that y = 0 when you’re solving the equation, you must subtract 16 from both sides to put the equation into normal form.

#### Solving Symbolic Functions for Particular Variables [ edit | edit source ]

The format for doing this is similar to that for solving for a single variable, but you will get a symbolic function rather than a number as output. There are a couple of things to look out for though.

As an example, suppose that you want to solve the equation y = 2x + 4 for x. The expected solution is x = (y-4)/2. Lets see how we can get MATLAB to do this. First let’s look at how NOT to do it:

What has happened here? The MATLAB toolbox assumes that the ‘y’ you declared is 0 for the purposes of solving the equation! So it solved the equation 2x + 4 = 0 for x. In order to do what you intended to do you have to put your original equation, y = 2x + 4, into normal form, which is 2x + 4 — y = 0. Once this is done, you need to assign a ‘dummy’ variable like this:

This is, of course, the same thing as what we expected. You could also just pass the function into the ‘solve’ function like this, as done with functions of a single variable:

The first method is preferable, because once it is set up it is much more flexible to changes in the function. In the second method you would have to change every call to ‘solve’ if you changed the function at all, whereas in the first you only need to change the original definition of S.

#### Solving Algebraic Systems [ edit | edit source ]

The ‘solve’ command also allows you to solve systems of algebraic equations, and will attempt to return all solutions to these systems. As a first example, let us consider the linear system

which has the solution (a,b) = (0,3). You can tell MATLAB to solve it as follows:

If only one output variable is specified but there are multiple equations, MATLAB will return the solutions in a struct array:

The good thing about this is that the fields have the same names as the original variables, whereas in the other form it is easy to get confused which variable is going into which spot in the array. In addition, the struct array is more convenient for large systems.

Now let us look at a slightly more complex example:

This has solutions (a,b) = (0,1) and (a,b) = (1,0). Now putting this into MATLAB gives:

Here both solutions are given, a(1) corresponds to b(1) and a(2) corresponds to b(2). To get one of the solutions into a single array together you can use normal array indexing, as in:

### Analytic Calculus [ edit | edit source ]

MATLAB’s symbolic toolbox, in addition to its algebraic capabilities, can also perform many common calculus tasks, including analytical integration, differentiation, partial differentiation, integral transforms, and solving ordinary differential equations, provided the given tasks are mathematically possible.

#### Differentiation and Integration with One Variable [ edit | edit source ]

Differentiation of functions with one or more variables is achieved using the ‘diff’ function. As usual, you can either define the function before the differentiation (recommended for M files) or you can manually write it in as an argument (recommended for command-line work). If there is only one symbolic variable in the expression, MATLAB assumes that is the variable you are differentiating with respect to. The syntax is simply:

Integration, similarly, is achieved using the ‘int’ function. Only specifying the function results in an indefinite integral, or the antiderivative of the function.

Note that if you only specify one output argument (or none at all), the ‘int’ function omits the integration constant. You just have to know it’s there.

To do a definite integral on a one-variable function, simply specify the beginning and end points.

#### Differentiation and Integration of Multivariable Functions [ edit | edit source ]

A convenient way of representing the derivatives of multivariate functions (partial derivatives) is with the Jacobian, which is performed by the ‘jacobian’ function. To use it, you should define an array of symbolic functions and then just pass it to the function (note the difference between the use of this function, which requires all equations to be in the same array, and the use of ‘solve’, which requires you to separately pass each equation):

Note that the first row is the gradient of f(1) and the second the gradient of f(2).

If you only want a specific partial derivative, not the entire Jacobian, you can call the ‘diff’ function with the function you want to differentiate and the variable you wish to differentiate with respect to. If none is specified, differentiation occurs with respect to the variable closest to ‘x’ in the alphabet.

It is worth noting that to complete an implicit differentiation, one can explicitly state the implicit assumption by multiplying the differentiated function by d d x i <\displaystyle <\frac >>> , where x i <\displaystyle x_> is the ith variable in a multivariable equation.

To do:
Put in an example of this for a simple implicit function (like x 2 + y 2 = 4 <\displaystyle x^<2>+y^<2>=4> or something)

Indefinite integration of multivariate functions works the same as for single functions; pass the function and MATLAB will return the indefinite integral with respect to the variable closest to x:

This is the integral with respect to b. To avoid confusion, you can specify the variable of integration with a second argument, as with differentiation.

Definite integration (as far as I can tell) can only be done with respect to one variable at a time, and this is done by specifying the variable, then the bounds:

#### Analytic Solutions to ODEs [ edit | edit source ]

MATLAB can solve some simple forms of ODEs. Unlike with the integration and algebraic solving techniques, the syntax for the differential equation solver required that you put the function in manually in a specific manner. The derivatives can be specified using the symbol ‘DNV’, where N is the order of the derivative and V is the variable that is changing. However, newer versions of MATLAB support entering differential equations in the form of symbolic equalities. For example, suppose you seek the solution to the equation d 2 d t 2 x = − x <\displaystyle <\frac >>>x=-x> , the solutions to which are of the form x(t) = A*cos(t) + B*sin(t). You would put this equation into the ‘dsolve’ function as follows:

Unlike the ‘int’ function, dsolve includes the integration constants. To specify initial conditions, just pass extra arguments to the ‘dsolve’ function as strings. If x'(0) = 2 and x(0) = 4 these are inserted as follows:

Note that the initial conditions can also be passed as strings.

MATLAB can also solve systems of differential equations. An acceptable syntax is to pass each equation as a separate string, and then pass each initial condition as a separate string:

The ‘dsolve’ function, like ‘solve’, thus returns the solution as a structure array, with field names the same as the variables you used. Also like ‘solve’, you can place the variables in separate arrays by specifying more than one output variable.

#### Integral Transforms [ edit | edit source ]

MATLAB’s symbolic math toolbox lets you find integral transforms (in particular, the Laplace, Fourier, and Z-transform) and their inverses when they exist. The syntax is similar to the other symbolic math functions: declare a function and pass it to the appropriate functions to obtain the transform (or inverse).