Как найти корни уравнения matlab

Содержание
  1. Решение нелинейных уравнений в Matlab
  2. Общая информация
  3. Стандартные функции Matlab
  4. Метод перебора Matlab
  5. Метод простых итераций Matlab
  6. Метод половинного деления Matlab
  7. Заключение
  8. MATLAB — алгебра
  9. Решение основных алгебраических уравнений в MATLAB
  10. Решение основных алгебраических уравнений в октаве
  11. Решение квадратичных уравнений в MATLAB
  12. Решение квадратичных уравнений в октаве
  13. Решение уравнений высшего порядка в MATLAB
  14. Решение уравнений высшего порядка в октаве
  15. Решение системы уравнений в MATLAB
  16. Решающая система уравнений в октаве
  17. Разложение и сбор уравнений в MATLAB
  18. Расширяя и собирая уравнения в октаве
  19. Факторизация и упрощение алгебраических выражений
  20. пример
  21. solve
  22. Syntax
  23. Description
  24. Examples
  25. Solve Quadratic Equation
  26. Solve Polynomial and Return Real Solutions
  27. Numerically Solve Equations
  28. Solve Multivariate Equations and Assign Outputs to Structure
  29. Solve Inequalities
  30. Solve Multivariate Equations and Assign Outputs to Variables
  31. Use Parameters and Conditions to Refine Solution
  32. Shorten Result with Simplification Rules
  33. Ignore Assumptions on Variables
  34. Solve Polynomial Equations of High Degree
  35. Return One Solution
  36. Input Arguments
  37. eqn — Equation to solve symbolic expression | symbolic equation
  38. var — Variable for which you solve equation symbolic variable
  39. eqns — System of equations symbolic expressions | symbolic equations
  40. vars — Variables for which you solve an equation or system of equations symbolic vector | symbolic matrix
  41. Name-Value Arguments
  42. Real — Flag for returning only real solutions false (default) | true
  43. ReturnConditions — Flag for returning parameters and conditions false (default) | true
  44. IgnoreAnalyticConstraints — Simplification rules applied to expressions and equations false (default) | true
  45. IgnoreProperties — Flag for returning solutions inconsistent with properties of variables false (default) | true
  46. MaxDegree — Maximum degree of polynomial equations for which solver uses explicit formulas 2 (default) | positive integer smaller than 5
  47. PrincipalValue — Flag for returning one solution false (default) | true
  48. Output Arguments
  49. S — Solutions of equation symbolic array
  50. Y — Solutions of system of equations structure
  51. y1. yN — Solutions of system of equations symbolic variables
  52. parameters — Parameters in solution vector of generated parameters
  53. conditions — Conditions under which solutions are valid vector of symbolic expressions
  54. Algorithms

Видео:1 - Решение систем нелинейных уравнений в MatlabСкачать

1 - Решение систем нелинейных уравнений в Matlab

Решение нелинейных уравнений в Matlab

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

Общая информация

Уравнения, которые содержат переменные, находящиеся в степенях, отличающихся от единицы, или имеющие нелинейные математические выражения (корень, экспонента, логарифм, синус, косинус и т.д.), а также имеющие вид f(x) = 0 называются нелинейными. В зависимости от сложности такого уравнения применяют методы для решения нелинейных уравнений.

В этой статье, помимо стандартных функций Matlab, мы рассмотрим следующие методы:

  • Метод перебора
  • Метод простых итераций
  • Метод половинного деления

Рассмотрим коротко их алгоритмы и применим для решения конкретной задачи.

Стандартные функции Matlab

Для решения нелинейных уравнений в Matlab есть функция fzero. Она принимает в качестве аргументов саму функцию, которую решаем, и отрезок, на котором происходит поиск корней нелинейного уравнения.

И сразу же разберем пример:

Решить нелинейное уравнение x = exp(-x), предварительно определив интервалы, на которых существуют решения уравнения.

Итак, для начала следует привести уравнение к нужному виду: x — exp(-x) = 0 , а затем определить интервалы, в которых будем искать решение уравнения. Методов для определения интервалов множество, но так как пример достаточно прост мы воспользуемся графическим методом.

