Sims requires symbolic math toolbox ошибка

Hi everyone

when i run the program at version 2021 a, it shows me this message

‘syms’ requires Symbolic Math Toolbox.

Error in M17_khodir (line 4)

syms x

however it works with my friend version (2018)

any Help

Thanks

Русские Блоги

Как добавить Toolbox в Matlab (подробное объяснение со скриншотами) (R2019b)

Каталог статей

1. Подготовьте набор инструментов.

Давайте рассмотрим добавление набора инструментов fecgsyn-master в качестве примера, чтобы объяснить метод добавления набора инструментов в Matlab.

Сайт загрузки наборов инструментов Matlab: http://fernandoandreotti.github.io/fecgsyn/

2. Разархивируйте и скопируйте в папку

Разархивируйте загруженный файл и скопируйте папку в каталог Toolbox Matlab, например: D: Program Files MATLAB R2019b toolbox.

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

3. Задайте путь

Откройте Matlab, нажмите «Файл-> Установить путь-> Добавить папку» (в китайской версии путь настройки указан прямо на панели, или вы можете найти его в справке) и добавьте папку, только что разархивированную и скопированную. Помните, что если в папке, которую вы хотите добавить, есть подпапки, вы должны нажать «Добавить с подпапками», выбрать папку только сейчас и добавить все подпапки папки.

4. Обновите кеш пути к панели инструментов.

Затем в «Файл-> Настройки-> Общие» обновите кэш пути к панели инструментов.

How to use the Symbolic Math Toolbox in MATLAB to analyze the Fourier series

Symbolic Math Toolbox provides an easy, intuitive and complete environment to interactively learn and apply math operations such as calculus, algebra, and differential equations.

It can perform common analytical computations such as differentiation and integration to get close form results.

It simplifies and manipulates expression for great insights and solves algebraic and differential equations.

In this tutorial, the Fourier series (Trigonometric and Exponential) is implemented and simulated using MATLAB’s Symbolic Math Toolbox.

The proposed programs are versatile and can receive any function of time(t). It means that the function is dependent on time.

Moreover, the program gives plots of harmonics, original and approximated functions, magnitude spectrum, and phase spectrum.

This toolbox is already available in MATLAB. Therefore, you do not need to retrieve it from an external source. For example, to understand more about the Fourier series, you can read here.

Prerequisites

To follow along with this tutorial, you will need:

    installed.

  1. A proper understanding of MATLAB basics.

Symbolic Math Toolbox

This toolbox has a wide range of applications:

To visualize analytical expressions in 2D and 3D and animate plots to create videos.

Symbolic Math Toolbox in the live editor (mode in MATLAB) lets you interactively update and display Symbolic math computations.

Besides, MATLAB code, formatted text, equations, and images can be published as executable live scripts, PDFs, or HTML documents.

While working with analytical problems, you can receive suggestions and tips. These suggestions help one insert and execute function calls or tasks directly into live scripts.

The Symbolic Math Toolbox also provides precision for higher or lower positions. It allows algorithms to run better than MATLAB’s in-built double. Furthermore, it has units for working with physical quantities and performing dimensional analysis.

Units for working with physical quantities

This is an example of how this toolbox adds units for physical quantities

Symbolic Math Toolbox is widely applied in many engineering and scientific applications. Symbolic expressions of exact gradient and Hessians improve accuracy and optimization speed.

In non-linear control design, the Symbolic Math Toolbox improves recalculation speed at any operating point during execution. Furthermore, you can integrate symbolic results with MATLAB and Simulink applications. It is done by converting symbolic expressions into numeric MATLAB functions, Simulink, and Simscape blocks.

converting functions to Simulink

Sample of function converted to Simulink

Now, all these applications discussed above were to give you an insight into the wide application of this toolbox. However, not all of them are discussed here. Here, we will only major in using the toolbox to solve Fourier series problems.

How to use the Symbolic Math Toolbox

This toolbox is enabled in MATLAB using the function syms . However, you get an error message if you have the expression x=2*a+b and try to execute it in Matlab. The error message is undefined function or variable ‘a’ as shown below:

When using the syms function, the variable x is saved without the error message. When using the Symbolic Math Toolbox, the idea here is that you first define the symbolic variables. Symbolic variables are the undefined variables in an equation. For example, our symbols are a and b for our expression above. We first define these variables using the symbolic function syms .

After defining the symbols and rerunning the code above, our workspace stored our variables. We will then have:

Solving Fourier series using the Symbolic Math Toolbox

Let’s say we have a Fourier transform shown below:

The symbolic variables are t , w , T , and W , which we define by executing the command below:

w is the angle theta, T is the time function, and W is used to express the angular radians in the Fourier transform.

After the declaration of the symbolic variables, you can write the Fourier transform as shown below:

In MATLAB, int means integration. In the MATLAB expression above: exp(-t/2) is our equation which we are finding its Fourier transform. exp(-j*w*t) is the basic function of the Fourier transform. t shows that we are differentiating with respect to time. [0, inf] shows the integration limits from 0 to infinity .

Note that we don’t write f(t) when writing our equation in MATLAB. It is because we already know that our function is a time function. Also, t is a symbol variable, so we do not write it in our expression.

When the above program is executed, we get the output below:

To format this output in a user-friendly manner, we use the function pretty() . pretty(f) prints the symbolic expression f in a format that resembles type-set mathematical equations. When you execute this function in the command window, we have:

Now, we need to get the values of w since we use them to plot the Fourier transform. To do that, execute the code below:

subs mean symbolic substitution. This function replaces the symbolic variable in f with the values of w . The values range from -pi to pi . When we do this, we get the values below:

We now plot these values using the plot() function.

plot(angle(double(data_value))) gives the phase spectrum plot. The function subplot() is used to create a subplot. title() gives the plot a title.

phase spectrum

Phase spectrum plot

Now, let us plot the magnitude response using the same values of w .

The code plot(abs(double(data_values))) gives the magnitude spectrum. This plot uses the absolute values of the data, thus abs() .

magnitude spectrum

Magnitude spectrum plot

Example 2

Let’s look at another example:

example 2

The output here is:

To find the values of w , we use the subs() function.

After that, we plot the absolute values of the variable f-sub .

Range of -pi to pi

Plot for the range -pi to pi

Range of -2pi to 2pi

Plot for the range -2pi to 2pi

Range of -4pi to 4pi

Plot for the range -4pi to 4pi

Range of -8pi to 8pi

Plot for the range -8pi to 8pi

While making the plots, we used the ezplot function. ezplot(FUN) is used to plot a function x over the default domain, -2*pi<x<2*pi . As we have seen, the Symbolic Math Toolbox makes it easy to analyze the Fourier series. Moreover, it makes it easy since you do not have to write long codes.

Conclusion

Symbolic Math Toolbox is an important toolbox for solving differential and integration operations. As we have seen in solving the Fourier series above, it is easy to use. This toolbox also helps find the Laplace transform of various equations. Generally, this toolbox has a wide application in science and engineering.

Цель работы:изучить систему команд расширения MATLAB (Toolbox) для работы с символьными переменными Symbolic Math.

Теоретические данные:

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

Основные команды, используемые для работы с символьными переменными:

1. Общие операции:

syms – создает символьные переменные упрощенным способом. Формат команды: syms vol1 vol2 …, где vol1, vol2 и т.д. – имена создаваемых символьных переменных. Для создания символьных переменных может также применяться команда sym, которая применяется в следующем формате: vol1 = sym(‘vol1’). Таким образом, в скобках, заключенное в апострофы, задается имя создаваемой переменной. Такая запись является чересчур громоздкой, поэтому рекомендуется применять упрощенную команду syms, при этом, создаваемые переменные просто перечисляются через пробел после самой команды. Ставить знак «;» после команды syms не требуется;

pretty – выдает символьное выражение в многоуровневом представлении (в привычном нам виде). Формат записи команды: pretty(vol), где vol – имя переменной, в которой хранится символьное выражение. Например, символьное выражение:
A = (2*x+y*x*2+y^2)/(2*a+3*b) в линейной форме записи, будет преобразовано командой pretty в:

2. Решение уравнений:

solve – решение алгебраических уравнений, в том числе их систем. Формат записи:

solve (‘eqn1′,’eqn2’. ‘eqnN’,’var1,var2. varN’), где eqn1, eqn2 и т.д. – уравнения, решения которых нужно найти.

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

dsolve – решение дифференциальных уравнений. Формат записи:

simplify – упрощение выражения;

expand – раскрывает все скобки в выражении;

collect – выносит общий множитель за скобки;

subs – подстановка числовых значений вместо символьных.

Формат записи для всех команд одинаков:

vol2 = command(vol1), где vol1 – преобразуемая переменная, vol2 – переменная, в которую будет записан результат преобразования, command – одна из указанных выше команд.

diff – дифференцирование выражения. Формат записи:
diff(vol1, n), где n – порядок дифференцирования;

int – интегрирование выражения. Формат записи: int(vol1,a,b), где a и b – верхний и нижний пределы интегрирования, в случае нахождения определенного интеграла;

limit – нахождение предела выражения. Формат записи:
limit(vol1,x,a,’ident’), где x – имя переменной которая стремится к пределу, a – численное значение, к которому стремится переменная x, ident – может принимать значения left и right, т.е. это указание, в какую сторону стремится величина x – направление для односторонних пределов.

Практическое применение:

Пример №1: Необходимо задать выражение A = (x*2+y^3-3*z)*3*x+4*y^3, упростить его и определить значение A в точке (1,2,1).

Выполняется следующим образом:

% после выполнения этой команды в рабочей области (workspace появятся три символьные переменные x, y и z

% результат выполнения команды:

% показывает как выражение было занесено в переменную А. В отдельных случаях, когда возможно упростить вводимое выражение, оно будет упрощено и выдано на экран уже в упрощенном виде. Как видно из результата применения команды, все составляющие в скобке были помножены на 3.

% для дополнительного контроля можно применить команду

% результат ее применения:

% (6 x + 3 y — 9 z) x + 4 y

% раскрываем скобки, запоминаем результат в переменной А1

% результат: A1 = 6*x^2+3*x*y^3-9*x*z+4*y^3

% группируем переменные в выражении А1 и выносим общие множители за скобки. Результат: A2 = 6*x^2+(3*y^3-9*z)*x+4*y^3

% задаем значения переменных x, y и z соответственно заданной точке (1,2,1). при этом в рабочей области появятся уже числовые переменные с соответствующими значениями.

% подставляем численные значения в наше выражение, получаем результат:

% Возможно присваивание численных значений только части символьных переменных выражения. Для иллюстрации этого вернем переменные x, y и z в символьный вид:

% результат в этом случае: A3 = 62-9*z

Пример №2: Необходимо решить независимые уравнения
x+20=10, 3*x^2+2*x-10=0 и 4*x+5*x^3=-12.

Выполняется следующим образом:

1 уравнение:

2 уравнение:

% MATLAB выдал два корня уравнения в неупрощенном виде, для их упрощения необходимо повторить ответ в командном окне (скопировать его и заново ввести в командное окно)

3 уравнение:

Пример №3: Необходимо решить независимые уравнения
x+y=35, 3*x^2+2*y=0 и 4*x+5*y^3=-12 относительно переменной x.

Выполняется следующим образом:

1 уравнение:

2 уравнение:

3 уравнение:

Пример №4: Необходимо найти неопределенный интеграл и дифференциал выражения 3*a^5*sin(a).

Выполняется следующим образом:

Пример №5: Необходимо найти определенный интеграл выражения 3*a^5*sin(a), для пределов от -10 до 100.

Выполняется следующим образом:

Пример №6: Необходимо продифференцировать выражение 3*a^5*sin(a) четыре раза.

Выполняется следующим образом:

Пример №7: Необходимо получить передаточную функцию трех последовательно соединенных звеньев: , и . А также определить передаточную функцию замкнутой системы, состоящей из звеньев W1, W2 и W3 – в прямой ветви, и звена – в обратной связи, при условии отрицательной обратной связи.

0 / 0 / 0

Регистрация: 16.12.2013

Сообщений: 48

1

11.05.2015, 19:01. Показов 14632. Ответов 11


Студворк — интернет-сервис помощи студентам

В 2008b матлабе при использовании syms пишет: ??? Undefined function or variable ‘syms’.
Что можно сделать? может быть подгрузить какие-то модули?



0



Northfolk

0 / 0 / 0

Регистрация: 11.05.2015

Сообщений: 3

11.05.2015, 19:08

2

Пробовали записать так?

Matlab M
1
x = sym('x');



0



0 / 0 / 0

Регистрация: 16.12.2013

Сообщений: 48

11.05.2015, 19:10

 [ТС]

3

Все равно ругается



0



Northfolk

0 / 0 / 0

Регистрация: 11.05.2015

Сообщений: 3

11.05.2015, 19:20

4

К сожалению, я новичок в работе с Matlab’ом и многим не помогу, но попробуйте прописать

Matlab M
1
ver

И посмотреть установлен ли у вас Symbolic Math Toolbox.



0



0 / 0 / 0

Регистрация: 16.12.2013

Сообщений: 48

11.05.2015, 21:59

 [ТС]

5

Не установлено, к сожалению. Вы не знаете, откуда можно это скачать? В гугле пока не нашел



0



Krasme

6647 / 4746 / 1980

Регистрация: 02.02.2014

Сообщений: 12,715

11.05.2015, 22:22

6

ничего не подключала специально…
такое работает

Matlab M
1
2
3
syms a b
f=(a+b)/(a*b);
disp(f);

Добавлено через 26 секунд
plif, вы бы свой текст показали..



0



0 / 0 / 0

Регистрация: 16.12.2013

Сообщений: 48

11.05.2015, 22:27

 [ТС]

7

syms a b не работает, как только появляется это слово, начинает ругаться.
А откуда вы скачивали матлаб?, может у меня неполная версия



0



6647 / 4746 / 1980

Регистрация: 02.02.2014

Сообщений: 12,715

11.05.2015, 22:32

8

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



0



0 / 0 / 0

Регистрация: 16.12.2013

Сообщений: 48

11.05.2015, 22:34

 [ТС]

9

а я файл не создавал… Просто пишу команды в Command Window



0



6647 / 4746 / 1980

Регистрация: 02.02.2014

Сообщений: 12,715

11.05.2015, 22:42

10

Лучший ответ Сообщение было отмечено plif как решение

Решение

тут обсуждается ваша проблема…



1



0 / 0 / 0

Регистрация: 16.12.2013

Сообщений: 48

12.05.2015, 00:35

 [ТС]

11

спасибо получилось!, когда я переустановил 32-битный, заработало!
Еще поставил 2013b матлаб, там тоже все работает



0



Krasme

12.05.2015, 06:23


    Syms не работает — Undefined function or variable ‘syms’

Не по теме:

теперь, как заяц, между двумя версиями прыг-скок? :D



0



OPEX

Пользователь
Сообщения: 150
Зарегистрирован: Вт сен 20, 2011 3:08 pm

не работает встроенная функция!!!

доброго времени суток. возникла проблема. есть встроенное слово syms, но у меня оно не работает. выдает такую ошибку:

??? Undefined function or variable ‘syms’.

пробовал переустановить MATLAB, но это не помогло.

помогите исправить.


Grizzly

Пользователь
Сообщения: 843
Зарегистрирован: Сб май 28, 2011 2:00 am

Сообщение Grizzly » Сб окт 08, 2011 6:47 pm

Symbolic Math Toolbox установлен?


OPEX

Пользователь
Сообщения: 150
Зарегистрирован: Вт сен 20, 2011 3:08 pm

Сообщение OPEX » Сб окт 08, 2011 6:51 pm

да, установлен. система Win 7 x64. может в этом проблема?


Grizzly

Пользователь
Сообщения: 843
Зарегистрирован: Сб май 28, 2011 2:00 am

Сообщение Grizzly » Сб окт 08, 2011 6:53 pm

У меня тоже Windows 7 x64, syms работает.


Grizzly

Пользователь
Сообщения: 843
Зарегистрирован: Сб май 28, 2011 2:00 am

Сообщение Grizzly » Сб окт 08, 2011 6:57 pm

Остальные-то функции Symbolic Math Toolbox работают?


OPEX

Пользователь
Сообщения: 150
Зарегистрирован: Вт сен 20, 2011 3:08 pm

Сообщение OPEX » Сб окт 08, 2011 6:57 pm

а Symbolic Math Toolbox Вы отдельно устанавливали? просто с одного и того же установочника устанавливали на два компьютера с х32 и х64, где х32 работает, а у меня нет! может Symbolic Math Toolbox отдельно надо установить?


OPEX

Пользователь
Сообщения: 150
Зарегистрирован: Вт сен 20, 2011 3:08 pm

Сообщение OPEX » Сб окт 08, 2011 6:58 pm

другие не пробовал!


Grizzly

Пользователь
Сообщения: 843
Зарегистрирован: Сб май 28, 2011 2:00 am

Сообщение Grizzly » Сб окт 08, 2011 6:58 pm

Наберите в командной строке

Вы увидете все установленные тулбоксы.


Grizzly

Пользователь
Сообщения: 843
Зарегистрирован: Сб май 28, 2011 2:00 am

Сообщение Grizzly » Сб окт 08, 2011 7:01 pm

Я устанавливал сразу все тулбоксы. Вероятно, вы установили выборочно некоторые из них. Попробуйте с этого же установочника поставить Symbolic Math Toolbox.


OPEX

Пользователь
Сообщения: 150
Зарегистрирован: Вт сен 20, 2011 3:08 pm

Сообщение OPEX » Сб окт 08, 2011 7:17 pm

решил проблему путем установки MATLABA для х32 системы. вроде сейчас все работает. попробовал «ver» как Вы сказали Symbolic Math Toolbox присутствует. большое спасибо за помощь.


Luqman Alabri

  • Direct link to this question

 ⋮ 

  • Direct link to this question

syms M m L q d_q dd_q x d_x dd_x g b J F

eq1= (M+m)*dd_x + m*L*(dd_q*cos(q)-d_q^2*sin(q))+b*d_x-F;

eq2= (J+mL)*dd_q+m*L*dd_x*cos(q)+m*L*g*cos(q);

solu=solve(eq1,eq2,dd_x,dd_q)

Accepted Answer

Stephan

  • Direct link to this answer

 ⋮ 

  • Direct link to this answer

Edited: Stephan

on 9 Dec 2022

«why do I receive syms requires Symbolic math tool box?» — Simple: Because syms is part of the symbolic toolbox. If your license doesn’t cover that toolbox you are not able to use it’s features.

In eq2 i replaced (J+mL) through (J+m*L):

syms M m L q d_q dd_q x d_x dd_x g b J F

eq1= (M+m)*dd_x + m*L*(dd_q*cos(q)-d_q^2*sin(q))+b*d_x-F;

eq2= (J+m*L)*dd_q+m*L*dd_x*cos(q)+m*L*g*cos(q);

solu=solve(eq1,eq2,dd_x,dd_q)

solu = struct with fields:

dd_x: (F*J + F*L*m — J*b*d_x + L^2*g*m^2*cos(q)^2 + L^2*d_q^2*m^2*sin(q) — L*b*d_x*m + J*L*d_q^2*m*sin(q))/(- L^2*m^2*cos(q)^2 + L*m^2 + M*L*m + J*m + J*M)
dd_q: -(L*m*cos(q)*(L*m*sin(q)*d_q^2 + F + M*g — b*d_x + g*m))/(- L^2*m^2*cos(q)^2 + L*m^2 + M*L*m + J*m + J*M)

solu.dd_x

ans = 

solu.dd_q

ans = 


More Answers (0)

See Also

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.

MathWorks - Domain Selector

Русские Блоги

Как добавить Toolbox в Matlab (подробное объяснение со скриншотами) (R2019b)

Каталог статей

1. Подготовьте набор инструментов.

Давайте рассмотрим добавление набора инструментов fecgsyn-master в качестве примера, чтобы объяснить метод добавления набора инструментов в Matlab.

Сайт загрузки наборов инструментов Matlab: http://fernandoandreotti.github.io/fecgsyn/

2. Разархивируйте и скопируйте в папку

Разархивируйте загруженный файл и скопируйте папку в каталог Toolbox Matlab, например: D: Program Files MATLAB R2019b toolbox.

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

3. Задайте путь

Откройте Matlab, нажмите «Файл-> Установить путь-> Добавить папку» (в китайской версии путь настройки указан прямо на панели, или вы можете найти его в справке) и добавьте папку, только что разархивированную и скопированную. Помните, что если в папке, которую вы хотите добавить, есть подпапки, вы должны нажать «Добавить с подпапками», выбрать папку только сейчас и добавить все подпапки папки.

4. Обновите кеш пути к панели инструментов.

Затем в «Файл-> Настройки-> Общие» обновите кэш пути к панели инструментов.

How to use the Symbolic Math Toolbox in MATLAB to analyze the Fourier series

Symbolic Math Toolbox provides an easy, intuitive and complete environment to interactively learn and apply math operations such as calculus, algebra, and differential equations.

It can perform common analytical computations such as differentiation and integration to get close form results.

It simplifies and manipulates expression for great insights and solves algebraic and differential equations.

In this tutorial, the Fourier series (Trigonometric and Exponential) is implemented and simulated using MATLAB’s Symbolic Math Toolbox.

The proposed programs are versatile and can receive any function of time(t). It means that the function is dependent on time.

Moreover, the program gives plots of harmonics, original and approximated functions, magnitude spectrum, and phase spectrum.

This toolbox is already available in MATLAB. Therefore, you do not need to retrieve it from an external source. For example, to understand more about the Fourier series, you can read here.

Prerequisites

To follow along with this tutorial, you will need:

    installed.

  1. A proper understanding of MATLAB basics.

Symbolic Math Toolbox

This toolbox has a wide range of applications:

To visualize analytical expressions in 2D and 3D and animate plots to create videos.

Symbolic Math Toolbox in the live editor (mode in MATLAB) lets you interactively update and display Symbolic math computations.

Besides, MATLAB code, formatted text, equations, and images can be published as executable live scripts, PDFs, or HTML documents.

While working with analytical problems, you can receive suggestions and tips. These suggestions help one insert and execute function calls or tasks directly into live scripts.

The Symbolic Math Toolbox also provides precision for higher or lower positions. It allows algorithms to run better than MATLAB’s in-built double. Furthermore, it has units for working with physical quantities and performing dimensional analysis.

Units for working with physical quantities

This is an example of how this toolbox adds units for physical quantities

Symbolic Math Toolbox is widely applied in many engineering and scientific applications. Symbolic expressions of exact gradient and Hessians improve accuracy and optimization speed.

In non-linear control design, the Symbolic Math Toolbox improves recalculation speed at any operating point during execution. Furthermore, you can integrate symbolic results with MATLAB and Simulink applications. It is done by converting symbolic expressions into numeric MATLAB functions, Simulink, and Simscape blocks.

converting functions to Simulink

Sample of function converted to Simulink

Now, all these applications discussed above were to give you an insight into the wide application of this toolbox. However, not all of them are discussed here. Here, we will only major in using the toolbox to solve Fourier series problems.

How to use the Symbolic Math Toolbox

This toolbox is enabled in MATLAB using the function syms . However, you get an error message if you have the expression x=2*a+b and try to execute it in Matlab. The error message is undefined function or variable ‘a’ as shown below:

When using the syms function, the variable x is saved without the error message. When using the Symbolic Math Toolbox, the idea here is that you first define the symbolic variables. Symbolic variables are the undefined variables in an equation. For example, our symbols are a and b for our expression above. We first define these variables using the symbolic function syms .

After defining the symbols and rerunning the code above, our workspace stored our variables. We will then have:

Solving Fourier series using the Symbolic Math Toolbox

Let’s say we have a Fourier transform shown below:

The symbolic variables are t , w , T , and W , which we define by executing the command below:

w is the angle theta, T is the time function, and W is used to express the angular radians in the Fourier transform.

After the declaration of the symbolic variables, you can write the Fourier transform as shown below:

In MATLAB, int means integration. In the MATLAB expression above: exp(-t/2) is our equation which we are finding its Fourier transform. exp(-j*w*t) is the basic function of the Fourier transform. t shows that we are differentiating with respect to time. [0, inf] shows the integration limits from 0 to infinity .

Note that we don’t write f(t) when writing our equation in MATLAB. It is because we already know that our function is a time function. Also, t is a symbol variable, so we do not write it in our expression.

When the above program is executed, we get the output below:

To format this output in a user-friendly manner, we use the function pretty() . pretty(f) prints the symbolic expression f in a format that resembles type-set mathematical equations. When you execute this function in the command window, we have:

Now, we need to get the values of w since we use them to plot the Fourier transform. To do that, execute the code below:

subs mean symbolic substitution. This function replaces the symbolic variable in f with the values of w . The values range from -pi to pi . When we do this, we get the values below:

We now plot these values using the plot() function.

plot(angle(double(data_value))) gives the phase spectrum plot. The function subplot() is used to create a subplot. title() gives the plot a title.

phase spectrum

Phase spectrum plot

Now, let us plot the magnitude response using the same values of w .

The code plot(abs(double(data_values))) gives the magnitude spectrum. This plot uses the absolute values of the data, thus abs() .

magnitude spectrum

Magnitude spectrum plot

Example 2

Let’s look at another example:

example 2

The output here is:

To find the values of w , we use the subs() function.

After that, we plot the absolute values of the variable f-sub .

Range of -pi to pi

Plot for the range -pi to pi

Range of -2pi to 2pi

Plot for the range -2pi to 2pi

Range of -4pi to 4pi

Plot for the range -4pi to 4pi

Range of -8pi to 8pi

Plot for the range -8pi to 8pi

While making the plots, we used the ezplot function. ezplot(FUN) is used to plot a function x over the default domain, -2*pi<x<2*pi . As we have seen, the Symbolic Math Toolbox makes it easy to analyze the Fourier series. Moreover, it makes it easy since you do not have to write long codes.

Conclusion

Symbolic Math Toolbox is an important toolbox for solving differential and integration operations. As we have seen in solving the Fourier series above, it is easy to use. This toolbox also helps find the Laplace transform of various equations. Generally, this toolbox has a wide application in science and engineering.

Цель работы:изучить систему команд расширения MATLAB (Toolbox) для работы с символьными переменными Symbolic Math.

Теоретические данные:

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

Основные команды, используемые для работы с символьными переменными:

1. Общие операции:

syms – создает символьные переменные упрощенным способом. Формат команды: syms vol1 vol2 …, где vol1, vol2 и т.д. – имена создаваемых символьных переменных. Для создания символьных переменных может также применяться команда sym, которая применяется в следующем формате: vol1 = sym(‘vol1’). Таким образом, в скобках, заключенное в апострофы, задается имя создаваемой переменной. Такая запись является чересчур громоздкой, поэтому рекомендуется применять упрощенную команду syms, при этом, создаваемые переменные просто перечисляются через пробел после самой команды. Ставить знак «;» после команды syms не требуется;

pretty – выдает символьное выражение в многоуровневом представлении (в привычном нам виде). Формат записи команды: pretty(vol), где vol – имя переменной, в которой хранится символьное выражение. Например, символьное выражение:
A = (2*x+y*x*2+y^2)/(2*a+3*b) в линейной форме записи, будет преобразовано командой pretty в:

2. Решение уравнений:

solve – решение алгебраических уравнений, в том числе их систем. Формат записи:

solve (‘eqn1′,’eqn2’. ‘eqnN’,’var1,var2. varN’), где eqn1, eqn2 и т.д. – уравнения, решения которых нужно найти.

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

dsolve – решение дифференциальных уравнений. Формат записи:

simplify – упрощение выражения;

expand – раскрывает все скобки в выражении;

collect – выносит общий множитель за скобки;

subs – подстановка числовых значений вместо символьных.

Формат записи для всех команд одинаков:

vol2 = command(vol1), где vol1 – преобразуемая переменная, vol2 – переменная, в которую будет записан результат преобразования, command – одна из указанных выше команд.

diff – дифференцирование выражения. Формат записи:
diff(vol1, n), где n – порядок дифференцирования;

int – интегрирование выражения. Формат записи: int(vol1,a,b), где a и b – верхний и нижний пределы интегрирования, в случае нахождения определенного интеграла;

limit – нахождение предела выражения. Формат записи:
limit(vol1,x,a,’ident’), где x – имя переменной которая стремится к пределу, a – численное значение, к которому стремится переменная x, ident – может принимать значения left и right, т.е. это указание, в какую сторону стремится величина x – направление для односторонних пределов.

Практическое применение:

Пример №1: Необходимо задать выражение A = (x*2+y^3-3*z)*3*x+4*y^3, упростить его и определить значение A в точке (1,2,1).

Выполняется следующим образом:

% после выполнения этой команды в рабочей области (workspace появятся три символьные переменные x, y и z

% результат выполнения команды:

% показывает как выражение было занесено в переменную А. В отдельных случаях, когда возможно упростить вводимое выражение, оно будет упрощено и выдано на экран уже в упрощенном виде. Как видно из результата применения команды, все составляющие в скобке были помножены на 3.

% для дополнительного контроля можно применить команду

% результат ее применения:

% (6 x + 3 y — 9 z) x + 4 y

% раскрываем скобки, запоминаем результат в переменной А1

% результат: A1 = 6*x^2+3*x*y^3-9*x*z+4*y^3

% группируем переменные в выражении А1 и выносим общие множители за скобки. Результат: A2 = 6*x^2+(3*y^3-9*z)*x+4*y^3

% задаем значения переменных x, y и z соответственно заданной точке (1,2,1). при этом в рабочей области появятся уже числовые переменные с соответствующими значениями.

% подставляем численные значения в наше выражение, получаем результат:

% Возможно присваивание численных значений только части символьных переменных выражения. Для иллюстрации этого вернем переменные x, y и z в символьный вид:

% результат в этом случае: A3 = 62-9*z

Пример №2: Необходимо решить независимые уравнения
x+20=10, 3*x^2+2*x-10=0 и 4*x+5*x^3=-12.

Выполняется следующим образом:

1 уравнение:

2 уравнение:

% MATLAB выдал два корня уравнения в неупрощенном виде, для их упрощения необходимо повторить ответ в командном окне (скопировать его и заново ввести в командное окно)

3 уравнение:

Пример №3: Необходимо решить независимые уравнения
x+y=35, 3*x^2+2*y=0 и 4*x+5*y^3=-12 относительно переменной x.

Выполняется следующим образом:

1 уравнение:

2 уравнение:

3 уравнение:

Пример №4: Необходимо найти неопределенный интеграл и дифференциал выражения 3*a^5*sin(a).

Выполняется следующим образом:

Пример №5: Необходимо найти определенный интеграл выражения 3*a^5*sin(a), для пределов от -10 до 100.

Выполняется следующим образом:

Пример №6: Необходимо продифференцировать выражение 3*a^5*sin(a) четыре раза.

Выполняется следующим образом:

Пример №7: Необходимо получить передаточную функцию трех последовательно соединенных звеньев: , и . А также определить передаточную функцию замкнутой системы, состоящей из звеньев W1, W2 и W3 – в прямой ветви, и звена – в обратной связи, при условии отрицательной обратной связи.

John

I have the symbolic math toolbox, but ‘syms’ isn’t working. How can I fix this?

VER info below:

«—————————————————————————————————-

MATLAB Version: 9.0.0.341360 (R2016a)

MATLAB License Number: xxxxxx

Operating System: Microsoft Windows 7 Professional Version 6.1 (Build 7601: Service Pack 1)

Java Version: Java 1.7.0_60-b19 with Oracle Corporation Java HotSpot™ 64-Bit Server VM mixed mode

—————————————————————————————————-

MATLAB Version 9.0 (R2016a)

Simulink Version 8.7 (R2016a)

Computer Vision System Toolbox Version 7.1 (R2016a)

Control System Toolbox Version 10.0 (R2016a)

Curve Fitting Toolbox Version 3.5.3 (R2016a)

Data Acquisition Toolbox Version 3.9 (R2016a)

Image Processing Toolbox Version 9.4 (R2016a)

MATLAB Coder Version 3.1 (R2016a)

Optimization Toolbox Version 7.4 (R2016a)

Signal Processing Toolbox Version 7.2 (R2016a)

Simulink Coder Version 8.10 (R2016a)

Simulink Control Design Version 4.3 (R2016a)

Simulink Design Optimization Version 3.0 (R2016a)

Simulink Desktop Real-Time Version 5.2 (R2016a)

Stateflow Version 8.7 (R2016a)

Statistics and Machine Learning Toolbox Version 10.2 (R2016a)

Symbolic Math Toolbox Version 7.0 (R2016a)

System Identification Toolbox Version 9.4 (R2016a)

*************************************

license(‘test’,’symbolic_toolbox’)

ans =


回答(2 个)

Om Yadav

One line solution: MATLAB —> HOME —> Set Path —> Default —> Save.


Hootan Manoochehri

I have the exact same problem, the symbolic math toolbox is installed, but whenever I use syms or sym() to define symbol, it doesn’t terminate it consumes all of my memory and then I can’t use my pc, and I should restart it or kill MATLAB before it gets all the memory.

CPU usage increase around 30% not that much, it seems it goes to a recursive function without termination !!!

>> ver

——————————————————————————————————

MATLAB Version: 9.4.0.813654 (R2018a)

MATLAB License Number: XXXXXXXX

Operating System: Microsoft Windows 10 Education Version 10.0 (Build 17134)

Java Version: Java 1.8.0_144-b01 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode

——————————————————————————————————

MATLAB Version 9.4 (R2018a)

Simulink Version 9.1 (R2018a)

Control System Toolbox Version 10.4 (R2018a)

DSP System Toolbox Version 9.6 (R2018a)

Data Acquisition Toolbox Version 3.13 (R2018a)

Embedded Coder Version 7.0 (R2018a)

Fixed-Point Designer Version 6.1 (R2018a)

Fuzzy Logic Toolbox Version 2.3.1 (R2018a)

GPU Coder Version 1.1 (R2018a)

Image Processing Toolbox Version 10.2 (R2018a)

Instrument Control Toolbox Version 3.13 (R2018a)

MATLAB Coder Version 4.0 (R2018a)

MATLAB Compiler Version 6.6 (R2018a)

MATLAB Compiler SDK Version 6.5 (R2018a)

Neural Network Toolbox Version 11.1 (R2018a)

OPC Toolbox Version 4.0.5 (R2018a)

Optimization Toolbox Version 8.1 (R2018a)

Parallel Computing Toolbox Version 6.12 (R2018a)

Signal Processing Toolbox Version 8.0 (R2018a)

Simulink Control Design Version 5.1 (R2018a)

Statistics and Machine Learning Toolbox Version 11.3 (R2018a)

Symbolic Math Toolbox Version 8.1 (R2018a)

Содержание

  1. Syms не работает — Undefined function or variable ‘syms’
  2. Решение
  3. Не работает объявление переменной/переменных sym/syms
  4. Документация
  5. Присвойте символьные переменные переменным MATLAB
  6. Создайте символьное число
  7. Создайте символьную переменную с предположениями
  8. Создайте много символьных переменных
  9. Создайте массив символьных переменных
  10. Символьная переменная во вложенной функции
  11. Похожие темы
  12. Открытый пример
  13. Документация Symbolic Math Toolbox
  14. Поддержка
  15. Syms matlab не работает
  16. Syntax
  17. Description
  18. Examples
  19. Create Symbolic Scalar Variables
  20. Create Vector of Symbolic Scalar Variables
  21. Create Matrix of Symbolic Scalar Variables
  22. Set Assumptions While Creating Variables
  23. Create Symbolic Functions
  24. Create Symbolic Functions with Matrices as Formulas
  25. Create Symbolic Matrices as Functions of Two Variables
  26. Create Symbolic Matrix Variables
  27. Commutation Relation of Symbolic Matrix Variables
  28. Find Hessian Matrix
  29. Create Symbolic Objects from Returned Symbolic Array
  30. List All Symbolic Scalar Variables, Functions, and Arrays
  31. Delete All Symbolic Variables, Functions, or Arrays
  32. Input Arguments
  33. var1 . varN — Symbolic scalar variables, matrices, arrays, or matrix variables valid variable names separated by spaces
  34. [n1 . nM] — Vector, matrix, or array dimensions of symbolic scalar variables vector of integers
  35. [nrow ncol] — Matrix dimensions of symbolic matrix variables vector of integers
  36. set — Assumptions on symbolic scalar variables real | positive | integer | rational
  37. f(var1. varN) — Symbolic function with its input arguments expression with parentheses
  38. symArray — Symbolic scalar variables and functions vector of symbolic scalar variables | cell array of symbolic scalar variables and functions
  39. Output Arguments
  40. S — Names of all symbolic scalar variables, functions, and arrays cell array of character vectors
  41. Limitations
  42. Compatibility Considerations
  43. syms clears assumptions

Syms не работает — Undefined function or variable ‘syms’

Помощь в написании контрольных, курсовых и дипломных работ здесь.

«Undefined function or method ‘syms’ for input arguments of type ‘char’»
>> syms x y . Undefined function or method ‘syms’ for input arguments of type ‘char’.

Не работает объявление переменной/переменных sym/syms
Подскажите, как можно решить данную проблему? Есть код из лабы, он рабочий, но мой лицензионный.

Syms — symbolic variables
помогите, пжл., что здесь не так syms D1s1 D1s2 D1s3 D2s1 D2s2 D2s3 D3s1 D3s2 D3s3 D x; D= .

Функция символа syms выдает ошибку
function w n=10 s=0; syms x for k=1:1:n g(k)=x^(k-1) end выдает такую ошибку, не понимаю.

Пробовали записать так?

К сожалению, я новичок в работе с Matlab’ом и многим не помогу, но попробуйте прописать

Решение

12.05.2015, 06:23 Syms не работает — Undefined function or variable ‘syms’

теперь, как заяц, между двумя версиями прыг-скок? 😀

Помощь в написании контрольных, курсовых и дипломных работ здесь.

Задание натурального логарифма с помощью syms.
дан пример J(y)=интеграл от 1 до 3(y’^2-y’lnx+2x)dx не получается в syms задать натуральный.

Undefined function or variable
Вот код — ошибка в том, что матлаб не видит заданное значение omega_M и epsilon. Если из f убрать.

Undefined function or variable
Есть программа, которая решает задачу управления многозначными траекториями. Написана она на более.

Ошибка Undefined function or variable
Здравствуйте, есть программа которая решает методом Адамса-Бешфорса-Мултона дифференциальные.

Источник

Не работает объявление переменной/переменных sym/syms

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

Текст ошибки:
Error using mupadmex
Internal error with symbolic engine. Quit and restart MATLAB.

Error in sym>symr (line 1321)
[S,err] = mupadmex(‘ ‘,x,3);

Error in sym>numeric2cellstr (line 1262)
S = symr(double(x(k)));

Error in sym>tomupad (line 1219)
S = mupadmex(numeric2cellstr(x));

Error in sym (line 211)
S.s = tomupad(x);

Error in sympref (line 81)
iSymprefs = implementedSymprefs;

Error in symengine

Error in sym (line 185)
symengine;

Warning: Failed to initialize symbolic preferences.
> In symengine
In sym (line 185)
Error using mupadmex
Internal error with symbolic engine. Quit and restart MATLAB.

Error in symengine

Error in sym (line 185)
symengine;

Error using mupadmex
Internal error with symbolic engine. Quit and restart MATLAB.

Error in sym>tomupad (line 1219)
S = mupadmex(numeric2cellstr(x));

Error in sym (line 211)
S.s = tomupad(x);

Error in syms (line 201)
toDefine = sym(zeros(1, 0));

Комментарий модератора
Правила форума, пункт 5.5. Запрещено размещать тему в нескольких подразделах одного раздела одновременно (кросспостинг), а также дублировать тему в одном разделе.

Помощь в написании контрольных, курсовых и дипломных работ здесь.

Источник

Документация

В Symbolic Math Toolbox™ можно объявить символьные объекты с помощью любого syms или sym . Эти две функции концептуально отличаются.

syms функция создает символьный объект, который автоматически присвоен переменной MATLAB® с тем же именем.

sym функция относится к символьному объекту, который может быть присвоен переменной MATLAB с тем же именем или другим именем.

Присвойте символьные переменные переменным MATLAB

syms функция создает переменную динамически. Например, команда syms x создает символьную переменную x и автоматически присвоения это к переменной MATLAB с тем же именем.

sym функция относится к символьной переменной, которую можно затем присвоить переменной MATLAB с другим именем. Например, команда f1 = sym(‘x’) относится к символьной переменной x и присвоения это к переменной MATLAB f1 .

Создайте символьное число

Используйте syms функция, чтобы создать символьную переменную x и автоматически присвойте его переменной MATLAB x . Когда вы присваиваете номер переменной MATLAB x , номер представлен в с двойной точностью, и это присвоение перезаписывает предыдущее присвоение на символьную переменную. Класс x становится double .

Используйте sym функция, чтобы относиться к точному символьному числу без приближения с плавающей точкой. Можно затем присвоить этот номер переменной MATLAB x . Класс x sym .

Создайте символьную переменную с предположениями

Когда вы создаете символьную переменную с предположением, MATLAB хранит символьную переменную и ее предположение отдельно.

Используйте syms создать символьную переменную, которая присвоена переменной MATLAB с тем же именем. Вы получаете новую символьную переменную без предположений. Если вы объявляете переменную с помощью syms , очищены существующие предположения.

Используйте sym относиться к существующей символьной переменной. Если эта символьная переменная использовалась в вашем сеансе работы с MATLAB прежде, то sym относится к нему и его текущему предположению. Если это не использовалось прежде, то sym создает его без предположений.

Создайте много символьных переменных

Создать много символьных переменных одновременно, с помощью syms функция более удобна. Можно создать несколько переменных в одной строке кода.

Когда вы используете sym , необходимо объявить переменные MATLAB один за другим и отослать их к соответствующим символьным переменным.

Создайте массив символьных переменных

Чтобы объявить символьный массив, который содержит символьные переменные как его элементы, можно использовать любой syms или sym .

Команда syms a [1 3] создает 1 3 символьный массив a и символьные переменные a1 , a2 , и a3 в рабочей области. Символьные переменные a1 , a2 , и a3 автоматически присвоены символьному массиву a .

Команда a = sym(‘a’,[1 3]) относится к символьным переменным a1 , a2 , и a3 , которые присвоены символьному массиву a в рабочей области. Элементы a1 , a2 , и a3 не создаются в рабочей области.

Символьная переменная во вложенной функции

Чтобы объявить символьную переменную во вложенной функции, используйте sym . Например, можно явным образом задать переменную MATLAB x в родительской функциональной рабочей области и отсылают x к символьной переменной с тем же именем.

Вложенные функции делают рабочую область статической, таким образом, вы не можете динамически добавить переменные с помощью syms .

Похожие темы

Открытый пример

У вас есть модифицированная версия этого примера. Вы хотите открыть этот пример со своими редактированиями?

Поддержка

© 1994-2021 The MathWorks, Inc.

1. Если смысл перевода понятен, то лучше оставьте как есть и не придирайтесь к словам, синонимам и тому подобному. О вкусах не спорим.

2. Не дополняйте перевод комментариями “от себя”. В исправлении не должно появляться дополнительных смыслов и комментариев, отсутствующих в оригинале. Такие правки не получится интегрировать в алгоритме автоматического перевода.

3. Сохраняйте структуру оригинального текста — например, не разбивайте одно предложение на два.

4. Не имеет смысла однотипное исправление перевода какого-то термина во всех предложениях. Исправляйте только в одном месте. Когда Вашу правку одобрят, это исправление будет алгоритмически распространено и на другие части документации.

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

Источник

Syms matlab не работает

Create symbolic scalar variables, functions, and matrix variables

Syntax

Description

syms var1 . varN creates symbolic scalar variables var1 . varN of type sym . Separate different variables by spaces. This syntax clears all previous definitions of var1 . varN . Since R2018b, syms also clears all assumptions from the variables.

syms var1 . varN [n1 . nM] creates arrays of symbolic scalar variables var1 . varN , where each array has the size n1 -by- . -by- nM and contains automatically generated symbolic scalar variables as its elements. For brevity, an array of symbolic scalar variables is also called a symbolic array. For example, syms a [1 3] creates the symbolic array a = [a1 a2 a3] and the symbolic scalar variables a1 , a2 , and a3 in the MATLAB ® workspace. For multidimensional arrays, these elements have the prefix a followed by the element’s index using _ as a delimiter, such as a1_3_2 .

syms var1 . varN n creates n -by- n matrices of symbolic scalar variables filled with automatically generated elements. For brevity, a matrix of symbolic scalar variables is also called a symbolic matrix.

syms ___ set sets the assumption that the created symbolic scalar variables belong to set , and clears other assumptions. Here, set can be real , positive , integer , or rational . You can also combine multiple assumptions using spaces. For example, syms x positive rational creates a symbolic scalar variable x with a positive rational value.

syms f(var1. varN) creates the symbolic function f of type symfun and the symbolic scalar variables var1. varN , which represent the input arguments of f . This syntax clears all previous definitions of var1. varN including symbolic assumptions. 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 scalar 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 scalar 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 scalar variable x in the MATLAB workspace. For multidimensional arrays, these elements have the prefix 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 matrix of symbolic functions filled with automatically generated elements.

syms var1 . varN [nrow ncol] matrix creates symbolic matrix variables var1 . varN of type symmatrix , where each symbolic matrix variable has the size nrow -by- ncol . (since R2021a)

syms var1 . varN n matrix creates n -by- n symbolic matrix variables. (since R2021a)

syms( symArray ) creates the symbolic scalar variables and functions contained in symArray , where symArray is either a vector of symbolic scalar variables or a cell array of symbolic scalar variables and functions. This syntax clears all previous definitions of variables specified in symArray including symbolic assumptions. 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 scalar variables, functions, and arrays in the MATLAB workspace.

S = syms returns a cell array of the names of all symbolic scalar variables, functions, and arrays.

Examples

Create Symbolic Scalar Variables

Create symbolic scalar variables x and y .

Create Vector of Symbolic Scalar Variables

Create a 1-by-4 vector of symbolic scalar variables a with the automatically generated elements a 1 , … , a 4 . This command also creates the symbolic scalar 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 scalar 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 Matrix of Symbolic Scalar Variables

Create a 3-by-4 matrix of symbolic scalar variables with automatically generated elements. The elements are of the form A i , j , which generates the symbolic matrix variables A 1 , 1 , … , A 3 , 4 .

Set Assumptions While Creating Variables

Create symbolic scalar variables x and y , and assume that they are integers.

Create another scalar 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 matrix of symbolic scalar variables.

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 Matrix Variables

Create two symbolic matrix variables with size 2 -by- 3 . Nonscalar symbolic matrix variables are displayed as bold characters in the Live Editor and Command Window.

Add the two matrices. The result is represented by the matrix notation A + B .

The data type of X is symmatrix .

Convert the symbolic matrix variable X to a matrix of symbolic scalar variables Y . The result is denoted by the sum of the matrix components.

The data type of Y is sym .

Show that the converted result in Y is equal to the sum of two matrices of symbolic scalar variables.

Commutation Relation of Symbolic Matrix Variables

Symbolic matrix variables represent matrices, vectors, and scalars in compact matrix notation. When representing nonscalars, these variables are noncommutative. When mathematical formulas involve matrices and vectors, writing them using symbolic matrix variables is more concise and clear than writing them componentwise.

Create two symbolic matrix variables.

Check the commutation relation for multiplication between two symbolic matrix variables.

Check the commutation relation for addition between two symbolic matrix variables.

Find Hessian Matrix

Create 3 -by- 3 and 3 -by- 1 symbolic matrix variables.

Find the Hessian matrix of X T A X . Derived equations involving symbolic matrix variables are displayed in typeset as they would be in textbooks.

Create Symbolic Objects from Returned Symbolic Array

Certain functions, such as solve and symReadSSCVariables , can return a vector of symbolic scalar variables or a cell array of symbolic scalar 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 Scalar Variables, Functions, and Arrays

Create some symbolic scalar variables, functions, and arrays.

Display a list of all symbolic scalar variables, functions, and arrays that currently exist in the MATLAB workspace by using syms .

Instead of displaying a list, return a cell array by providing an output to 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 scalar variables, matrices, arrays, or matrix variables
valid variable names separated by spaces

Symbolic scalar variables, matrices, arrays, or matrix variables (since R2021a) , specified as valid variable names separated by spaces. Each variable name must begin with a letter and can contain only alphanumeric characters and underscores. To verify that the name is a valid variable name, use isvarname .

Example: x y123 z_1

[n1 . nM] — Vector, matrix, or array dimensions of symbolic scalar variables
vector of integers

Vector, matrix, or array dimensions of symbolic scalar variables, 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 of symbolic scalar variables.

Example: [2 3] , [2,3]

[nrow ncol] — Matrix dimensions of symbolic matrix variables
vector of integers

Matrix dimensions of symbolic matrix variables, specified as a vector of integers. As a shortcut, you can create a square symbolic matrix variable by specifying only one integer. For example, syms x 3 matrix creates a square 3 -by- 3 symbolic matrix variable.

Example: [2 3] , [2,3]

set — Assumptions on symbolic scalar variables
real | positive | integer | rational

Assumptions on symbolic scalar variables, specified as real , positive , integer , or rational .

You can combine multiple assumptions using spaces. For example, syms x positive rational creates a symbolic scalar variable x with a positive rational value.

Example: rational

f(var1. varN) — Symbolic function with its input arguments
expression with parentheses

Symbolic function with its input arguments, specified as an expression with parentheses. The function name f and the variable names var1. varN must be valid variable names. That is, they must begin with a letter and can contain only alphanumeric characters and underscores. To verify that the name is a valid variable name, use isvarname .

Example: s(t) , f(x,y)

symArray — Symbolic scalar variables and functions
vector of symbolic scalar variables | cell array of symbolic scalar variables and functions

Symbolic scalar variables or functions, specified as a vector of symbolic scalar variables or a cell array of symbolic scalar 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 scalar variables, functions, and arrays
cell array of character vectors

Names of all symbolic scalar variables, functions, and arrays in the MATLAB workspace, returned as a cell array of character vectors.

Limitations

Using Symbolic Math Toolbox™, you can create symbolic functions that depend on symbolic scalar variables as parameters. However, symbolic matrix variables cannot be parameter-dependent. For example, the command syms A(x) [3 2] matrix currently errors.

Differentiation functions, such as jacobian and laplacian , currently do not accept symbolic matrix variables as input. To evaluate differentiation with respect to vectors and matrices, you can use the diff function instead.

To show all the functions in Symbolic Math Toolbox that accept symbolic matrix variables as input, use the command methods symmatrix .

syms is a shortcut for sym . This shortcut lets you create several symbolic scalar 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.

In functions and scripts, do not use syms to create symbolic scalar variables with the same names as MATLAB functions. For these names, MATLAB does not create symbolic scalar variables, but keeps the names assigned to the MATLAB functions. If you want to create a symbolic scalar variable with the same name as a MATLAB function inside a function or a script, use sym instead. For example, use alpha = sym(‘alpha’) .

Avoid using syms within functions, since it generates variables without direct output assignment. Using syms within functions can create side effects and other unexpected behaviors. Instead, use sym with left-side output assignment within functions, such as t = sym(‘t’) . For more details, see Choose syms or sym Function.

The following variable names are invalid with syms : integer , real , rational , positive , and clear . To create symbolic scalar 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 symbolic scalar 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 scalar 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 Considerations

syms clears assumptions

Behavior changed in R2018b

syms now clears any assumptions on the symbolic scalar variables that it creates. For example,

Источник

My Matlab is 2008b version

when I give the following command :

x=syms('x')

it return the follwing message :

??? Undefined function or method 'syms' for input arguments of type 'char'.

and the same for the command of the form :

 syms c1 c2 x 

how to run the symbol math in Matlab 2008b ?

asked Nov 9, 2012 at 16:10

Ibrahim Ghalawinji's user avatar

It is possible that you do not have the appropriate toolbox installed.

Run the command ver on the command line, and check whether the Symbolic Toolbox is one of the installed toolboxes.

answered Nov 9, 2012 at 16:15

Jonas's user avatar

JonasJonas

74.6k10 gold badges137 silver badges177 bronze badges

You can go in your Matlab installation path and click to uninstall the program. When it asks you to select, select modify and then in the installation page, you can select any toolbox you have not installed yet to be installed.

spenibus's user avatar

spenibus

4,32911 gold badges26 silver badges35 bronze badges

answered Oct 4, 2015 at 9:49

mahdi's user avatar

You can use just :

syms x;

like this:

clc
clear
syms x;
f=(sin(x)^2)+log(x)+sqrt(x-1);
disp(subs(f,x,5));`

Yanga's user avatar

Yanga

2,8471 gold badge29 silver badges32 bronze badges

answered Dec 24, 2016 at 7:22

RAM's user avatar

Понравилась статья? Поделить с друзьями:
  • Sims medieval ошибка публикации
  • Sims freeplay ошибка магазина 20020
  • Sims freeplay ошибка 20020 что делать
  • Sims freeplay ошибка 20013
  • Sims 4 скриптовая ошибка