Как из sym перевести в число матлаб
Перейти к содержимому

Как из sym перевести в число матлаб

  • автор:

Convert output from symbolic math (sym) to double

and contains mostly values like 5098902830068945997216661558291421977734221147306628926962736786585701268374390522728433444885024747513/17917957937422433684459538244547554224973163977877196279199912807710334969441287563047019946172856926208

I now want to convert all integer values to double values while keeping the symbol x. A simple double fails because M contains a symbol. How could I convert the whole matrix to a matlab like matrix with doubles?

Тема 3.3. Символьные (аналитические) вычисления и алгебраические преобразования

Система является MatLabсамой крупной системой компьютерной математики, ориентированной на матричные и численные вычисления. ОднакоMatLabимеет также и средства аналитических вычислений. ПакетSymbolic Math Toolboxдобавил системеMatLabкачественно новые возможности, связанные с выполнением символьных вычислений и преобразований, которые были доступны только в системе принципиально иного класса, относящихся к компьютерной алгебре.Теперь MatLab, с учетом новых средств, становится в полной мере универсальной системой. Последняя реализация системы символьной математики Maple в своем ядре и в расширениях имеет около 3000 функций. Система MatLab с пакетом Symbolic, включающим в себя чуть больше сот­ни символьных команд и функций, намного уступает Maple по ко­личеству таких команд и функций. Однако в данный пакет включе­ны лишь наиболее важные и широко распространенные функции. Кроме того, есть специальная команда, которая дает доступ к ядру Maple, что заметно расширяет круг используемых функций.

С помощью команды help symbolicможно получить перечень входящих в пакет команд и функций. Для получения справки по любой команде или функции можно использовать ко­мандуhelp sym / name.m, гдеname– это имя соответствующей команды или функции, аname.m— имяm-файла, задающего данную команду или функцию. ПакетSymbolic Math Toolbox включает следующие типы математических вычислений, которые приведены в таблице 3.3.1.

Дифференцирование, интегрирование, пределы, суммы и произведения, разложение в ряд Тейлора

С демонстрационными примерами пакета Symbolic можно ознакомиться с помощью директории Symbolic Toolbox.

3.3.2. Создание и работа с символьными переменными, выражениями и функциями

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

. Undefined function or variable ‘x’.

Мы видим, что система MatLaв «возмутилась» нашей не­брежностью и сообщила, что функция или переменная х не опред­елена и ни о каких вычислениях синуса и косинуса речи быть не может. Вместе с тем она подсказала, как надо поступить — заключить имя переменной в апострофы, ибо таким образом система получает информацию о необходимости включить символь­ный режим вычислений. Поэтому во второй раз получен вполне осмысленный результат — сумма квадратов синуса и косинуса пе­ременной ‘х’ выдана равной 1.

Таким образом для работы с командами ядра MаpleвMatLabнеобходимо создать новыйсимвольного объекта, который фактически является строковой переменной. То есть для проведения аналитических (символьных) операций нужно, чтобы соответствующие переменные были предварительно объявлены с помощью функции sym():

имя_переменной = sym(имя_переменной)

Рассмотрим пример иллюстрирующий различие между стандартными типами данных MatLab символьных объектов.

Пакет Symbolic может работать с числами различных форматов, применяемых в MatLab.Рассмотрим следующий пример:

Необходимо обратить внимание на то, что MatLabпроизводить вычисления с представлением чисел в формате с плавающей точкой с двойной точности (double ), в то время как пакетSymbolicстремиться представить числа в наиболее точном виде, то есть в целом или рациональном виде.

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

Для создания группы символьных объектов служит команда syms:

syms argl arg2 .

Например, набор команд

соответствует следующей команде

Рассмотрим еще один пример на применение команды syms.

Для работы с действительными и комплексными числами существует ряд возможностей. Прежде всего это применение опций real, unreal, imag. Например,

Функции real(z) и imag(z) обеспечивают выделение действительной и мнимой частей комплексного числа z.

Снятие наложенных ограничений на возможные значения переменных, например, определенной выше действительной переменной х, осуществляется командой

что делает переменную х не вещественной.

Из вышеприведенных примеров видно, что создание символьного выражения осуществляется командой

sym(‘символьное_выражение ‘)

Символьные выражения стоятся на основе переменных, констант, арифметических операторов и функций – как встроенных, так и определяемых пользователем. В выражениях могут использоваться арифметические операции. В общем случае это векторные и матричные операции. Например,

В математических выражениях могут использоваться как обычные, так и символьные переменные. Функция findsym(S) позволяет выделить символьные переменные в составе выражения S. Она возвращает в алфавитном порядке список всех символьных переменных выражения S. При отсутствии таковых возвращается пустая строка. Например:

>> findsym (a*x^2 + b*y + z)

>>findsym(a + b + x + y + z,)

Символьные переменные могут являться элементами матриц и векторов, причем с ними можно выполнять различные операции. Например,

MatLab в отличие от современных систем MathCad, Maple или Mathematica, пока не способна выводить выражения и результаты их преобразований в естественной математической форме с использованием общеприня­тых спецзнаков для отображения интегралов, сумм, произведений и т. д. Тем не менее некоторые ограниченные текстовым форматом воз­можности близкого к математическому виду вывода обеспечивает функция pretty(S) . Она позволяет вывести выражения S в формате, приближенном к математическому, например,

(sin(x) + a) (cos(x) + b)

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

Для вычисления символьного выражения с заданной точностью предназначена функция vpa():

Как из sym перевести в число матлаб

By Priya PedamkarPriya Pedamkar

Matlab sym()

Introduction to Matlab sym()

When any symbolic variable is created being associated with an assumption, the symbolic variable and its assumption get stored separately by MATLAB. The sym() in MATLAB is used to create numbered symbolic variables or symbolic variables in different MATLAB functions. Symbolic numbers generated from the sym() function are the exact representations of the input numbers.

Sym() can also be used to refer to an existing symbolic variable and current assumption associated with the variable. If the expected symbolic variable is not used in any MATLAB function previously, then sym() creates the variable without associating any assumptions.

Hadoop, Data Science, Statistics & others

Syntax of Matlab sym()

Syntax of matlab sym() is given: below:

When the syntax MAT = sym(‘mat’,[n1 … nM]) is used, only the symbolic array MAT gets assigned to the MATLAB workspace by the sim() function. In order to assign also the automatically generated elements of MAT, the syms function needs to be used instead of sym().

  • creates the row vector: mat = [mat1 mat2 mat3] and
  • the symbolic variables in the MATLAB workspace: a1, a2, and a3.

Note:

In the case of multidimensional arrays, sym() function generates automatically generated elements, having the prefix followed by the index for the element being added with ‘ _’ as a delimiter.

Example: a1_3_2.

Adding the command ‘clear x’ actually does not clear the symbolic object with respect to assumptions associated with the variable, such as real, positive, or any assumptions, etc. Hence, to remove assumptions, one of the below options is recommended:

  • assume(x,’clear’): all assumptions that affect x, are being removed.
  • clear all: clears all MATLAB workspace objects resetting the symbolic engine.
  • assume and assumeAlso: Add further flexibility for applying assumptions on the variable.

Expressions such aspi = sym(pi),theta = sym(‘1/10’) etc. create symbolic numbers which enable the program to avoid floating-point approximations. The variable is created as a workspace variable to hold the symbolic value given within the sym() function. It temporarily replaces the name for built-in numeric function having the same name.

Matlab sym()

By Priya PedamkarPriya Pedamkar

Matlab sym()

Introduction to Matlab sym()

When any symbolic variable is created being associated with an assumption, the symbolic variable and its assumption get stored separately by MATLAB. The sym() in MATLAB is used to create numbered symbolic variables or symbolic variables in different MATLAB functions. Symbolic numbers generated from the sym() function are the exact representations of the input numbers.

Python TutorialMachine LearningAWSArtificial Intelligence

TableauR ProgrammingPowerBIDeep Learning

Sym() can also be used to refer to an existing symbolic variable and current assumption associated with the variable. If the expected symbolic variable is not used in any MATLAB function previously, then sym() creates the variable without associating any assumptions.

Hadoop, Data Science, Statistics & others

Syntax of Matlab sym()

Syntax of matlab sym() is given: below:

When the syntax MAT = sym(‘mat’,[n1 … nM]) is used, only the symbolic array MAT gets assigned to the MATLAB workspace by the sim() function. In order to assign also the automatically generated elements of MAT, the syms function needs to be used instead of sym().

  • creates the row vector: mat = [mat1 mat2 mat3] and
  • the symbolic variables in the MATLAB workspace: a1, a2, and a3.

Note:

In the case of multidimensional arrays, sym() function generates automatically generated elements, having the prefix followed by the index for the element being added with ‘ _’ as a delimiter.