Здесь задали примерные границы по оси x, чтобы можно было построить график и посмотреть как ведет себя функция. Вот график:
Как найти корни уравнения matlab
Из графика видно, что на отрезке [0;1] есть корень уравнения (там, где y = 0), соответственно в дальнейшем будем использовать этот интервал. Чем точнее выбран интервал, тем быстрее метод придет к решению уравнения, а для сложных уравнений правильный выбор интервала определяет погрешность, с которой будет получен ответ.

С помощью стандартной функции Matlab находим корень нелинейного уравнения и выводим. Теперь для проверки отобразим все это графически:

Как найти корни уравнения matlab

Как вы видите, все достаточно точно просчиталось. Теперь мы исследуем эту же функцию с помощью других методов и сравним полученные результаты.

Метод перебора Matlab

Самый простой метод, который заключается в том, что сначала задается какое то приближение x (желательно слева от предполагаемого корня) и значение шага h. Затем, пока выполняется условие f(x) * f(x + h) > 0, значение x увеличивается на значение шага x = x + h. Как только условие перестало выполняться — это значит, что решение нелинейного уравнения находится на интервале [x; x + h].

Теперь реализуем метод перебора в Matlab:

Лучше всего создать новый m-файл, в котором и прописать код. После вызова получаем такой вывод:

Функцию объявляем с помощью очень полезной команды inline, в цикле пока выполняется условие отсутствия корней (или их четного количества), прибавляем к x значение шага. Очевидно, что чем точнее начальное приближение, тем меньше итераций необходимо затратить.

Метод простых итераций Matlab

Этот метод заключается в том, что функцию преобразуют к виду: x = g(x). Эти преобразования можно сделать разными способами, в зависимости от вида начальной функции. Помимо этого следует задать интервал, в котором и будет производиться итерационный процесс, а также начальное приближение. Сам процесс строится по схеме xn= g(xn-1). То есть итерационно проходим от предыдущего значения к последующему.

Процесс заканчивается как только выполнится условие: Как найти корни уравнения matlab, то есть, как только будет достигнута заданная точность. И сразу же разберем реализацию метода простых итераций в Matlab для примера, который был приведен выше.

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

А вот и вывод программы:

Очевидно, что метод простых итераций работает гораздо быстрее и получает точное решение.

Метод половинного деления Matlab

Метод достаточно прост: существует отрезок поиска решения [a;b], сначала находят значение функции в точке середины c, где c = (a+b)/2. Затем сравнивают знаки f(a) и f(c). Если знаки разные — то решение находится на отрезке [a;c], если нет — то решение находится на отрезке [c;b]. Таким образом мы сократили область в 2 раза. Такое сокращение происходит и дальше, пока не достигнем заданной точности.

Перейдем к реализации метода в Matlab:

Все самое важное происходит в цикле: последовательно сокращаем область нахождения решения, пока не будет достигнута заданная точность.
Вот что получилось в выводе:

Этот метод хорошо работает, когда правильно определен интервал, на котором находится решение. Тем не менее, метод простых итераций считается наиболее точным и быстрым.

Заключение

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

На этом все — спасибо за внимание. В следующей статье мы разберем решение систем нелинейных уравнений в matlab.

Видео:Решение произвольных уравнений. Методы вычислений в MATLAB. Часть 1. Урок 61Скачать

Решение произвольных уравнений. Методы вычислений в MATLAB. Часть 1. Урок 61

MATLAB — алгебра

До сих пор мы видели, что все примеры работают как в MATLAB, так и в его GNU, альтернативно называемом Octave. Но для решения основных алгебраических уравнений и MATLAB, и Octave немного отличаются, поэтому мы постараемся охватить MATLAB и Octave в отдельных разделах.

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

Видео:MatLab. 6.1. Решение уравненийСкачать

MatLab. 6.1. Решение уравнений

Решение основных алгебраических уравнений в MATLAB

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

Например, давайте решим для х в уравнении х-5 = 0

MATLAB выполнит приведенный выше оператор и вернет следующий результат —

Вы также можете вызвать функцию решения как —

MATLAB выполнит приведенный выше оператор и вернет следующий результат —

Вы можете даже не включать правую часть уравнения —

MATLAB выполнит приведенный выше оператор и вернет следующий результат —

Если в уравнение входит несколько символов, то по умолчанию MATLAB предполагает, что вы решаете для x, однако функция решения имеет другую форму —

где вы также можете упомянуть переменную.

Например, давайте решим уравнение v — u — 3t 2 = 0, для v. В этом случае мы должны написать —

MATLAB выполнит приведенный выше оператор и вернет следующий результат —

Видео:Числовое решение. Функция root в MathCAD 14 (28/34)Скачать

Числовое решение. Функция root в MathCAD 14 (28/34)

Решение основных алгебраических уравнений в октаве

Функция корней используется для решения алгебраических уравнений в Octave, и вы можете написать приведенные выше примеры следующим образом:

Например, давайте решим для х в уравнении х-5 = 0

Octave выполнит приведенный выше оператор и вернет следующий результат —

Вы также можете вызвать функцию решения как —

Octave выполнит приведенный выше оператор и вернет следующий результат —

Видео:Численное решение системы дифференциальных уравнений(задачи Коши)Скачать

Численное решение системы дифференциальных уравнений(задачи Коши)

Решение квадратичных уравнений в MATLAB

Функция решения также может решать уравнения более высокого порядка. Он часто используется для решения квадратных уравнений. Функция возвращает корни уравнения в массиве.

В следующем примере решается квадратное уравнение x 2 -7x +12 = 0. Создайте файл сценария и введите следующий код —

Когда вы запускаете файл, он показывает следующий результат —

Видео:2 - Решениt систем линейных алгебраических уравнений (СЛАУ) с помощью Matlab.Скачать

2 - Решениt систем линейных алгебраических уравнений (СЛАУ) с помощью Matlab.

Решение квадратичных уравнений в октаве

В следующем примере решается квадратное уравнение x 2 -7x +12 = 0 в октаве. Создайте файл сценария и введите следующий код —

Когда вы запускаете файл, он показывает следующий результат —

Видео:Математика это не ИсламСкачать

Математика это не Ислам

Решение уравнений высшего порядка в MATLAB

Функция решения также может решать уравнения более высокого порядка. Например, давайте решим кубическое уравнение как (x-3) 2 (x-7) = 0

MATLAB выполнит приведенный выше оператор и вернет следующий результат —

В случае уравнений более высокого порядка корни длинные, содержащие много членов. Вы можете получить числовое значение таких корней, преобразовав их в двойные. В следующем примере решается уравнение четвертого порядка x 4 — 7x 3 + 3x 2 — 5x + 9 = 0.

Создайте файл сценария и введите следующий код —

Когда вы запускаете файл, он возвращает следующий результат —

Обратите внимание, что последние два корня являются комплексными числами.

Видео:Метод Ньютона (метод касательных) Пример РешенияСкачать

Метод Ньютона (метод касательных) Пример Решения

Решение уравнений высшего порядка в октаве

В следующем примере решается уравнение четвертого порядка x 4 — 7x 3 + 3x 2 — 5x + 9 = 0.

Создайте файл сценария и введите следующий код —

Когда вы запускаете файл, он возвращает следующий результат —

Видео:Как в MATLAB Simulink моделировать уравнения (Структурная схема САУ)Скачать

Как в MATLAB Simulink моделировать уравнения (Структурная схема САУ)

Решение системы уравнений в MATLAB

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

Давайте решим уравнения —

Создайте файл сценария и введите следующий код —

Когда вы запускаете файл, он показывает следующий результат —

Таким же образом вы можете решать большие линейные системы. Рассмотрим следующую систему уравнений —

Видео:MatLab. 9.5f. Функция решения алгебраических уравнений – solveСкачать

MatLab. 9.5f. Функция решения алгебраических уравнений – solve

Решающая система уравнений в октаве

У нас есть немного другой подход к решению системы ‘n’ линейных уравнений с ‘n’ неизвестными. Давайте рассмотрим простой пример, чтобы продемонстрировать это использование.

Давайте решим уравнения —

Такая система линейных уравнений может быть записана в виде единого матричного уравнения Ax = b, где A — матрица коэффициентов, b — вектор столбцов, содержащий правую часть линейных уравнений, а x — вектор столбцов, представляющий решение как показано в программе ниже —

Создайте файл сценария и введите следующий код —

Когда вы запускаете файл, он показывает следующий результат —

Таким же образом, вы можете решить большие линейные системы, как указано ниже —

Видео:MatLab. 6.2. Вычисление всех корней полиномаСкачать

MatLab. 6.2. Вычисление всех корней полинома

Разложение и сбор уравнений в MATLAB

Функция расширения и сбора расширяет и собирает уравнение соответственно. Следующий пример демонстрирует понятия —

Когда вы работаете со многими символическими функциями, вы должны объявить, что ваши переменные являются символическими.

Создайте файл сценария и введите следующий код —

Когда вы запускаете файл, он показывает следующий результат —

Видео:MatLab для новичков. Решаем case с квадратным уравнением.Скачать

MatLab для новичков. Решаем case с квадратным уравнением.

Расширяя и собирая уравнения в октаве

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

Когда вы работаете со многими символическими функциями, вы должны объявить, что ваши переменные являются символическими, но у Octave другой подход к определению символических переменных. Обратите внимание на использование Sin и Cos , которые также определены в символической упаковке.

Создайте файл сценария и введите следующий код —

Когда вы запускаете файл, он показывает следующий результат —

Видео:Решение систем Д/У: 1. Знакомство с функциями odeXYСкачать

Решение систем Д/У: 1. Знакомство с функциями odeXY

Факторизация и упрощение алгебраических выражений

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

пример

Создайте файл сценария и введите следующий код —

Когда вы запускаете файл, он показывает следующий результат —

Видео:Линейные уравнения matlabСкачать

Линейные уравнения matlab

solve

Equations and systems solver

Support for character vector or string inputs has been removed. Instead, use syms to declare variables and replace inputs such as solve(‘2*x == 1′,’x’) with solve(2*x == 1,x) .

Видео:Символьные и численные расчеты в MATLABСкачать

Символьные и численные расчеты в MATLAB

Syntax

Видео:MatLab. Решение дифференциального уравнения.Скачать

MatLab. Решение дифференциального уравнения.

Description

S = solve( eqn , var ) solves the equation eqn for the variable var . If you do not specify var , the symvar function determines the variable to solve for. For example, solve(x + 1 == 2, x) solves the equation x + 1 = 2 for x.

S = solve( eqn , var , Name,Value ) uses additional options specified by one or more Name,Value pair arguments.

Y = solve( eqns , vars ) solves the system of equations eqns for the variables vars and returns a structure that contains the solutions. If you do not specify vars , solve uses symvar to find the variables to solve for. In this case, the number of variables that symvar finds is equal to the number of equations eqns .

Y = solve( eqns , vars , Name,Value ) uses additional options specified by one or more Name,Value pair arguments.

[ y1. yN ] = solve( eqns , vars ) solves the system of equations eqns for the variables vars . The solutions are assigned to the variables y1. yN . If you do not specify the variables, solve uses symvar to find the variables to solve for. In this case, the number of variables that symvar finds is equal to the number of output arguments N .

[ y1. yN ] = solve( eqns , vars , Name,Value ) uses additional options specified by one or more Name,Value pair arguments.

[ y1. yN , parameters , conditions ] = solve( eqns , vars ,’ ReturnConditions ‘,true) returns the additional arguments parameters and conditions that specify the parameters in the solution and the conditions on the solution.

Видео:Алгоритмы. Нахождение корней уравнений методом деления отрезка пополам.Скачать

Алгоритмы. Нахождение корней уравнений методом деления отрезка пополам.

Examples

Solve Quadratic Equation

Solve the quadratic equation without specifying a variable to solve for. solve chooses x to return the solution.

Specify the variable to solve for and solve the quadratic equation for a .

Solve Polynomial and Return Real Solutions

Solve a fifth-degree polynomial. It has five solutions.

Return only real solutions by setting ‘Real’ option to true . The only real solutions of this equation is 5 .

Numerically Solve Equations

When solve cannot symbolically solve an equation, it tries to find a numeric solution using vpasolve . The vpasolve function returns the first solution found.

Try solving the following equation. solve returns a numeric solution because it cannot find a symbolic solution.

Plot the left and the right sides of the equation. Observe that the equation also has a positive solution.

Как найти корни уравнения matlab

Find the other solution by directly calling the numeric solver vpasolve and specifying the interval.

Solve Multivariate Equations and Assign Outputs to Structure

When solving for multiple variables, it can be more convenient to store the outputs in a structure array than in separate variables. The solve function returns a structure when you specify a single output argument and multiple outputs exist.

Solve a system of equations to return the solutions in a structure array.

Access the solutions by addressing the elements of the structure.

Using a structure array allows you to conveniently substitute solutions into other expressions.

Use the subs function to substitute the solutions S into other expressions.

If solve returns an empty object, then no solutions exist.

Solve Inequalities

The solve function can solve inequalities and return solutions that satisfy the inequalities. Solve the following inequalities.

x 2 + y 2 + x y 1

Set ‘ReturnConditions’ to true to return any parameters in the solution and conditions on the solution.

The parameters u and v do not exist in MATLAB® workspace and must be accessed using S.parameters .

Check if the values u = 7/2 and v = 1/2 satisfy the condition using subs and isAlways .

isAlways returns logical 1 ( true ) indicating that these values satisfy the condition. Substitute these parameter values into S.x and S.y to find a solution for x and y .

Solve Multivariate Equations and Assign Outputs to Variables

Solve the system of equations.

When solving for more than one variable, the order in which you specify the variables defines the order in which the solver returns the solutions. Assign the solutions to variables solv and solu by specifying the variables explicitly. The solver returns an array of solutions for each variable.

Entries with the same index form the pair of solutions.

Use Parameters and Conditions to Refine Solution

Return the complete solution of an equation with parameters and conditions of the solution by specifying ‘ReturnConditions’ as true .

Solve the equation sin ( x ) = 0 . Provide two additional output variables for output arguments parameters and conditions .

The solution π k contains the parameter k , where k must be an integer. The variable k does not exist in MATLAB workspace and must be accessed using parameters .

Restrict the solution to 0 x 2 π . Find a valid value of k for this restriction. Assume the condition, conditions , and use solve to find k . Substitute the value of k found into the solution for x .

Alternatively, determine the solution for x by choosing a value of k . Check if the value chosen satisfies the condition on k using isAlways .

Check if k = 4 satisfies the condition on k .

isAlways returns logical 1( true ), meaning that 4 is a valid value for k . Substitute k with 4 to obtain a solution for x . Use vpa to obtain a numeric approximation.

Shorten Result with Simplification Rules

Solve the equation exp ( log ( x ) log ( 3 x ) ) = 4 .

By default, solve does not apply simplifications that are not valid for all values of x . In this case, the solver does not assume that x is a positive real number, so it does not apply the logarithmic identity log ( 3 x ) = log ( 3 ) + log ( x ) . As a result, solve cannot solve the equation symbolically.

Set ‘IgnoreAnalyticConstraints’ to true to apply simplification rules that might allow solve to find a solution. For details, see Algorithms.

solve applies simplifications that allow the solver to find a solution. The mathematical rules applied when performing simplifications are not always valid in general. In this example, the solver applies logarithmic identities with the assumption that x is a positive real number. Therefore, the solutions found in this mode should be verified.

Ignore Assumptions on Variables

The sym and syms functions let you set assumptions for symbolic variables.

Assume that the variable x is positive.

When you solve an equation for a variable under assumptions, the solver only returns solutions consistent with the assumptions. Solve this equation for x .

Allow solutions that do not satisfy the assumptions by setting ‘IgnoreProperties’ to true .

For further computations, clear the assumption that you set on the variable x by recreating it using syms .

Solve Polynomial Equations of High Degree

When you solve a polynomial equation, the solver might use root to return the solutions. Solve a third-degree polynomial.

Try to get an explicit solution for such equations by calling the solver with ‘MaxDegree’ . The option specifies the maximum degree of polynomials for which the solver tries to return explicit solutions. The default value is 2 . Increasing this value, you can get explicit solutions for higher order polynomials.

Solve the same equations for explicit solutions by increasing the value of ‘MaxDegree’ to 3 .

Return One Solution

Solve the equation sin ( x ) + cos ( 2 x ) = 1 .

Instead of returning an infinite set of periodic solutions, the solver picks three solutions that it considers to be the most practical.

Choose only one solution by setting ‘PrincipalValue’ to true .

Видео:Как найти корни уравнения в Excel с помощью Подбора параметраСкачать

Как найти корни уравнения в Excel с помощью Подбора параметра

Input Arguments

eqn — Equation to solve
symbolic expression | symbolic equation

Equation to solve, specified as a symbolic expression or symbolic equation. The relation operator == defines symbolic equations. If eqn is a symbolic expression (without the right side), the solver assumes that the right side is 0, and solves the equation eqn == 0 .

var — Variable for which you solve equation
symbolic variable

Variable for which you solve an equation, specified as a symbolic variable. By default, solve uses the variable determined by symvar .

eqns — System of equations
symbolic expressions | symbolic equations

System of equations, specified as symbolic expressions or symbolic equations. If any elements of eqns are symbolic expressions (without the right side), solve equates the element to 0 .

vars — Variables for which you solve an equation or system of equations
symbolic vector | symbolic matrix

Variables for which you solve an equation or system of equations, specified as a symbolic vector or symbolic matrix. By default, solve uses the variables determined by symvar .

The order in which you specify these variables defines the order in which the solver returns the solutions.

Name-Value Arguments

Real — Flag for returning only real solutions
false (default) | true

Flag for returning only real solutions, specified as the comma-separated pair consisting of ‘Real’ and one of these values.

falseReturn all solutions.
trueReturn only those solutions for which every subexpression of the original equation represents a real number. This option also assumes that all symbolic parameters of an equation represent real numbers.

ReturnConditions — Flag for returning parameters and conditions
false (default) | true

Flag for returning parameters in solution and conditions under which the solution is true, specified as the comma-separated pair consisting of ‘ReturnConditions’ and one of these values.

falseDo not return parameterized solutions and the conditions under which the solution holds. The solve function replaces parameters with appropriate values.
trueReturn the parameters in the solution and the conditions under which the solution holds. For a call with a single output variable, solve returns a structure with the fields parameters and conditions . For multiple output variables, solve assigns the parameters and conditions to the last two output variables. This behavior means that the number of output variables must be equal to the number of variables to solve for plus two.

Example: [v1, v2, params, conditions] = solve(sin(x) +y == 0,y^2 == 3,’ReturnConditions’,true) returns the parameters in params and conditions in conditions .

IgnoreAnalyticConstraints — Simplification rules applied to expressions and equations
false (default) | true

Simplification rules applied to expressions and equations, specified as the comma-separated pair consisting of ‘IgnoreAnalyticConstraints’ and one of these values.

falseUse strict simplification rules.
trueApply purely algebraic simplifications to expressions and equations. Setting IgnoreAnalyticConstraints to true can give you simpler solutions, which could lead to results not generally valid. In other words, this option applies mathematical identities that are convenient, but the results might not hold for all possible values of the variables. In some cases, it also enables solve to solve equations and systems that cannot be solved otherwise.

IgnoreProperties — Flag for returning solutions inconsistent with properties of variables
false (default) | true

Flag for returning solutions inconsistent with the properties of variables, specified as the comma-separated pair consisting of ‘IgnoreProperties’ and one of these values.

falseDo not include solutions inconsistent with the properties of variables.
trueInclude solutions inconsistent with the properties of variables.

MaxDegree — Maximum degree of polynomial equations for which solver uses explicit formulas
2 (default) | positive integer smaller than 5

Maximum degree of polynomial equations for which solver uses explicit formulas, specified as a positive integer smaller than 5. The solver does not use explicit formulas that involve radicals when solving polynomial equations of a degree larger than the specified value.

PrincipalValue — Flag for returning one solution
false (default) | true

Flag for returning one solution, specified as the comma-separated pair consisting of ‘PrincipalValue’ and one of these values.

falseReturn all solutions.
trueReturn only one solution. If an equation or a system of equations does not have a solution, the solver returns an empty symbolic object.

Output Arguments

S — Solutions of equation
symbolic array

Solutions of an equation, returned as a symbolic array. The size of a symbolic array corresponds to the number of the solutions.

Y — Solutions of system of equations
structure

Solutions of a system of equations, returned as a structure. The number of fields in the structure correspond to the number of independent variables in a system. If ‘ReturnConditions’ is set to true , the solve function returns two additional fields that contain the parameters in the solution, and the conditions under which the solution is true.

y1. yN — Solutions of system of equations
symbolic variables

Solutions of a system of equations, returned as symbolic variables. The number of output variables or symbolic arrays must be equal to the number of independent variables in a system. If you explicitly specify independent variables vars , then the solver uses the same order to return the solutions. If you do not specify vars , the toolbox sorts independent variables alphabetically, and then assigns the solutions for these variables to the output variables.

parameters — Parameters in solution
vector of generated parameters

Parameters in a solution, returned as a vector of generated parameters. This output argument is only returned if ReturnConditions is true . If a single output argument is provided, parameters is returned as a field of a structure. If multiple output arguments are provided, parameters is returned as the second-to-last output argument. The generated parameters do not appear in the MATLAB ® workspace. They must be accessed using parameters .

Example: [solx, params, conditions] = solve(sin(x) == 0, ‘ReturnConditions’, true) returns the parameter k in the argument params .

conditions — Conditions under which solutions are valid
vector of symbolic expressions

Conditions under which solutions are valid, returned as a vector of symbolic expressions. This output argument is only returned if ReturnConditions is true . If a single output argument is provided, conditions is returned as a field of a structure. If multiple output arguments are provided, conditions is returned as the last output argument.

Example: [solx, params, conditions] = solve(sin(x) == 0, ‘ReturnConditions’, true) returns the condition in(k, ‘integer’) in conditions . The solution in solx is valid only under this condition.

If solve cannot find a solution and ReturnConditions is false , the solve function internally calls the numeric solver vpasolve that tries to find a numeric solution. For polynomial equations and systems without symbolic parameters, the numeric solver returns all solutions. For nonpolynomial equations and systems without symbolic parameters, the numeric solver returns only one solution (if a solution exists).

If solve cannot find a solution and ReturnConditions is true , solve returns an empty solution with a warning. If no solutions exist, solve returns an empty solution without a warning.

If the solution contains parameters and ReturnConditions is true , solve returns the parameters in the solution and the conditions under which the solutions are true. If ReturnConditions is false , the solve function either chooses values of the parameters and returns the corresponding results, or returns parameterized solutions without choosing particular values. In the latter case, solve also issues a warning indicating the values of parameters in the returned solutions.

If a parameter does not appear in any condition, it means the parameter can take any complex value.

The output of solve can contain parameters from the input equations in addition to parameters introduced by solve .

Parameters introduced by solve do not appear in the MATLAB workspace. They must be accessed using the output argument that contains them. Alternatively, to use the parameters in the MATLAB workspace use syms to initialize the parameter. For example, if the parameter is k , use syms k .

The variable names parameters and conditions are not allowed as inputs to solve .

To solve differential equations, use the dsolve function.

When solving a system of equations, always assign the result to output arguments. Output arguments let you access the values of the solutions of a system.

MaxDegree only accepts positive integers smaller than 5 because, in general, there are no explicit expressions for the roots of polynomials of degrees higher than 4.

The output variables y1. yN do not specify the variables for which solve solves equations or systems. If y1. yN are the variables that appear in eqns , then there is no guarantee that solve(eqns) will assign the solutions to y1. yN using the correct order. Thus, when you run [b,a] = solve(eqns) , you might get the solutions for a assigned to b and vice versa.

To ensure the order of the returned solutions, specify the variables vars . For example, the call [b,a] = solve(eqns,b,a) assigns the solutions for a to a and the solutions for b to b .

Algorithms

When you use IgnoreAnalyticConstraints , the solver applies these rules to the expressions on both sides of an equation.

log( a) + log( b) = log( a· b) for all values of a and b. In particular, the following equality is valid for all values of a, b, and c:

log( a b ) = b·log( a) for all values of a and b. In particular, the following equality is valid for all values of a, b, and c:

If f and g are standard mathematical functions and f( g( x)) = x for all small positive numbers, f( g( x)) = x is assumed to be valid for all complex values x. In particular:

asinh(sinh( x)) = x , acosh(cosh( x)) = x , atanh(tanh( x)) = x

W k( x· e x ) = x for all branch indices k of the Lambert W function.

The solver can multiply both sides of an equation by any expression except 0 .

The solutions of polynomial equations must be complete.

Поделиться или сохранить к себе: