Symbolic math toolbox matlab как установить
Давайте рассмотрим добавление набора инструментов 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.
- 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.
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.
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 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 plot
Example 2
Let’s look at another example:
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 .
Plot for the range -pi to pi
Plot for the range -2pi to 2pi
Plot for the range -4pi to 4pi
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
Цель работы:изучить систему команд расширения 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 – в прямой ветви, и звена – в обратной связи, при условии отрицательной обратной связи.
How to open symbolic math toolbox in matlab
There are several considerations in using symbolic calculations with optimization functions: Optimization objective and constraint functions should be defined in terms of a vector, say . Now we calculate the Hessians of the two constraint functions, and make function handle versions with .
How to install and enable Symbolic Math Toolbox
Solution 1:
Solution 2:
'Symbolic Math Toolbox' functions exist in MATLAB but not in the documentation
Solution:
It could be a license issue. Try to get further information with:
If you have a Student version, some functions cannot be executed.
In case that you are in an office/university, and you have floating licenses. Be sure to check-out all the licenses before running your code.
Using Symbolic Mathematics with Optimization Toolbox Solvers
This example shows how to use the Symbolic Math Toolbox™ functions jacobian and matlabFunction to provide analytical derivatives to optimization solvers. Optimization Toolbox™ solvers are usually more accurate and efficient when you supply gradients and Hessians of the objective and constraint functions.
Problem-based optimization can calculate and use gradients automatically; see Automatic Differentiation in Optimization Toolbox. For a problem-based example using automatic differentiation, see Constrained Electrostatic Nonlinear Optimization, Problem-Based.
There are several considerations in using symbolic calculations with optimization functions:
Optimization objective and constraint functions should be defined in terms of a vector, say x . However, symbolic variables are scalar or complex-valued, not vector-valued. This requires you to translate between vectors and scalars.
Optimization gradients, and sometimes Hessians, are supposed to be calculated within the body of the objective or constraint functions. This means that a symbolic gradient or Hessian has to be placed in the appropriate place in the objective or constraint function file or function handle.
Calculating gradients and Hessians symbolically can be time-consuming. Therefore you should perform this calculation only once, and generate code, via matlabFunction , to call during execution of the solver.
Evaluating symbolic expressions with the subs function is time-consuming. It is much more efficient to use matlabFunction .
matlabFunction generates code that depends on the orientation of input vectors. Since fmincon calls the objective function with column vectors, you must be careful to call matlabFunction with column vectors of symbolic variables.
First Example: Unconstrained Minimization with Hessian
The objective function to minimize is:
f ( x 1 , x 2 ) = log ( 1 + 3 ( x 2 — ( x 1 3 — x 1 ) ) 2 + ( x 1 — 4 / 3 ) 2 ) .
This function is positive, with a unique minimum value of zero attained at x1 = 4/3, x2 =(4/3)^3 — 4/3 = 1.0370.
We write the independent variables as x1 and x2 because in this form they can be used as symbolic variables. As components of a vector x they would be written x(1) and x(2) . The function has a twisty valley as depicted in the plot below.
Symbolic math toolbox matlab как установить
How to Install the Symbolic Math Toolbox to Use with MATLAB
Once you have obtained a copy of the Symbolic Math Toolbox to use with MATLAB, you should have a number of files on your hard drive. These files provide everything needed to install the Symbolic Math Toolbox. You have two ways by which you can interact with the files:
If you were able to use the download agent, you see a dialog box telling you that the download is complete. At this point, you can perform one of these two tasks:
Select the Start Installer option and click Finish to start the installation process. The Symbolic Math Toolbox installer will start automatically.
Select the Open Location of the Downloaded Files option and click Finish. You see the location of the files open, and you must double-click the installer file to start the installation process. (The installer file is typically the only executable program in the folder.)
If you performed the manual download process, you need to find the download location of the files. You must double-click the installer file to start the installation process. (The installer file is typically the only executable program in the folder.)
Windows platform users may see a User Account Control (UAC) dialog box when starting the installer. Click Yes to give the installer permission to install the Symbolic Math Toolbox. Otherwise, the installation will fail.
No matter how you start the installer, eventually you see a MathWorks installer dialog box. This dialog box determines the source of the files that you use to perform the installation. (Choosing the Install Using the Internet option downloads the files directly from the MathWorks site — you also have the option of using source files on your hard drive.) The following steps help you complete the installation process.
Select an installation source (either Internet or local hard drive) and click Next.
You see the License Agreement dialog box.
Read the licensing agreement, click Yes, and then click Next.
You see the File Installation Key dialog box. This is where you supply the licensing information. If you don’t have the key, make sure that you select the second option and follow the steps required to obtain the license.
Supply the File Installation Key and click Next.
The installer asks you to select an installation method. In most cases, you obtain a better, faster, more error-free installation by selecting the Typical option. The steps that follow assume that you have chosen the Typical option.
Click the Typical option and then click Next.
The installer asks you to choose an installation destination. This destination differs by platform. In most cases, choosing the default installation destination is the best idea. However, if you have an existing installation and want to preserve this installation precisely as it is, you need to choose a different installation location.
Choose a destination location, if necessary, and click Next.
If you already have a copy of MATLAB installed and you choose the default installation location, the installer will ask whether you want to overwrite the existing copy. Click Yes To All (if you need to update your copy of MATLAB) or No (when you have the most current version) to proceed.
When you click Yes To All, you agree to allow the installer to remove your old copy of MATLAB and install a new one. Be aware that you’ll likely lose any special configuration options you have set up, along with any features you had installed previously.
The installer displays a Confirmation dialog box. Check the details carefully to ensure that the installation provides everything you need.
Click Install.
The installation process begins. You can watch the progress by checking the progress bar. The installation can require several minutes depending on the installation options you choose, the complexity of the installation, and the speed of your system.
When the installation process is complete, you see an Installation Complete dialog box.
Select the Activate MATLAB option and then click Next.
MATLAB asks whether you want to activate your copy using the Internet or manually. Using the Internet is generally the faster and easier option, unless you have already downloaded a license file ( license.lic ) as part of getting the file installation key.
Choose an activation option and click Next.
When you choose the Internet option, you must provide your email address and password to log on to the system for activation purposes. If you don’t have an account, you can also choose to create an account or provide the location of your locally stored license.lic file.
Supply any required input and click Next.
If activation is successful, you see an Activation Complete dialog box. (When you don’t see this dialog box, retry obtaining the required activation or contact MathWorks support.)
Multiprecision Computing Toolbox User’s Manual
The Multiprecision Computing Toolbox is easily installed after following only a few brief steps.
Windows. After downloading the program allow it to run. Follow the step-by-step instructions of the installer to complete the installation process.
GNU Linux and Mac OSX. Installation instructions are provided upon trial version request for the platforms.
After installation we recommend completing the following steps:
-
Add the destination folder where toolbox is installed to MATLAB’s search path. For Windows 7, this may look like the following:
Quick Start
Arbitrary precision numbers and matrices can be created with the new special function mp() , which stands for multiprecision:
The argument to the constructor mp() can be a string with mathematical expression or usual MATLAB’s matrix of any numeric type ( double, single, logical, int8, int16, int32, int64 or else). Complex numbers, n-dimensional arrays and sparse matrices are supported as well.
Constructor creates objects with default precision controlled by mp.Digits() routine. On toolbox startup default precision is assigned to 34 decimal digits which conforms to IEEE 174-2008 standard for quadruple precision.
Toolbox is capable of working with any level of precision – hardware configuration is the only limiting factor:
Once are created, the new multiprecision numbers and matrices can be used in programs the same way as ordinary double precision objects:
These examples show a basic principle of the MATLAB program porting to the computing with toolbox. In most cases, this is accomplished by substituting standard numeric objects with the analogous multiprecision entities. The rest of the code stays intact – computations are now completed using requested level of precision transparently to user.
Information on toolbox-specific routines can be obtained by the MATLAB help command: help mp.Digits, help mp.GaussLegendre , etc.)
The toolbox provides extended-precision equivalents to the majority of the commonly used MATLAB routines.
Every function in toolbox is implemented in multiple different modifications in order to support all special cases and features of MATLAB’s standard routines. For example, arbitrary precision eig(), svd(), ifft() and bicgstab() functions cover all of the following special cases:
All options are supported:
[___] = eig(A,balanceOption)
[___] = eig(A,B,algorithm)
[___] = eig(___,eigvalOption)
BiCGSTAB iterative solver for large/sparse matrices:
x = bicgstab(A,b)
bicgstab(A,b,tol)
bicgstab(A,b,tol,maxit)
bicgstab(A,b,tol,maxit,M)
bicgstab(A,b,tol,maxit,M1,M2)
bicgstab(A,b,tol,maxit,M1,M2,x0)
[x,flag] = bicgstab(A,b. )
[x,flag,relres] = bicgstab(A,b. )
[x,flag,relres,iter] = bicgstab(A,b. )
[x,flag,relres,iter,resvec] = bicgstab(A,b. )
Please refer to Function Reference page for a complete list of supported functions. All of them are capable of computing with arbitrary level of precision and support special cases and options of MATLAB.
Be aware that in some cases this may affect accuracy of the final result of computations:
Generally, floating-point numbers should be re-calculated using high precision arithmetic from the onset, not converted from MATLAB as the accuracy is inherited. Please see More on Existing Code Porting for examples and more details.
In examples on the page we frequently use direct conversion of double matrices to mp-type. This is just for making demonstrations brief and simple, as it is not part of physical simulations or other meaningful computations. Please be careful in real-world applications.
More Examples
In this section we show several examples of toolbox usage in different fields. This reflects just the tiny portion of toolbox functionality, but we hope it will be helpful for understanding on how to apply toolbox in other situations.
Arbitrary Precision Gauss-Legendre Quadrature
Our first example illustrates one particular case of existing code porting to computing with extended precision.
The Gauss-Legendre quadrature’s nodes and weights can be calculated from the eigenvalues and eigenvectors of a Jacobi matrix, built from the coefficients of a 3-term recurrence relation of orthogonal Legendre polynomials. MATLAB code for the algorithm:
Toolbox enables this program to calculate abscissae and weights with arbitrary precision, without any modifications to code:
How is this possible? During the program’s every function call, MATLAB detects the type of supplied arguments. Built-in functions are called for the numeric objects of standard double type. However, if an argument is a multiprecision number or matrix, MATLAB recognizes this and uses the functions provided by Multiprecision Computing Toolbox.
Thus, when we pass mp-number mp(N) to gauss() , MATLAB uses the high precision routines from the toolbox for all further mathematical operations: +, -, *, ./, colon(:), .^, diag(), eig() and sort() .
It is important to note that MATLAB does a silent conversion of the floating-point constant 0.5 using the mp() constructor. Since 0.5 is a power of 2 , it is exactly representable in binary format using the standard double type. As a result, direct conversion to extended precision is safe – no rounding error is introduced in a process. All other non-power-of-two constants should be re-computed in higher precision by the toolbox (e.g. 1/3 => mp(‘1/3’) ).
Linear Algebra (Dense matrices)
All linear algebra routines in toolbox are implemented in native C++/Assembler programming languages with heavy optimization for parallel execution on multi-core CPUs. We implement only state-of-the-art algorithms, as soon as they appear in LAPACK or published in papers.
Every routine (e.g. det , svd , eig , etc.) is a meta-algorithm which analyses the properties of the input matrix and applies the best suitable method for it.
Thus, for example, eigensolver uses multi-shift QR with aggressive deflation for unsymmetric matrices, MRRR or D&C for symmetric and tridiagonal matrices. The system solver \ handles much more additional cases, including positive definite, banded and triangular matrices.
Solve system of equations
Although ill-conditioning has eaten up 15 digits of accuracy, extended precision is able to provide meaningful solution anyway.
Compute sensitive eigenvalues
The eigenvalues of the matrix (we call it “Circus matrix”) are invariant to transposition, so that eig(A)==eig(A.’) . We verify this property below using the double and quadruple precision:
The eigenvalues of the original matrix are displayed in black, and the eigenvalues of the transposed – in red. They should coincide:
Similar examples can be found on the page Computing Eigenvalues in Extended Precision.
Besides the main routine eig , toolbox provides less common functions related to eigenproblems: condeig, schur, ordeig, ordqz, ordschur, poly, polyeig, qz, hess, balance, cdf2rdf and rsf2csf .
Compute subset of eigenvalues and eigenvectors
Toolbox implements EIGS routine for computing part of the eigenspectrum:
It is based on Krylov-Schur iterative method with the support of usual features: standard and generalized eigenproblems, matrix and function handle inputs and various parts of the spectrum – ‘SM’, ‘LM’, ‘SA’, ‘LA’, ‘SI’, ‘LI’, ‘SR’ and ‘LR’ .
In case of handle inputs, routine MPEIGS should be called:
Matrix functions
Evaluation of matrix functions is closely related to Schur decomposition and eigenproblem in general. Naturally extended precision plays important role in the field as well. Toolbox provides all common routines – expm, sqrtm, logm, sinm, cosm, sinhm, coshm and funm for computing arbitrary matrix functions.
Maximum relative error over 10 tests when run with double precision:
Correct result can be obtained by using the quadruple precision:
Linear Algebra (Sparse matrices)
Creation and manipulation
Similarly to dense case, multiprecision sparse matrices can be created in several ways.
Or directly by using the special functions:
Toolbox provides the basic functionality for working with sparse matrices: element-wise access, indexing & assignment, concatenation and basic functions ( nonzeros, spfun, spones, min/max, find, nnz, etc.). Arithmetic operations also support mixed type arguments (full-sparse) and compatible with MATLAB’s semantic (type of result, etc).
Direct solvers
System solver in toolbox ( mldivide or \ ) relies on direct decompositions – SuperLU , Cholesky and sparse QR , depending on problem to be solved. All of them are implemented in C++ and capable of working with arbitrary precision.
The mmread routine is needed to read MatrixMarket matrices and it is provided here.
Timing examples for solving the test matrices from MatrixMarket and test scripts can be found on the pages: Direct Solvers for Sparse Matrices or Advanpix vs. Maple – Direct Sparse Solvers Comparison.
Iterative solvers
Toolbox includes following full-featured iterative solvers: BiCG, BiCGSTAB, BiCGSTABL, CGS, GMRES, MINRES and PCG .
All methods are capable of working with arbitrary precision sparse and dense matrices. Routines are implemented in different variants, support preconditionares, matrix and function handles as inputs. Please use them in your code, see Krylov Subspace Methods in Arbitrary Precision and Arbitrary Precision Iterative Solver – GMRES for more details.
But here we consider simple self-written conjugate gradient for illustrative purposes.
Let’s consider conjugate gradient iterative method and check how its convergence speed changes with precision. Here is very simple implementation (without preconditioning or else):
Ideally CG should produce exact solution in a number of steps no large than the size of the matrix. In a world of double precision floating-point arithmetic this obviously doesn’t work:
The method needs 15.6 times more iterations to reach the 1e-10 accuracy in double precision than theory dictates! Exactly the same routine can be used to solve the problem using quadruple precision:
Two times less iterations needed, but still too many. Toolbox allows computing with any level of precision, e.g. let’s try 650 digits:
Finally practice coincides with theory – method converged in 237 iterations = matrix size. Worth to note that high precision might actually give boost in performance, since much less number of iterations is required:
Iterations required to reach 1e-10 accuracy versus precision used in solver (CG, NOS1.mtx)
Numerical methods
Solve system of nonlinear equations (fsolve)
Toolbox provides full-featured fsolve , including sparse formulation, Jacobian and three algorithms of optimization: Levenberg-Marquardt , trust-region-dogleg and trust-region-reflective . All options and special cases are covered:
x = fsolve(fun,x0)
x = fsolve(fun,x0,options)
x = fsolve(problem)
[x,fval] = fsolve(fun,x0)
[x,fval,exitflag] = fsolve(. )
[x,fval,exitflag,output] = fsolve(. )
[x,fval,exitflag,output,jacobian] = fsolve(. )
Quick start example for demonstration:
Find function zeros
Find zeros of nonlinear function using fzero . Try double precision first:
Here is plot of the function produced by MATLAB in double precision:
Do the same but with 50-digits of precision:
MATLAB is not able to overcome the cancellation errors in computing function zeros, whereas elevated precision does provide the correct results.
Numerical integration
Numerical integration using the adaptive Gauss-Kronrod quadrature:
The quadgk routine provided in toolbox computes Gauss-Kronrod coefficients for the requested precision and then runs adaptive integration algorithm.
If you are interested in more details on how to compute the coefficients in arbitrary precision please take a look on the page: Gauss-Kronrod Quadrature Nodes and Weights.
Ordinary differential equations
Solve nonstiff differential equations using ode113 (toolbox also provides ode45 and ode15s ):
Symbolic Math Toolbox (VPA) vs. Multiprecision Computing Toolbox
Even in basic operations like elementary functions:
Or in trivial array manipulation (e.g. vertical concatenation):
VPA gives plainly wrong results in some cases:
Even for basic special functions:
Moreover MATLAB has serious issues with accurate computation of special functions even in double precision.
In case of Bessel functions of the first and second kind Yn(x) and Jn(x) – MATLAB suffers from catastrophic accuracy loss near zeros of the functions. Red lines show the expected limits of relative error for double precision:
MATLAB’s functions bessely(n,x) and besselj(n,x) give no single correct digit in neighborhood of zeros of Yn(x) and Jn(x) .
In case of modified Bessel functions MATLAB provides non-uniform accuracy (depending on argument range) and actually gives the highest error among mathematical libraries. For example, relative accuracy in terms of machine epsilon for might reach the 11.5eps near
:
Please refer to the reports: K0(x) , K1(x) , I0(x) and I1(x) for more details on modified functions.
Built-in Hankel functions in MATLAB suffers from accuracy loss as well:
Same for gamma (and many other functions) in MATLAB:
To be fair, accuracy loss is endemic issue of numerical libraries, commercial or open source. For example, relative accuracy plots for I1(x) of NAG libraries:
NAG demonstrates serious accuracy degradation for :
Actually relative error can be as high as 257eps .
Last but not the least issue with Symbolic Math Toolbox is that it doesn’t follow semantic of MATLAB’s standard functions. For example, it has no support for n-dimensional arrays in basic functions like max, min, sum, mean, etc.:
More on Existing Code Porting
Smooth transition (ideally without modifications) of existing code to arbitrary precision is the main goal of the Multiprecision Computing Toolbox. However, there is an important case to be aware of.
Floating-point numerical constants in the code, such as 1/3, pi, sin(pi/3), sqrt(2)/2, eps, realmin, realmax , should be calculated using multiprecision arithmetic – mp(‘1/3’), mp(‘pi’), mp(‘sin(pi/3)’), mp(‘sqrt(2)/2’), mp(‘eps’), eps(‘mp’), realmin(‘mp’), realmax(‘mp’) . Otherwise, MATLAB will evaluate these numbers with its standard precision first, and this might affect the overall accuracy of computations as well as final result.
Be aware that in some cases this may affect accuracy of the final result of computations:
Extra-care should be taken to the stopping criteria of various iterative algorithms. Most likely it should be changed to allow more iterations and use machine epsilon matching to precision used.
Following function is from Chebfun, it is one of the many used in computing nodes & weights of Gauss-Laguerre quadrature:
Assuming that input parameter xs is passed as mp-number, the routine will run in multiprecision mode. But still we need to do few changes to the code (changed lines are highlighted):
Now stopping criteria is capable of working with arbitrary precision (maximum number of iterations is an open question, probably it needs to be found empirically for every level of precision or omitted altogether).
Please check the article How to write precision independent code in MATLAB for more ideas on the process.
Symbolic Math Toolbox
Symbolic Math Toolbox™ provides functions for solving, plotting, and manipulating symbolic math equations. You can create, run, and share symbolic math code. In the MATLAB ® Live Editor, you can get next-step suggestions for symbolic workflows. The toolbox provides functions in common mathematical areas such as calculus, linear algebra, algebraic and differential equations, equation simplification, and equation manipulation.
Symbolic Math Toolbox lets you analytically perform differentiation, integration, simplification, transforms, and equation solving. You can perform dimensional computations and convert between units. Your computations can be performed either analytically or using variable-precision arithmetic, with the results displayed in mathematical typeset.
You can share your symbolic work with other MATLAB users as live scripts or convert them to HTML, Word, LaTeX, or PDF documents. You can generate MATLAB functions, Simulink ® function blocks, and Simscape™ equations directly from symbolic expressions.
MATLAB 8.0 (R2012b) — красота аналитических вычислений с пакетом Symbolic Math Toolbox
В MATLAB 8.0 символьные (аналитические) вычисления выполняются с применением пакета расширения по символьной математике Symbolic Math Toolbox 5.9, созданного на основе сравнительно новой системы компьютерной математики MuPad, встроенной в MATLAB. Вычисления можно выполнять прямо в окне командного режима работы MATLAB (рис. 1).
Рис. 1. Примеры символьных вычислений в окне командного режима MATLAB 8.0
Для изучения возможностей символьных вычислений рекомендуется пользоваться справкой по пакету расширения Symbolic Math Toobox (рис. 2). Она подробная, но представлена на английском языке.
Рис. 2. Окно справки MATLAB 8.0 по пакету расширения Symbolic Math Toolbox
Есть и другой путь оценки всех возможностей пакета. Для этого нужно исполнить в командном режиме команду:
Будут выведены данные о версии пакета, дата его создания и список всех возможностей:
Мы привели лишь начало списка. Пользователю настоятельно рекомендуется просмотреть этот список полностью. Команда help name выводит справку по функции с именем name.
Есть и другой, порою более удобный путь выполнения таких вычислений — в окне ноутбука интегрированной системы компьютерной алгебры MuPad со своим графическим интерфейсом пользователя GUI (рис. 3). Ноутбук вызывается кнопкой MuPad в каталоге приложений APPS новейшей системы MATLAB 8.0.
Рис. 3. Ноутбук системы MuPad 5.9, интегрированной с MATLAB 8.0
В правой части окна MuPad расположены отключаемые панели ввода операторов и функций MuPad и команд графики. На рис. 3 приведены простые примеры вычислений и окно c данными пакета Symbolic Math.
Начало символьных вычислений
При символьных вычислениях используются неопределенные (символьные) переменные. В ноутбуках MuPad все переменные изначально являются неопределенными. При вычислениях в командном окне MATLAB символьные переменные задаются поодиночке как:
или группой, например:
Заданные переменные появляются в рабочем пространстве MATLAB (рис. 1). Теперь становится возможным выполнение простых аналитических вычислений, например проверка правила о том, что при любом x сумма квадратов синуса и косинуса равна 1:
Обратите внимание на то, что в режиме символьных вычислений входные и выходные ячейки выводятся без характерного для обычных численных вычислений отступа относительно символа приглашения >>. Программы указываются без символа >> у строк ввода.
Symbolic Math работает с 8–64‑разрядными числами и числами одинарной и двойной точности. Для работы с комплексными числами также существует ряд возможностей, например вызов действительной и мнимой частей:
С комплексными числами могут работать также некоторые функции символьных преобразований, которые будут описаны позже.
Математические выражения и функции
В математических выражениях могут использоваться широко распространенные встроенные функции и арифметические операторы «+», «–», «*», «/» и «^». В общем случае это векторные и матричные операторы. Если необходимы операторы поэлементные, то нужно использовать операторы «.+», «.–», «.*», «./» и «.^». Пример:
В выражениях доступны все элементарные функции и множество специальных. Так, в приведенном примере использована функция синуса. Можно также задать абстрактную функцию:
Набор операторов и функций системы MuPad немного отличается от примененного в пакете расширения Symbolic Math. Этот набор представлен в панелях ноутбуков.
Вывод символьного выражения в формате C , LaTeX и Fortran
К сожалению, в отличие от современных систем символьной математики (Mathcad, Maple или Mathematica), система MATLAB пока не рассчитана на вывод выражений и результатов их преобразований в естественной математической форме. Тем не менее некоторые, ограниченные текстовым форматом возможности близкого к математическому виду вывода обеспечивает функция pretty:
Функция latex(S) возвращает выражение S в форме языка LaTeX. Примеры применения этой функции:
С помощью функции ccode(S) можно представить выражения языка MATLAB в форме, принятой в языке C:
Функция fortran(S) обеспечивает преобразование выражения MATLAB в форму, соответствующую записи на языке Fortran.
Матрицы с символьными элементами
Символьные переменные можно использовать в качестве элементов матриц:
С такими матрицами можно выполнять различные символьные операции, описанные ниже. Символьные операции можно выполнять и в окне ноутбука системы MuPad (рис. 4). Кстати, в нем показано окно справки по точечному произведению матриц.
Рис. 4. Выполнение символьных операций в окне ноутбука системы MuPad
Векторизация означает проведение почленного преобразования элементов матриц и векторов. В MATLAB функция vectorize(S) для символьного выражения S вставляет знак «.» перед всеми следующими символами: «^», «*» или «/». Результатом будет строка, содержащая операторы для почленного вычисления выражения:
Арифметика произвольной точности
Арифметикой произвольной точности, или просто точной арифметикой, называют вычисления, у которых все числа результатов являются точными. Функция digits служит для установки числа цифр в числах арифметики произвольной точности:
Для проведения вычислений в арифметике произвольной точности (со всеми верными цифрами чисел) служит функция vpa(S), которая возвращает результат вычислений каждого элемента символьного массива S , используя арифметику произвольной точности с текущим числом цифр D , установленным функцией digits. Функция vpa(S,D) возвращает результат с количеством знаков чисел D .
Точные вычисления с большими факториалами в ноутбуке системы MuPad показаны на рис. 3.
Символьные операции линейной алгебры
Линейная алгебра — главная особенность системы MATLAB. Но реализована она численными методами. В этом разделе описаны функции линейной алгебры, обеспечивающие символьные преобразования и вычисления векторов и матриц, существенно расширяющие типовые средства линейной алгебры системы MATLAB.
Для создания диагональных матриц и извлечения из них диагональных элементов служит функция diag(V,K): если V — вектор с N компонентами, то формируется квадратная матрица с размером N+ABS(K), в которой на K ‑ой диагонали размещен вектор V . При K = 0 вектор V располагается на главной диагонали, при K > 0 на K ‑ой диагонали сверху, а при K < 0 — снизу относительно главной диагонали. Помимо заданных, остальные элементы матриц — нули. Применение этой функции вполне очевидно, как и функции triu для формирования верхней треугольной матрицы и tril — для формирования нижней треугольной матрицы.
Для обращения (инвертирования) матрицы в символьном виде используется функция inv:
Функция det(X) вычисляет детерминант квадратной матрицы в символьном виде.
Для вычисления ранга квадратной матрицы используется функция rank:
Для приведения матрицы к верхней треугольной форме используется функция rref. Функция [R,jb] = rref(A,tol) осуществляет приведение матрицы к треугольной форме, используя метод исключения Гаусса с частичным выбором ведущего элемента для заданного значения порога допустимости tol.
Функция Z = null(A) возвращает матрицу Z , столбцы которой являются базисом нуль-пространства целочисленной матрицы A . Число столбцов матрицы Z задает размер нуль-пространства. При этом A * Z = 0, а если матрица A имеет полный ранг, то матрица Z будет пустой.
Функция colspace(A) возвращает матрицу, столбцы которой являются образующими базиса пространства. Ранг целочисленной матрицы A равен size(B,2) . Для вычисления собственных значений и собственных векторов матриц используется функция eig, имеющая ряд форм записи:
LAMBDA=eig(A) — формирует символьный вектор LAMBDA собственных значений квадратной матрицы A .
[V,D]=eig(A) — возвращает матрицу V , столбцы которой являются векторами собственных значений матрицы A , и диагональную матрицу D собственных значений. Если размеры V и A одинаковы, то A имеет полную систему независимых собственных векторов. При этом A * V = V * D .
[V,D,P]=eig(A) — дополнительно к сказанному возвращает вектор индексов P , длина которого равна числу линейно независимых векторов. При этом A * V = V * D ( P , P ).
LAMBDA=eig(VPA(A)) и [V,D]= eig(VPA(A)) — возвращают численные значения собственных векторов и собственных значений в формате арифметики с произвольной точностью. Если матрица A не имеет полной системы собственных векторов, то столбцы матрицы V будут линейно зависимыми.
Для символьного вычисления матричных функций и операций линейной алгебры служит пакет расширения MuPad linalg:: (рис. 5). С его имени начинаются имена функций этого пакета. На рис. 5 показаны некоторые операции линейной алгебры и окно с разделом справки по операции транспонирования матриц.
Рис. 5. Вычисление некоторых матричных функций в ноутбуке MuPad
О богатстве операций линейной алгебры свидетельствует ноутбук системы MuPad (рис. 6). В правой части его окна открыты списки основных математических операций General Math и основных групп операций линейной алгебры.
Рис. 6. Окно ноутбука MuPad: списки основных математических операций General Math и основных групп операций линейной алгебры
Символьные операции математического анализа
Для вычисления в символьном виде производных от выражения S служит функция diff, записываемая в формате diff(S,‘v’) или diff(S, sym(‘v’)). Она возвращает символьное значение первой ( n = 1) производной от символьного выражения или массива символьных выражений S по переменной v :
Действие этой функции:
diff(S,n) — возвращает n ‑ю ( n — целое число) производную от символьного выражения или массива символьных выражений S по переменной v .
diff(S,‘v’,n) и diff(S,n,‘v’) — возвращает
n ‑ю производную S по переменной v , то есть значение:
S n ( v ) = d n S / dv n .
В практической работе часто возникает необходимость вычисления неопределенных и определенных интегралов вида:
I = ∫ f ( x ) dx
где f ( x ) — подынтегральная функция независимой переменной x ; a и b — нижний и верхний пределы интегрирования для определенного интеграла.
Примеры применения этой функции:
С помощью функции int можно вычислять имеющие аналитическое решение сложные интегралы, например с бесконечными пределами (или одним из пределов), а также кратные интегралы. Пример вычисления одного из таких интегралов:
Аппарат точной арифметики позволяет вычислять определенные интегралы, хотя при этом возникают трудности в связи с большими числами. К примеру, интеграл:
часто дает нулевое значение вместо 0,01835… Попробуем выяснить, в чем тут дело. Вычислим для этого неопределенный интеграл:
∫ x 20 exp(– x ) dx ,
используя функцию int, но в символьном виде:
Нетрудно заметить, что интеграл представлен рядом экспонент с большими множителями перед ними. MATLAB с пакетом Symbolic Math благополучно выдает точное и приближенное значение нашего интеграла:
Следующий пример относится к вычислению тройного интеграла:
Вычисление пределов функций представляет собой важный раздел математического анализа. Число L называется пределом функции F ( x ) в точке a , если при x , стремящемся к a (или x → a ), значение функции неограниченно приближается к L . Это обозначается следующим образом:
Предел может быть конечным числом, положительной или отрицательной бесконечностью. Приведем примеры применения этих функций:
В задачах аппроксимации и приближения функций f ( x ) важное место занимает их разложение в ряд Тейлора в окрестности точки a :
Частным случаем этого ряда при a = 0 является ряд Маклорена:
Для получения разложений аналитических функций в ряд Тейлора (и Маклорена) пятого порядка служит функция taylor:
Опция Order с последующим числом позволяет указать максимальный порядок (степень) ряда. Для построения графиков различных функций очень удобна графическая функция ezplot(f(x),[xmin, xmax]). Приведем программу, позволяющую сравнить график функции sin( x ) с графиком ряда Маклорена порядка 8 (рис. 7):
Рис. 7. Сравнение синусоидальной функции с ее разложением в ряд Маклорена с максимальной степенью 8
Следует сделать несколько комментариев по программе. Графики она строит в интервале изменения x от – pi до + pi . Кривые помечены разным цветом: синим — синусоида, красным — ее разложение в ряд. Установки set задают вид кривой и ее параметры. Команда hold on задерживает построение кривой синуса и позволяет отобразить ее в одном окне с кривой разложения. После этого команда hold off отключает задержку. Уже при максимальном порядке 10 кривые синуса и ряда Маклорена в пределах периода синусоиды совпадают в заданном интервале изменения x .
вычисляется функцией jacobian:
В математическом анализе часто приходится вычислять суммы некоторой функции f ( i ) для целочисленных значений аргумента i от a до b :
Примеры вычисления сумм:
Вычисление специальных функций
Специальные функции являются решениями интегралов специального вида или дифференциальных уравнений. В Symbolic Math включены основные типы специальных математических функций:
Рассмотрим некоторые из них. Для вычисления интегрального синуса:
служит функция sinint(z).
Интегральный косинус при |arg( z )| < p определяется выражением:
где g — постоянная Эйлера (0,5772…).
На рис. 8 показан построенный график функции интегрального косинуса при x от 0 до 10.
Рис. 8. График функции интегрального косинуса
Дзета-функция Римана определяется выражением:
W‑функция Ламберта является решением трансцендентного уравнения w exp( w ) = x и задается функцией lambertw(X) или lambertw(K, X). В последнем виде функция находит K ‑ю комплексную ветвь для многозначной функции.
Пример применения этой функции:
Функции rsums(f) и rsums f вычисляют приближение Римана к интегралу с подынтегральной функцией f ( x ) и строят график функции в виде столбцовой диаграммы и площадей под ее кривой (рис. 9). Здесь используется функция tan(x). Число термов можно менять от 2 до 256, перемещая ползунок под рисунком.
Рис. 9. Столбцовая диаграмма функции rsums
Решение алгебраических уравнений
Для решения систем алгебраических уравнений и одиночных уравнений служит функция solve:
Обратите внимание на то, что для задания уравнений в явном виде используются строковые выражения, для чего уравнения заключаются в апострофы. Уравнения могут решаться и в окне ноутбуков встроенной системы MuPad, при этом задание уравнений и их решения приближены к обычному математическому виду, показанному на рис. 10.
Рис. 10. Примеры решения уравнений в ноутбуке MuPad
Символьные преобразования и операции с выражениями
Функция simplify(S) поэлементно упрощает символьные выражения:
Функция simple(S) выполняет различные упрощения для элементов массива S и выводит как промежуточные результаты, так и самый короткий конечный результат. В другой форме — [R,HOW] = simple(S) — промежуточные результаты не выводятся. Результаты упрощений содержатся в векторе R , а в строковом векторе HOW указывается выполняемое преобразование:
Функция expand(S) расширяет выражения, входящие в массив S . Рациональные выражения она раскладывает на простые дроби, полиномы — на полиномиальные разложения и т. д. Функция работает со многими алгебраическими и тригонометрическими функциями:
Функция factor(S) поэлементно разлагает выражения вектора S на простые множители, а целые числа — на произведение простых чисел:
Функция collect(S,v) обеспечивает комплектование выражений в составе вектора или матрицы S по степеням переменной v . А функция collect(S)выполняет аналогичные действия относительно переменной, определяемой функцией findsym.
Примеры применения этой функции:
Функция [N,D]=numden(A) преобразует каждый элемент массива A в рациональную форму в виде отношения двух неприводимых полиномов с целочисленными коэффициентами. При этом N и D — числители и знаменатели каждого преобразованного элемента массива. Функция horner(P)возвращает символьный полином или массив символьных полиномов P , преобразованный по схеме Горнера, которая минимизирует число операций умножения:
Функция [Y,SIGMA]=subexpr (X,SIGMA) или [Y,SIGMA]=subexpr (X,‘SIGMA’) преобразует символьное выражение X , обеспечивая при этом подстановку SIGMA. Для представления подвыражений используются обозначения %1,%2 и т. д.
Одной из самых эффектных и часто используемых операций символьной математики является операция подстановки. Она реализуется функцией subs, имеющей несколько форм записи.
Часто возникает необходимость в задании функции, обратной по отношению к заданной функции f . Для этого в Symbolic имеется функция обращения inverse(f):
К числу часто встречающихся в символьной математике манипуляций с функциями относится суперпозиция функций, реализуемая функциями compose:
- compose(f,g) — возвращает значение функции 1/(1+sin( y ) 2 );
- compose(f,g,t) — возвращает значение функции 1/(1+sin( t ) 2 );
- compose(h,g,x,z) — возвращает значение функции sin( z ) t ;
- compose(h,g,t,z) — возвращает значение функции x sin( z ) ;
- compose(h,p,x,y,z) — возвращает значение функции exp(– z / u ) t ;
- compose(h,p,t,u,z) — возвращает значение функции x exp(– y / z ) .
В связи с использованием в символьных вычислениях символьных выражений возникает необходимость в преобразовании их в обычные числа с плавающей точкой и обычной двойной точностью. Для этого служит функция double(S) :
Если задан полином, коэффициенты которого хранятся в векторе C , то функция poly2sym(C) преобразует его в символьное представление полинома в стандартной форме записи с независимой переменной x . Другие функции — poly2sym(C,‘V’) и poly2sym(C,SYM(‘V’) — делают то же, но позволяют задать независимую переменную полинома как V .
Если задан символьный полином P , то функция sym2poly(P) возвращает вектор его коэффициентов. Это поясняют следующие примеры:
Функция char(A) преобразует символьный объект A в строку. Если A — вектор или матрица, результат представляется в форме ‘array([[…]]):
Решение дифференциальных уравнений
Для аналитического решения дифференциальных уравнений в форме Коши служит функция dsolve(‘eqn1’,‘eqn2’, …). Она возвращает аналитическое решение системы дифференциальных уравнений с начальными условиями. Они задаются равенствами eqnI (вначале задаются уравнения, затем начальные условия).
По умолчанию независимой переменной считается переменная t , обычно обозначающая время. Можно использовать и другую переменную, добавив ее в конец списка параметров функции dsolve. Символ D обозначает производную по независимой переменной, то есть d / dt , при этом D 2 означает d 2 / dt 2 и т. д. Имя независимой переменной не должно начинаться с буквы D .
Начальные условия задаются в виде равенств y ( a )= b или Dy ( a )= b , где y — независимая переменная, a и b — константы. Если число начальных условий меньше, чем число дифференциальных уравнений, то в решении будут присутствовать произвольные постоянные C 1, C 2 и т. д. Правила вывода подобны приведенным для функции solve.
Примеры применения функции dsolve:
Решения дифференциальных уравнений легко представить в виде графика. Часто такой график строится на фоне векторного поля решения: пример показан на рис. 11. Там же приведен открытый список поддерживаемых типов графики ноутбуков MuPad.
Рис. 11. Примеры решения уравнений (последний пример с построением решения дифференциального уравнения на графике векторного поля)
Заключение
Пакет расширения Symbolic Math на основе системы компьютерной алгебры MuPad открыл перед матричной системой MATLAB всю красоту и все принципиально новые возможности символьных (аналитических) вычислений. Они реализованы как в командном окне MATLAB, так и в ноутбуках MuPad c их графическим интерфейсом пользователя GUI. В новейшей реализации MATLAB 8.0 (R2012b) появился вызов MuPad из каталога пакетов расширения. Панели для ввода мышью основных операторов и функций символьной математики, а также средства графической визуализации вычислений делают их проведение простым и удобным.
Symbolic math toolbox matlab как установить
Давайте рассмотрим добавление набора инструментов 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.
- 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.
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.
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 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 plot
Example 2
Let’s look at another example:
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 .
Plot for the range -pi to pi
Plot for the range -2pi to 2pi
Plot for the range -4pi to 4pi
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
Цель работы:изучить систему команд расширения 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 – в прямой ветви, и звена – в обратной связи, при условии отрицательной обратной связи.
How to open symbolic math toolbox in matlab
There are several considerations in using symbolic calculations with optimization functions: Optimization objective and constraint functions should be defined in terms of a vector, say . Now we calculate the Hessians of the two constraint functions, and make function handle versions with .
How to install and enable Symbolic Math Toolbox
Solution 1:
Solution 2:
'Symbolic Math Toolbox' functions exist in MATLAB but not in the documentation
Solution:
It could be a license issue. Try to get further information with:
If you have a Student version, some functions cannot be executed.
In case that you are in an office/university, and you have floating licenses. Be sure to check-out all the licenses before running your code.
Using Symbolic Mathematics with Optimization Toolbox Solvers
This example shows how to use the Symbolic Math Toolbox™ functions jacobian and matlabFunction to provide analytical derivatives to optimization solvers. Optimization Toolbox™ solvers are usually more accurate and efficient when you supply gradients and Hessians of the objective and constraint functions.
Problem-based optimization can calculate and use gradients automatically; see Automatic Differentiation in Optimization Toolbox. For a problem-based example using automatic differentiation, see Constrained Electrostatic Nonlinear Optimization, Problem-Based.
There are several considerations in using symbolic calculations with optimization functions:
Optimization objective and constraint functions should be defined in terms of a vector, say x . However, symbolic variables are scalar or complex-valued, not vector-valued. This requires you to translate between vectors and scalars.
Optimization gradients, and sometimes Hessians, are supposed to be calculated within the body of the objective or constraint functions. This means that a symbolic gradient or Hessian has to be placed in the appropriate place in the objective or constraint function file or function handle.
Calculating gradients and Hessians symbolically can be time-consuming. Therefore you should perform this calculation only once, and generate code, via matlabFunction , to call during execution of the solver.
Evaluating symbolic expressions with the subs function is time-consuming. It is much more efficient to use matlabFunction .
matlabFunction generates code that depends on the orientation of input vectors. Since fmincon calls the objective function with column vectors, you must be careful to call matlabFunction with column vectors of symbolic variables.
First Example: Unconstrained Minimization with Hessian
The objective function to minimize is:
f ( x 1 , x 2 ) = log ( 1 + 3 ( x 2 — ( x 1 3 — x 1 ) ) 2 + ( x 1 — 4 / 3 ) 2 ) .
This function is positive, with a unique minimum value of zero attained at x1 = 4/3, x2 =(4/3)^3 — 4/3 = 1.0370.
We write the independent variables as x1 and x2 because in this form they can be used as symbolic variables. As components of a vector x they would be written x(1) and x(2) . The function has a twisty valley as depicted in the plot below.
How to Install the Symbolic Math Toolbox to Use with MATLAB
Once you have obtained a copy of the Symbolic Math Toolbox to use with MATLAB, you should have a number of files on your hard drive. These files provide everything needed to install the Symbolic Math Toolbox. You have two ways by which you can interact with the files:
If you were able to use the download agent, you see a dialog box telling you that the download is complete. At this point, you can perform one of these two tasks:
Select the Start Installer option and click Finish to start the installation process. The Symbolic Math Toolbox installer will start automatically.
Select the Open Location of the Downloaded Files option and click Finish. You see the location of the files open, and you must double-click the installer file to start the installation process. (The installer file is typically the only executable program in the folder.)
If you performed the manual download process, you need to find the download location of the files. You must double-click the installer file to start the installation process. (The installer file is typically the only executable program in the folder.)
Windows platform users may see a User Account Control (UAC) dialog box when starting the installer. Click Yes to give the installer permission to install the Symbolic Math Toolbox. Otherwise, the installation will fail.
No matter how you start the installer, eventually you see a MathWorks installer dialog box. This dialog box determines the source of the files that you use to perform the installation. (Choosing the Install Using the Internet option downloads the files directly from the MathWorks site — you also have the option of using source files on your hard drive.) The following steps help you complete the installation process.
Select an installation source (either Internet or local hard drive) and click Next.
You see the License Agreement dialog box.
Read the licensing agreement, click Yes, and then click Next.
You see the File Installation Key dialog box. This is where you supply the licensing information. If you don’t have the key, make sure that you select the second option and follow the steps required to obtain the license.
Supply the File Installation Key and click Next.
The installer asks you to select an installation method. In most cases, you obtain a better, faster, more error-free installation by selecting the Typical option. The steps that follow assume that you have chosen the Typical option.
Click the Typical option and then click Next.
The installer asks you to choose an installation destination. This destination differs by platform. In most cases, choosing the default installation destination is the best idea. However, if you have an existing installation and want to preserve this installation precisely as it is, you need to choose a different installation location.
Choose a destination location, if necessary, and click Next.
If you already have a copy of MATLAB installed and you choose the default installation location, the installer will ask whether you want to overwrite the existing copy. Click Yes To All (if you need to update your copy of MATLAB) or No (when you have the most current version) to proceed.
When you click Yes To All, you agree to allow the installer to remove your old copy of MATLAB and install a new one. Be aware that you’ll likely lose any special configuration options you have set up, along with any features you had installed previously.
The installer displays a Confirmation dialog box. Check the details carefully to ensure that the installation provides everything you need.
Click Install.
The installation process begins. You can watch the progress by checking the progress bar. The installation can require several minutes depending on the installation options you choose, the complexity of the installation, and the speed of your system.
When the installation process is complete, you see an Installation Complete dialog box.
Select the Activate MATLAB option and then click Next.
MATLAB asks whether you want to activate your copy using the Internet or manually. Using the Internet is generally the faster and easier option, unless you have already downloaded a license file ( license.lic ) as part of getting the file installation key.
Choose an activation option and click Next.
When you choose the Internet option, you must provide your email address and password to log on to the system for activation purposes. If you don’t have an account, you can also choose to create an account or provide the location of your locally stored license.lic file.
Supply any required input and click Next.
If activation is successful, you see an Activation Complete dialog box. (When you don’t see this dialog box, retry obtaining the required activation or contact MathWorks support.)
Symbolic math toolbox matlab как установить
How to Install the Symbolic Math Toolbox to Use with MATLAB
Once you have obtained a copy of the Symbolic Math Toolbox to use with MATLAB, you should have a number of files on your hard drive. These files provide everything needed to install the Symbolic Math Toolbox. You have two ways by which you can interact with the files:
If you were able to use the download agent, you see a dialog box telling you that the download is complete. At this point, you can perform one of these two tasks:
Select the Start Installer option and click Finish to start the installation process. The Symbolic Math Toolbox installer will start automatically.
Select the Open Location of the Downloaded Files option and click Finish. You see the location of the files open, and you must double-click the installer file to start the installation process. (The installer file is typically the only executable program in the folder.)
If you performed the manual download process, you need to find the download location of the files. You must double-click the installer file to start the installation process. (The installer file is typically the only executable program in the folder.)
Windows platform users may see a User Account Control (UAC) dialog box when starting the installer. Click Yes to give the installer permission to install the Symbolic Math Toolbox. Otherwise, the installation will fail.
No matter how you start the installer, eventually you see a MathWorks installer dialog box. This dialog box determines the source of the files that you use to perform the installation. (Choosing the Install Using the Internet option downloads the files directly from the MathWorks site — you also have the option of using source files on your hard drive.) The following steps help you complete the installation process.
Select an installation source (either Internet or local hard drive) and click Next.
You see the License Agreement dialog box.
Read the licensing agreement, click Yes, and then click Next.
You see the File Installation Key dialog box. This is where you supply the licensing information. If you don’t have the key, make sure that you select the second option and follow the steps required to obtain the license.
Supply the File Installation Key and click Next.
The installer asks you to select an installation method. In most cases, you obtain a better, faster, more error-free installation by selecting the Typical option. The steps that follow assume that you have chosen the Typical option.
Click the Typical option and then click Next.
The installer asks you to choose an installation destination. This destination differs by platform. In most cases, choosing the default installation destination is the best idea. However, if you have an existing installation and want to preserve this installation precisely as it is, you need to choose a different installation location.
Choose a destination location, if necessary, and click Next.
If you already have a copy of MATLAB installed and you choose the default installation location, the installer will ask whether you want to overwrite the existing copy. Click Yes To All (if you need to update your copy of MATLAB) or No (when you have the most current version) to proceed.
When you click Yes To All, you agree to allow the installer to remove your old copy of MATLAB and install a new one. Be aware that you’ll likely lose any special configuration options you have set up, along with any features you had installed previously.
The installer displays a Confirmation dialog box. Check the details carefully to ensure that the installation provides everything you need.
Click Install.
The installation process begins. You can watch the progress by checking the progress bar. The installation can require several minutes depending on the installation options you choose, the complexity of the installation, and the speed of your system.
When the installation process is complete, you see an Installation Complete dialog box.
Select the Activate MATLAB option and then click Next.
MATLAB asks whether you want to activate your copy using the Internet or manually. Using the Internet is generally the faster and easier option, unless you have already downloaded a license file ( license.lic ) as part of getting the file installation key.
Choose an activation option and click Next.
When you choose the Internet option, you must provide your email address and password to log on to the system for activation purposes. If you don’t have an account, you can also choose to create an account or provide the location of your locally stored license.lic file.
Supply any required input and click Next.
If activation is successful, you see an Activation Complete dialog box. (When you don’t see this dialog box, retry obtaining the required activation or contact MathWorks support.)
Multiprecision Computing Toolbox User’s Manual
The Multiprecision Computing Toolbox is easily installed after following only a few brief steps.
Windows. After downloading the program allow it to run. Follow the step-by-step instructions of the installer to complete the installation process.
GNU Linux and Mac OSX. Installation instructions are provided upon trial version request for the platforms.
After installation we recommend completing the following steps:
-
Add the destination folder where toolbox is installed to MATLAB’s search path. For Windows 7, this may look like the following:
Quick Start
Arbitrary precision numbers and matrices can be created with the new special function mp() , which stands for multiprecision:
The argument to the constructor mp() can be a string with mathematical expression or usual MATLAB’s matrix of any numeric type ( double, single, logical, int8, int16, int32, int64 or else). Complex numbers, n-dimensional arrays and sparse matrices are supported as well.
Constructor creates objects with default precision controlled by mp.Digits() routine. On toolbox startup default precision is assigned to 34 decimal digits which conforms to IEEE 174-2008 standard for quadruple precision.
Toolbox is capable of working with any level of precision – hardware configuration is the only limiting factor:
Once are created, the new multiprecision numbers and matrices can be used in programs the same way as ordinary double precision objects:
These examples show a basic principle of the MATLAB program porting to the computing with toolbox. In most cases, this is accomplished by substituting standard numeric objects with the analogous multiprecision entities. The rest of the code stays intact – computations are now completed using requested level of precision transparently to user.
Information on toolbox-specific routines can be obtained by the MATLAB help command: help mp.Digits, help mp.GaussLegendre , etc.)
The toolbox provides extended-precision equivalents to the majority of the commonly used MATLAB routines.
Every function in toolbox is implemented in multiple different modifications in order to support all special cases and features of MATLAB’s standard routines. For example, arbitrary precision eig(), svd(), ifft() and bicgstab() functions cover all of the following special cases:
All options are supported:
[___] = eig(A,balanceOption)
[___] = eig(A,B,algorithm)
[___] = eig(___,eigvalOption)
BiCGSTAB iterative solver for large/sparse matrices:
x = bicgstab(A,b)
bicgstab(A,b,tol)
bicgstab(A,b,tol,maxit)
bicgstab(A,b,tol,maxit,M)
bicgstab(A,b,tol,maxit,M1,M2)
bicgstab(A,b,tol,maxit,M1,M2,x0)
[x,flag] = bicgstab(A,b. )
[x,flag,relres] = bicgstab(A,b. )
[x,flag,relres,iter] = bicgstab(A,b. )
[x,flag,relres,iter,resvec] = bicgstab(A,b. )
Please refer to Function Reference page for a complete list of supported functions. All of them are capable of computing with arbitrary level of precision and support special cases and options of MATLAB.
Be aware that in some cases this may affect accuracy of the final result of computations:
Generally, floating-point numbers should be re-calculated using high precision arithmetic from the onset, not converted from MATLAB as the accuracy is inherited. Please see More on Existing Code Porting for examples and more details.
In examples on the page we frequently use direct conversion of double matrices to mp-type. This is just for making demonstrations brief and simple, as it is not part of physical simulations or other meaningful computations. Please be careful in real-world applications.
More Examples
In this section we show several examples of toolbox usage in different fields. This reflects just the tiny portion of toolbox functionality, but we hope it will be helpful for understanding on how to apply toolbox in other situations.
Arbitrary Precision Gauss-Legendre Quadrature
Our first example illustrates one particular case of existing code porting to computing with extended precision.
The Gauss-Legendre quadrature’s nodes and weights can be calculated from the eigenvalues and eigenvectors of a Jacobi matrix, built from the coefficients of a 3-term recurrence relation of orthogonal Legendre polynomials. MATLAB code for the algorithm:
Toolbox enables this program to calculate abscissae and weights with arbitrary precision, without any modifications to code:
How is this possible? During the program’s every function call, MATLAB detects the type of supplied arguments. Built-in functions are called for the numeric objects of standard double type. However, if an argument is a multiprecision number or matrix, MATLAB recognizes this and uses the functions provided by Multiprecision Computing Toolbox.
Thus, when we pass mp-number mp(N) to gauss() , MATLAB uses the high precision routines from the toolbox for all further mathematical operations: +, -, *, ./, colon(:), .^, diag(), eig() and sort() .
It is important to note that MATLAB does a silent conversion of the floating-point constant 0.5 using the mp() constructor. Since 0.5 is a power of 2 , it is exactly representable in binary format using the standard double type. As a result, direct conversion to extended precision is safe – no rounding error is introduced in a process. All other non-power-of-two constants should be re-computed in higher precision by the toolbox (e.g. 1/3 => mp(‘1/3’) ).
Linear Algebra (Dense matrices)
All linear algebra routines in toolbox are implemented in native C++/Assembler programming languages with heavy optimization for parallel execution on multi-core CPUs. We implement only state-of-the-art algorithms, as soon as they appear in LAPACK or published in papers.
Every routine (e.g. det , svd , eig , etc.) is a meta-algorithm which analyses the properties of the input matrix and applies the best suitable method for it.
Thus, for example, eigensolver uses multi-shift QR with aggressive deflation for unsymmetric matrices, MRRR or D&C for symmetric and tridiagonal matrices. The system solver \ handles much more additional cases, including positive definite, banded and triangular matrices.
Solve system of equations
Although ill-conditioning has eaten up 15 digits of accuracy, extended precision is able to provide meaningful solution anyway.
Compute sensitive eigenvalues
The eigenvalues of the matrix (we call it “Circus matrix”) are invariant to transposition, so that eig(A)==eig(A.’) . We verify this property below using the double and quadruple precision:
The eigenvalues of the original matrix are displayed in black, and the eigenvalues of the transposed – in red. They should coincide:
Similar examples can be found on the page Computing Eigenvalues in Extended Precision.
Besides the main routine eig , toolbox provides less common functions related to eigenproblems: condeig, schur, ordeig, ordqz, ordschur, poly, polyeig, qz, hess, balance, cdf2rdf and rsf2csf .
Compute subset of eigenvalues and eigenvectors
Toolbox implements EIGS routine for computing part of the eigenspectrum:
It is based on Krylov-Schur iterative method with the support of usual features: standard and generalized eigenproblems, matrix and function handle inputs and various parts of the spectrum – ‘SM’, ‘LM’, ‘SA’, ‘LA’, ‘SI’, ‘LI’, ‘SR’ and ‘LR’ .
In case of handle inputs, routine MPEIGS should be called:
Matrix functions
Evaluation of matrix functions is closely related to Schur decomposition and eigenproblem in general. Naturally extended precision plays important role in the field as well. Toolbox provides all common routines – expm, sqrtm, logm, sinm, cosm, sinhm, coshm and funm for computing arbitrary matrix functions.
Maximum relative error over 10 tests when run with double precision:
Correct result can be obtained by using the quadruple precision:
Linear Algebra (Sparse matrices)
Creation and manipulation
Similarly to dense case, multiprecision sparse matrices can be created in several ways.
Or directly by using the special functions:
Toolbox provides the basic functionality for working with sparse matrices: element-wise access, indexing & assignment, concatenation and basic functions ( nonzeros, spfun, spones, min/max, find, nnz, etc.). Arithmetic operations also support mixed type arguments (full-sparse) and compatible with MATLAB’s semantic (type of result, etc).
Direct solvers
System solver in toolbox ( mldivide or \ ) relies on direct decompositions – SuperLU , Cholesky and sparse QR , depending on problem to be solved. All of them are implemented in C++ and capable of working with arbitrary precision.
The mmread routine is needed to read MatrixMarket matrices and it is provided here.
Timing examples for solving the test matrices from MatrixMarket and test scripts can be found on the pages: Direct Solvers for Sparse Matrices or Advanpix vs. Maple – Direct Sparse Solvers Comparison.
Iterative solvers
Toolbox includes following full-featured iterative solvers: BiCG, BiCGSTAB, BiCGSTABL, CGS, GMRES, MINRES and PCG .
All methods are capable of working with arbitrary precision sparse and dense matrices. Routines are implemented in different variants, support preconditionares, matrix and function handles as inputs. Please use them in your code, see Krylov Subspace Methods in Arbitrary Precision and Arbitrary Precision Iterative Solver – GMRES for more details.
But here we consider simple self-written conjugate gradient for illustrative purposes.
Let’s consider conjugate gradient iterative method and check how its convergence speed changes with precision. Here is very simple implementation (without preconditioning or else):
Ideally CG should produce exact solution in a number of steps no large than the size of the matrix. In a world of double precision floating-point arithmetic this obviously doesn’t work:
The method needs 15.6 times more iterations to reach the 1e-10 accuracy in double precision than theory dictates! Exactly the same routine can be used to solve the problem using quadruple precision:
Two times less iterations needed, but still too many. Toolbox allows computing with any level of precision, e.g. let’s try 650 digits:
Finally practice coincides with theory – method converged in 237 iterations = matrix size. Worth to note that high precision might actually give boost in performance, since much less number of iterations is required:
Iterations required to reach 1e-10 accuracy versus precision used in solver (CG, NOS1.mtx)
Numerical methods
Solve system of nonlinear equations (fsolve)
Toolbox provides full-featured fsolve , including sparse formulation, Jacobian and three algorithms of optimization: Levenberg-Marquardt , trust-region-dogleg and trust-region-reflective . All options and special cases are covered:
x = fsolve(fun,x0)
x = fsolve(fun,x0,options)
x = fsolve(problem)
[x,fval] = fsolve(fun,x0)
[x,fval,exitflag] = fsolve(. )
[x,fval,exitflag,output] = fsolve(. )
[x,fval,exitflag,output,jacobian] = fsolve(. )
Quick start example for demonstration:
Find function zeros
Find zeros of nonlinear function using fzero . Try double precision first:
Here is plot of the function produced by MATLAB in double precision:
Do the same but with 50-digits of precision:
MATLAB is not able to overcome the cancellation errors in computing function zeros, whereas elevated precision does provide the correct results.
Numerical integration
Numerical integration using the adaptive Gauss-Kronrod quadrature:
The quadgk routine provided in toolbox computes Gauss-Kronrod coefficients for the requested precision and then runs adaptive integration algorithm.
If you are interested in more details on how to compute the coefficients in arbitrary precision please take a look on the page: Gauss-Kronrod Quadrature Nodes and Weights.
Ordinary differential equations
Solve nonstiff differential equations using ode113 (toolbox also provides ode45 and ode15s ):
Symbolic Math Toolbox (VPA) vs. Multiprecision Computing Toolbox
Even in basic operations like elementary functions:
Or in trivial array manipulation (e.g. vertical concatenation):
VPA gives plainly wrong results in some cases:
Even for basic special functions:
Moreover MATLAB has serious issues with accurate computation of special functions even in double precision.
In case of Bessel functions of the first and second kind Yn(x) and Jn(x) – MATLAB suffers from catastrophic accuracy loss near zeros of the functions. Red lines show the expected limits of relative error for double precision:
MATLAB’s functions bessely(n,x) and besselj(n,x) give no single correct digit in neighborhood of zeros of Yn(x) and Jn(x) .
In case of modified Bessel functions MATLAB provides non-uniform accuracy (depending on argument range) and actually gives the highest error among mathematical libraries. For example, relative accuracy in terms of machine epsilon for might reach the 11.5eps near
:
Please refer to the reports: K0(x) , K1(x) , I0(x) and I1(x) for more details on modified functions.
Built-in Hankel functions in MATLAB suffers from accuracy loss as well:
Same for gamma (and many other functions) in MATLAB:
To be fair, accuracy loss is endemic issue of numerical libraries, commercial or open source. For example, relative accuracy plots for I1(x) of NAG libraries:
NAG demonstrates serious accuracy degradation for :
Actually relative error can be as high as 257eps .
Last but not the least issue with Symbolic Math Toolbox is that it doesn’t follow semantic of MATLAB’s standard functions. For example, it has no support for n-dimensional arrays in basic functions like max, min, sum, mean, etc.:
More on Existing Code Porting
Smooth transition (ideally without modifications) of existing code to arbitrary precision is the main goal of the Multiprecision Computing Toolbox. However, there is an important case to be aware of.
Floating-point numerical constants in the code, such as 1/3, pi, sin(pi/3), sqrt(2)/2, eps, realmin, realmax , should be calculated using multiprecision arithmetic – mp(‘1/3’), mp(‘pi’), mp(‘sin(pi/3)’), mp(‘sqrt(2)/2’), mp(‘eps’), eps(‘mp’), realmin(‘mp’), realmax(‘mp’) . Otherwise, MATLAB will evaluate these numbers with its standard precision first, and this might affect the overall accuracy of computations as well as final result.
Be aware that in some cases this may affect accuracy of the final result of computations:
Extra-care should be taken to the stopping criteria of various iterative algorithms. Most likely it should be changed to allow more iterations and use machine epsilon matching to precision used.
Following function is from Chebfun, it is one of the many used in computing nodes & weights of Gauss-Laguerre quadrature:
Assuming that input parameter xs is passed as mp-number, the routine will run in multiprecision mode. But still we need to do few changes to the code (changed lines are highlighted):
Now stopping criteria is capable of working with arbitrary precision (maximum number of iterations is an open question, probably it needs to be found empirically for every level of precision or omitted altogether).
Please check the article How to write precision independent code in MATLAB for more ideas on the process.
Symbolic Math Toolbox
Symbolic Math Toolbox™ provides functions for solving, plotting, and manipulating symbolic math equations. You can create, run, and share symbolic math code. In the MATLAB ® Live Editor, you can get next-step suggestions for symbolic workflows. The toolbox provides functions in common mathematical areas such as calculus, linear algebra, algebraic and differential equations, equation simplification, and equation manipulation.
Symbolic Math Toolbox lets you analytically perform differentiation, integration, simplification, transforms, and equation solving. You can perform dimensional computations and convert between units. Your computations can be performed either analytically or using variable-precision arithmetic, with the results displayed in mathematical typeset.
You can share your symbolic work with other MATLAB users as live scripts or convert them to HTML, Word, LaTeX, or PDF documents. You can generate MATLAB functions, Simulink ® function blocks, and Simscape™ equations directly from symbolic expressions.