Example: a1_3_2.

Adding the command ‘clear x’ actually does not clear the symbolic object with respect to assumptions associated with the variable, such as real, positive, or any assumptions, etc. Hence, to remove assumptions, one of the below options is recommended:

  • assume(x,’clear’): all assumptions that affect x, are being removed.
  • clear all: clears all MATLAB workspace objects resetting the symbolic engine.
  • assume and assumeAlso: Add further flexibility for applying assumptions on the variable.

Expressions such aspi = sym(pi),theta = sym(‘1/10’) etc. create symbolic numbers which enable the program to avoid floating-point approximations. The variable is created as a workspace variable to hold the symbolic value given within the sym() function. It temporarily replaces the name for built-in numeric function having the same name.

Examples of Matlab sym()

Following are the examples of matlab sym() are given below:

Example #1

Output:

Matlab sym()-1.1

Example #2

Output:

Matlab sym()-1.2

Example #3

Output:

Matlab sym()-1.3

Example #4 – Create Symbolic Multidimensional Arrays

MATLAB enables its program to create multidimensional array containing symbolic elements at one time, using sym() function.

MAT = sym(‘mat’,[2 2 2])

Output:

Matlab sym()-1.4

Example #5 – Converting Expressions to Symbolic Expressions

Application of sym() function on the complete expressions makes the conversion inaccurate as MATLAB converts the expression to a floating-point number, which results in reducing accuracy and recovery of the lost accuracy is not possible by sym() all the time. Hence in order to extract symbolic expressions with respect to expressions, sym() needs to be applied on subexpressions instead of the entire expression to achieve better accuracy.

var_inaccurate1 = sym(1/1234567)
var_accurate1 = 1/sym(1234567)
var_inaccurate2 = sym(sqrt(1234567))

Output:

Matlab sym()-1.5

Example #6 – Generating Large Symbolic Numbers

In case of generating symbolic number having 15 or more digits, quotation marks are used to represent the numbers with optimum accuracy.

var_inaccurateNum = sym(11111111111111111111)
var_accurateNum = sym(‘11111111111111111111’)
sym(‘12335567 + 5i’)

Output:

Output-1.6

Note: Sym() treats the imaginary symbol ‘i’ as an identifier in a character vector input. Hence in order to provide imaginary number I as an input, it is suggested to use 1i instead.

Example #7 – Generating Symbolic Expressions out of Function Handles

MATLAB supports creating any symbolic expression or a symbolic matrix from anonymous functions that are associated with MATLAB handles.

mat_expr = @(x)(sin(x) + cos(x));
mat_sym_expr = sym(mat_expr)
mat_matrix = @(x)(x*pascal(3));
mat_sym_matrix = sym(mat_matrix)

Output:

Output-1.7

Example 8 – Setting of Assumptions While Generating Symbolic Variables

MATLAB supports creating symbolic variables adding a different set of assumptions about characteristics of the variable such as the number being real or positive or rational etc.

p = sym(‘p’,’real’);
q = sym(‘q’,’positive’);
r = sym(‘r’,’rational’);
s = sym(‘s’,<'positive','integer'>);
assume([p q r s],’clear’)
assumptions

Output:

Output-1.8

Example #9 – Selecting Conversion Technique for Floating-Point Values

The functionality of the sym() function is extended to choose any conversion technique. It is achieved by specifying the second argument which is optional by nature. The value for the arguments can be ‘r’, ‘f’, ‘d’, or ‘e’. However, the default value remains ‘r’.

p = sym(pi)
q = sym(pi,’f’)
r = sym(pi,’d’)
s = sym(pi,’e’)

Output:

Output-1.9

Conclusion

When one or more elements of a numeric vector or matrix is/are replaced with a symbolic number, MATLAB treats the number as a double-precision number, but those elements of a numeric vector or matrix do not support replacement with a symbolic variable, function or expression as these elements cannot be converted to double-precision numbers. The functions Sym() and syms() share similar functionality but differs as:

The syms() function creates a symbolic object, automatically assigning to a MATLAB variable having the same name, whereas, a symbolic object referred by sym() function can be assigned to a MATLAB variable with the same name and to a different name as well.

Recommended Articles

This is a guide to Matlab sym(). Here we also discuss the introduction and syntax of matlab sym() along with different examples and its code implementation. you may also have a look at the following articles to learn more –

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *