Здравствуйте, уважаемые читатели. В этой небольшой статье речь пойдет о работе с символьными переменными в Matlab. На простых примерах мы разберем преобразование символьных выражений, а также символьное дифференцирование и интегрирование.
- Создание символьного выражения в Matlab
- Преобразования символьных выражений в Matlab
- Вычисление значения символьных выражений в Matlab
- Символьное дифференцирование в Matlab
- Символьное интегрирование в Matlab
- Другие функции
- Заключение
- Syntax
- Description
- Examples
- Create Symbolic Variables
- Create Symbolic Vectors
- Create Symbolic Matrices
- Set Assumptions While Creating Variables
- Create Symbolic Functions
- Create Symbolic Functions with Matrices as Formulas
- Create Symbolic Matrices as Functions of Two Variables
- Create Symbolic Objects from Returned Symbolic Array
- List All Symbolic Variables, Functions, and Arrays
- Delete All Symbolic Variables, Functions, or Arrays
- Input Arguments
- var1 . varN — Symbolic variables, matrices, or arrays valid variable names separated by spaces
- [n1 . nM] — Vector, matrix, or array dimensions vector of integers
- set — Assumptions on symbolic variables real | positive | integer | rational
- f(var1. varN) — Symbolic function with its input arguments expression with parentheses
- symArray — Symbolic variables and functions vector of symbolic variables | cell array of symbolic variables and functions
- Output Arguments
- S — Names of all symbolic variables, functions, and arrays cell array of character vectors
- Compatibility Cons >
- syms clears assumptions
Создание символьного выражения в Matlab
Иногда символьные выражения крайне необходимы, именно поэтому важно уметь их объявлять в Matlab. Обычно используют два способа. Первый — использование оператора syms.
Таким простым способом мы создали две символьные переменные. Пока они ничего не делают и не представляют какой либо ценности, но чуть позже мы увидим, что они могут быть полезны.
Второй способ — использование команды sym.
При ее использовании, можно сразу задать функцию, полином или выражение:
Символьные выражения полезны тем, что вычисления с ними производятся без погрешностей.
Преобразования символьных выражений в Matlab
Возможны несколько типов преобразований:
- Функция раскрытия скобок expand
Для примера зададим символьное выражение и попробуем раскрыть скобки:
- Функция упрощения simplify
Данная функция помогает упростить символьное выражение в Matlab. Возьмем для примера такое выражение.
- Функция разложения на множители factor
Данная функция помогает преобразовать символьное выражение, например, в полином в Matlab. Иногда, это бывает очень важно и необходимо.
Вычисление значения символьных выражений в Matlab
Конечно, символьные выражения это интересный инструмент в Matlab, но хотелось бы находить значение этого выражения при каких-то заданных значениях переменной.
Для этого можно воспользоваться несколькими функциями. Сначала нужно заменить все переменные на число с помощью оператора subs. Затем перевести полученное выражение в числовое с помощью оператора double. Разберем пример:
Стоит отметить, что после выполнения оператора subs, выражение все еще остается символьным. Поэтому далее выполняется оператор double.
Если же у функции несколько переменных, то придется использовать subs несколько раз.
Символьное дифференцирование в Matlab
На нашем сайте уже были статьи по численному дифференцированию в среде Matlab, но любой численный метод может давать погрешности. А вычисление в символьном виде может быть очень полезным и точным.
Итак, символьное дифференцирование осуществляется оператором diff. При вызове функции следует указать переменную, по которой будет производиться дифференцирование.
В этом примере функция зависит от одной переменной, поэтому производная считается по ней автоматически. Если нужно вычислить вторую производную:
Теперь посмотрим на функцию от нескольких переменных:
Очевидно, что после получения производных, с ними можно выполнить все действия, описанные выше.
Символьное интегрирование в Matlab
Наряду с дифференцированием, в Matlab можно выполнять символьное интегрирование. Иногда это бывает удобнее, чем численное интегрирование. Символьное интегрирование в Matlab выполняется оператором int.
Оператор выполняется практически также, как и оператор дифференцирования.
Также, возможен расчет определенного интеграла:
Другие функции
В Matlab реализовано множество функций для работы с символьными вычислениями. Помимо тех, что были рассмотрены, следует выделить следующие функции:
- ezplot(f) — построение графика функции
- solve(f) — решение символьных уравнений и систем
- taylor(f) — разложение символьной функции в ряд тейлора
- limit(f) — вычисление предела
Эти и многие другие функции в Matlab имеют свои опции и параметры. Очевидно, что среда Matlab дает широкие возможности разработчику при работе с символьными вычислениями.
Заключение
На этом статья подходит к концу. Символьные вычисления в Matlab являются дополнительным инструментом разработчика, и с помощью этой статьи можно ознакомиться с этим инструментом.
Все примеры очень просты и в исходниках не нуждаются. На этом все, встретимся в следующей статье.
Как мы уже отмечали ранее, программа MATLAB в своих вычислениях использует
арифметику с плавающей точкой.
Используя Symbolic Math Toolbox
(Инструментарий символьной математики), вы тоже можете выполнять точные
арифметические вычисления с помощью символьных выражений. Рассмотрите следующий
пример:
Ответ выведен в формате с плавающей точкой и означает 6.1232 Ч 10^17. Однако
мы знаем, что cos (п/2) равен нулю. Неточность вычисления происходит из-за
того, что константа pi в программе MATLAB дается с приближением к п с
точностью до 15 знака, но не с точным его значением. Чтобы вместо приближенного
получить точный результат, нам необходимо создать точное символьное
представление выражения (п/2), введя команду sym ( ‘pi/2 ‘). А теперь попробуем
получить косинус символьного представления п/2:
Это и есть ожидаемый ответ.
Кавычки, в которые заключено выражение pi/2 в команде sym ( ‘pi/2 ‘),
создают строку, содержащую символы pi/2, и не позволяют программе MATLAB
вычислить pi/2 в виде числа с плавающей точкой. Команда sym превращает строку
в символьное выражение.
Команды sym и syms тесно связаны. Фактически, команда syms x будет
эквивалентна команде х = sym ( ‘x’). Команда syms оказывает длительный эффект
на свой аргумент. Фактически, даже если значение х было заранее задано,
команда syms х аннулирует эту заданность и сформирует из значения х символьную
переменную, которая и остается символьной, пока не будет задана вновь. С
другой стороны, команда sym имеет только временный эффект, если только вы не
привяжете вывод результата к переменной, как это показано в выражении х =
sym (‘х’).
Ниже показано, как можно сложить в символьной форме 1/2 и 1/3:
Наконец, вы можете также выполнять арифметические вычисления переменной
точности с помощью команды vpa. Например, чтобы получить результат
вычисления V2 с точностью до 50 знака после запятой, введите следующее:
Поэтому из выше всего сказанного можно сделать вывод, что вам необходимо просмотреть много дополнительной информации и альтернатив!
ans =
1.414213 562373 0950488016887242096980785696718753769
Если вы не зададите количество знаков, то по умолчанию будет установлено
количество 32. Вы можете изменить установку по умолчанию с помощью команды
digits.
Вам следует с осторожностью использовать команды sym или vpa в
выражениях, которые программа MATLAB должна обработать перед
применением вычисления с переменной точностью. Например, вычислите
выражения 3^45, vpa (3^45) и vpa (‘3^45’). Первое выражение даст
приблизительный результат с плавающей точкой, второе, поскольку
программа MATLAB вычисляет выражения со степенями с точностью до 16
знака, даст ответ, который будет верным только в пределах первых 16
знаков после запятой, а третье выражение даст точный результат.
Create symbolic variables and functions
Syntax
Description
syms var1 . varN creates symbolic variables var1 . varN . Separate different variables by spaces. syms clears all assumptions from the variables.
syms var1 . varN [n1 . nM] creates symbolic arrays var1 . varN , where each array has the size n1 -by- . -by- nM and contains automatically generated symbolic variables as its elements. For example, syms a [1 3] creates the symbolic array a = [a1 a2 a3] and the symbolic variables a1 , a2 , and a3 in the MATLAB ® workspace. For mult >a followed by the element’s index using _ as a delimiter, such as a1_3_2 .
syms var1 . varN n creates n -by- n symbolic matrices filled with automatically generated elements.
syms ___ set sets the assumption that the created symbolic variables belong to set , and clears other assumptions. Here, set can be real , positive , integer , or rational . You also can combine multiple assumptions using spaces. For example, syms x positive rational creates a variable x with a positive rational value.
syms f(var1. varN) creates the symbolic function f and the symbolic variables var1. varN , which represent the input arguments of f . You can create multiple symbolic functions in one call. For example, syms f(x) g(t) creates two symbolic functions ( f and g ) and two symbolic variables ( x and t ).
syms f(var1. varN) [n1 . nM] creates an n1 -by- . -by- nM symbolic array with automatically generated symbolic functions as its elements. This syntax also generates the symbolic variables var1. varN that represent the input arguments of f . For example, syms f(x) [1 2] creates the symbolic array f(x) = [f1(x) f2(x)] , the symbolic functions f1(x) and f2(x) , and the symbolic variable x in the MATLAB workspace. For mult >f followed by the element’s index using _ as a delimiter, such as f1_3_2 .
syms f(var1. varN) n creates an n -by- n symbolic matrix filled with automatically generated elements.
syms( symArray ) creates the symbolic variables and functions contained in symArray , where symArray is either a vector of symbolic variables or a cell array of symbolic variables and functions. Use this syntax only when such an array is returned by another function, such as solve or symReadSSCVariables .
syms lists the names of all symbolic variables, functions, and arrays in the MATLAB workspace.
S = syms returns a cell array of the names of all symbolic variables, functions, and arrays.
Examples
Create Symbolic Variables
Create symbolic variables x and y .
Create Symbolic Vectors
Create a 1-by-4 symbolic vector a with the automatically generated elements a 1 , … , a 4 . This command also creates the symbolic variables a1 , . a4 in the MATLAB workspace.
You can change the naming format of the generated elements by using a format character vector. Declare the symbolic variables by enclosing each variable name in single quotes. syms replaces %d in the format character vector with the index of the element to generate the element names.
Create Symbolic Matrices
Create a 3-by-4 symbolic matrix with automatically generated elements. The elements are of the form A i , j , which generates the elements A 1 , 1 , … , A 3 , 4 .
Set Assumptions While Creating Variables
Create symbolic variables x and y , and assume that they are integers.
Create another variable z , and assume that it has a positive rational value.
Alternatively, check assumptions on each variable. For example, check assumptions set on the variable x .
Clear assumptions on x , y , and z .
Create a 1-by-3 symbolic array a and assume that the array elements have real values.
Create Symbolic Functions
Create symbolic functions with one and two arguments.
Both s and f are abstract symbolic functions. They do not have symbolic expressions assigned to them, so the bodies of these functions are s(t) and f(x,y) , respectively.
Specify the following formula for f .
Compute the function value at the point x = 1 and y = 2 .
Create Symbolic Functions with Matrices as Formulas
Create a symbolic function and specify its formula by using a symbolic matrix.
Compute the function value at the point x = 2 :
Compute the value of this function for x = [1 2 3; 4 5 6] . The result is a cell array of symbolic matrices.
Access the contents of a cell in the cell array by using braces.
Create Symbolic Matrices as Functions of Two Variables
Create a 2-by-2 symbolic matrix with automatically generated symbolic functions as its elements.
Assign symbolic expressions to the symbolic functions f1_1(x,y) and f2_2(x,y) . These functions are displayed as f 1 , 1 ( x , y ) and f 2 , 2 ( x , y ) in the Live Editor. When you assign these expressions, the symbolic matrix f still contains the initial symbolic functions in its elements.
Substitute the expressions assigned to f1_1(x,y) and f2_2(x,y) by using the subs function.
Evaluate the value of the symbolic matrix A , which contains the substituted expressions at x = 2 and y = 3 .
Create Symbolic Objects from Returned Symbolic Array
Certain functions, such as solve and symReadSSCVariables , can return a vector of symbolic variables or a cell array of symbolic variables and functions. These variables or functions do not automatically appear in the MATLAB workspace. Create these variables or functions from the vector or cell array by using syms .
Solve the equation sin(x) == 1 by using solve . The parameter k in the solution does not appear in the MATLAB workspace.
Create the parameter k by using syms . The parameter k now appears in the MATLAB workspace.
Similarly, use syms to create the symbolic objects contained in a vector or cell array. Examples of functions that return a cell array of symbolic objects are symReadSSCVariables and symReadSSCParameters .
List All Symbolic Variables, Functions, and Arrays
Create some symbolic variables, functions, and arrays.
Display a list of all symbolic objects that currently exist in the MATLAB workspace by using syms .
Instead of displaying a list, return a cell array of all symbolic objects by prov >syms .
Delete All Symbolic Variables, Functions, or Arrays
Create several symbolic objects.
Return all symbolic objects as a cell array by using the syms function. Use the cellfun function to delete all symbolic objects in the cell array symObj .
Check that you deleted all symbolic objects by calling syms . The output is empty, meaning no symbolic objects exist in the MATLAB workspace.
Input Arguments
var1 . varN — Symbolic variables, matrices, or arrays
valid variable names separated by spaces
Example: x y123 z_1
[n1 . nM] — Vector, matrix, or array dimensions
vector of integers
Vector, matrix, or array dimensions, specified as a vector of integers. As a shortcut, you can create a square matrix by specifying only one integer. For example, syms x 3 creates a square 3 -by- 3 matrix.
Example: [2 3] , [2,3] , [2;3]
set — Assumptions on symbolic variables
real | positive | integer | rational
Assumptions on a symbolic variable or matrix, specified as real , positive , integer , or rational .
You can combine multiple assumptions using spaces. For example, syms x positive rational creates a variable x with a positive rational value.
Example: rational
f(var1. varN) — Symbolic function with its input arguments
expression with parentheses
Example: s(t) , f(x,y)
symArray — Symbolic variables and functions
vector of symbolic variables | cell array of symbolic variables and functions
Symbolic variables or functions, specified as a vector of symbolic variables or a cell array of symbolic variables and functions. Such a vector or array is typically the output of another function, such as solve or symReadSSCVariables .
Output Arguments
S — Names of all symbolic variables, functions, and arrays
cell array of character vectors
Names of all symbolic variables, functions, and arrays in the MATLAB workspace, returned as a cell array of character vectors.
syms is a shortcut for sym . This shortcut lets you create several symbolic variables in one function call. Alternatively, you can use sym and create each variable separately. However, when you create variables using sym , any existing assumptions on the created variables are retained. You can also use symfun to create symbolic functions.
The following variable names are inval >syms : integer , real , rational , positive , and clear . To create variables with these names, use sym . For example, real = sym(‘real’) .
clear x does not clear the symbolic object of its assumptions, such as real, positive, or any assumptions set by assume , sym , or syms . To remove assumptions, use one of these options:
syms x clears all assumptions from x .
assume(x,’clear’) clears all assumptions from x .
clear all clears all objects in the MATLAB workspace and resets the symbolic engine.
assume and assumeAlso provide more flexibility for setting assumptions on variables.
When you replace one or more elements of a numeric vector or matrix with a symbolic number, MATLAB converts that number to a double-precision number.
You cannot replace elements of a numeric vector or matrix with a symbolic variable, expression, or function because these elements cannot be converted to double-precision numbers. For example, syms a; A(1,1) = a throws an error.
Compatibility Cons >
syms clears assumptions
Behavior changed in R2018b
syms now clears any assumptions on the variables that it creates. For example,