Solve Equations Numerically - MATLAB & Simulink (2024)

Open Live Script

Symbolic Math Toolbox™ offers both numeric and symbolic equation solvers. For a comparison of numeric and symbolic solvers, see Select Numeric or Symbolic Solver. An equation or a system of equations can have multiple solutions. To find these solutions numerically, use the function vpasolve. For polynomial equations, vpasolve returns all solutions. For nonpolynomial equations, vpasolve returns the first solution it finds. These examples show you how to use vpasolve to find solutions to both polynomial and nonpolynomial equations, and how to obtain these solutions to arbitrary precision.

Find All Roots of a Polynomial Function

Use vpasolve to find all the solutions to the function f(x)=6x7-2x6+3x3-8.

syms f(x)f(x) = 6*x^7-2*x^6+3*x^3-8;sol = vpasolve(f)
sol =

(1.0240240759053702941448316563337-0.88080620051762149639205672298326+0.50434058840127584376331806592405i-0.88080620051762149639205672298326-0.50434058840127584376331806592405i-0.22974795226118163963098570610724+0.96774615576744031073999010695171i-0.22974795226118163963098570610724-0.96774615576744031073999010695171i0.7652087814927846556172932675903+0.83187331431049713218367239317121i0.7652087814927846556172932675903-0.83187331431049713218367239317121i)

vpasolve returns seven roots of the function, as expected, because the function is a polynomial of degree seven.

Find Zeros of a Nonpolynomial Function Using Search Ranges and Starting Points

A plot of the function f(x)=e(x/7)cos(2x) reveals periodic zeros, with increasing slopes at the zero points as x increases.

syms xh = fplot(exp(x/7)*cos(2*x),[-2 25]);grid on

Solve Equations Numerically- MATLAB & Simulink (1)

Use vpasolve to find a zero of the function f. Note that vpasolve returns only one solution of a nonpolynomial equation, even if multiple solutions exist. On repeated calls, vpasolve returns the same result.

f = exp(x/7)*cos(2*x);for k = 1:3 vpasolve(f,x)end
ans =-7.0685834705770347865409476123789
ans =-7.0685834705770347865409476123789
ans =-7.0685834705770347865409476123789

To find multiple solutions, set the option 'Random' to true. This makes vpasolve choose starting points randomly. For information on the algorithm that chooses random starting points, see Algorithms on the vpasolve page.

for k = 1:3 vpasolve(f,x,'Random',true)end
ans =-226.98006922186256147892598444194
ans =52.621676947629036744249276669932

To find a zero close to x=10, set the starting point to 10.

vpasolve(f,x,10)
ans =10.210176124166828025003590995658

To find a zero close to x=1000, set the starting point to 1000.

vpasolve(f,x,1000)
ans =999.8118620049516981407362567287

To find a zero in the range 15x25, set the search range to [15 25].

vpasolve(f,x,[15 25])
ans =21.205750411731104359622842837137

To find multiple zeros in the range [15 25], you cannot call vpasolve repeatedly because it returns the same result on each call, as previously shown. Instead, set the search range and set 'Random' to true.

for k = 1:3 vpasolve(f,x,[15 25],'Random',true)end
ans =21.205750411731104359622842837137
ans =21.205750411731104359622842837137
ans =16.493361431346414501928877762217

Because 'Random' selects starting points randomly, the same solution might be found on successive calls.

Find All Zeros in a Specified Search Range

Create a function findzeros to systematically find all zeros for f in a given search range, within a specified error tolerance. The function starts with the input search range and calls vpasolve to find a zero. Then, it splits the search range into two around the zero value and recursively calls itself with the new search ranges as inputs to find more zeros.

The function is explained section by section here.

Declare the function with the three inputs and one output. The first input is the function, the second input is the range, and the optional third input allows you to specify the error between a zero and the higher and lower bounds generated from it.

function sol = findzeros(f,range,err)

If you do not specify the optional argument for error tolerance, findzeros sets err to 0.001.

if nargin < 2 err = 1e-3;end

Find a zero in the search range using vpasolve.

sol = vpasolve(f,range);

If vpasolve does not find a zero, exit.

if(isempty(sol)) return

If vpasolve finds a zero, split the search range into two search ranges above and below the zero.

else lowLimit = sol-err; highLimit = sol+err;

Call findzeros with the lower search range. If findzeros returns zeros, copy the values into the solution array and sort them.

 temp = findzeros(f,[range(1) lowLimit],1); if ~isempty(temp) sol = sort([sol temp]); end

Call findzeros with the higher search range. If findzeros returns zeros, copy the values into the solution array and sort them.

 temp = findzeros(f,[highLimit range(2)],1); if ~isempty(temp) sol = sort([sol temp]); end returnendend

The entire function findzeros is as follows. Save this function as findzeros.m in the current folder.

function sol = findzeros(f,range,err)if nargin < 3 err = 1e-3;endsol = vpasolve(f,range);if(isempty(sol)) returnelse lowLimit = sol-err; highLimit = sol+err; temp = findzeros(f,[range(1) lowLimit],1); if ~isempty(temp) sol = sort([sol temp]); end temp = findzeros(f,[highLimit range(2)],1); if ~isempty(temp) sol = sort([sol temp]); end returnendend

Call findzeros with search range [15 25] to find all zeros in that range for f(x) = exp(x/7)*cos(2*x), within the default error tolerance.

syms f(x)f(x) = exp(x/7)*cos(2*x);sol = findzeros(f,[15 25])'
sol =

(16.49336143134641450192887776221718.06415775814131112116019945385719.63495408493620774039152114549721.20575041173110435962284283713722.77654673852600097885416452877624.347343065320897598085486220416)

Obtain Solutions to Arbitrary Precision

Use digits to set the precision of the solutions returned by vpasolve. By default, vpasolve returns solutions to a precision of 32 significant figures.

f = exp(x/7)*cos(2*x);vpasolve(f)
ans =-7.0685834705770347865409476123789

Use digits to increase the precision to 64 significant figures. When modifying digits, ensure that you save its current value so that you can restore it.

digitsOld = digits;digits(64)vpasolve(f)
ans =-7.068583470577034786540947612378881489443631148593988097193625333

Next, change the precision of the solutions to 16 significant figures.

digits(16)

Solve Multivariate Equations Using Search Ranges

Consider the following system of equations.

z=10(cos(x)+cos(y))z=x+y2-0.1x2yx+y-2.7=0

A plot of the equations for 0x2.5 and 0x2.5 shows that the three surfaces intersect in two points. To better visualize the plot, change the line of sight using view.

syms x y zeqn1 = z == 10*(cos(x) + cos(y));eqn2 = z == x+y^2-0.1*x^2*y;eqn3 = x+y-2.7 == 0;equations = [eqn1 eqn2 eqn3];fimplicit3(equations)axis([0 2.5 0 2.5 -20 10])title('System of Multivariate Equations')view(69,28)

Solve Equations Numerically- MATLAB & Simulink (2)

Use vpasolve to find a point where the surfaces intersect. The function vpasolve returns a structure. To access the x-, y-, and z-values of the solution, index into the structure.

sol = vpasolve(equations);[sol.x sol.y sol.z]
ans =(2.3697477224547980.33025227754520212.293354376823228)

To search a region of the solution space, specify search ranges for the variables. If you specify the ranges 0x1.5 and 1.5y2.5, then vpasolve function searches the bounded area shown.

Solve Equations Numerically- MATLAB & Simulink (3)

Use vpasolve to find a solution for this search range. To omit a search range for z, set the third search range to [NaN NaN].

vars = [x y z];range = [0 1.5; 1.5 2.5; NaN NaN];sol = vpasolve(equations,vars,range);[sol.x sol.y sol.z]
ans =(0.91062661725633361.7893733827436663.964101572135625)

To find multiple solutions, set the 'Random' option to true. This makes vpasolve use random starting points on successive runs. The 'Random' option can be used in conjunction with search ranges to make vpasolve use random starting points within a search range. Because 'Random' selects starting points randomly, the same solution might be found on successive calls. Call vpasolve repeatedly to ensure you find both solutions.

clear solrange = [0 3; 0 3; NaN NaN];for k = 1:5 temp = vpasolve(equations,vars,range,'Random',true); sol(k,1) = temp.x; sol(k,2) = temp.y; sol(k,3) = temp.z;endsol
sol =

(2.3697477224547980.33025227754520212.2933543768232282.3697477224547980.33025227754520212.2933543768232282.3697477224547980.3302522775452022.2933543768232280.91062661725633361.7893733827436663.9641015721356250.91062661725633361.7893733827436663.964101572135625)

Plot the equations. Superimpose the solutions as a scatter plot of points with yellow X markers using scatter3. To better visualize the plot, make two of the surfaces transparent using alpha and change the line of sight using view.

vpasolve finds solutions at the intersection of the surfaces formed by the equations as shown.

clfax = axes;h = fimplicit3(equations);h(2).FaceAlpha = 0;h(3).FaceAlpha = 0;axis([0 2.5 0 2.5 -20 10])hold onscatter3(sol(:,1),sol(:,2),sol(:,3),600,'red','X','LineWidth',2)title('Randomly Found Solutions in Specified Search Range')cz = ax.Children;view(69,28)hold off

Solve Equations Numerically- MATLAB & Simulink (4)

Lastly, restore the old value of digits for further calculations.

digits(digitsOld)
Solve Equations Numerically
- MATLAB & Simulink (2024)

FAQs

Solve Equations Numerically - MATLAB & Simulink? ›

An equation or a system of equations can have multiple solutions. To find these solutions numerically, use the function vpasolve . For polynomial equations, vpasolve returns all solutions. For nonpolynomial equations, vpasolve returns the first solution it finds.

How to numerically solve an equation in MATLAB? ›

Y = vpasolve( eqns , vars ) numerically solves the system of equations eqns for the variables vars . This syntax returns a structure array Y that contains the solutions. The fields in the structure array correspond to the variables specified by vars .

How to solve equations in Simulink? ›

For analytic solutions, use solve , and for numerical solutions, use vpasolve . For solving linear equations, use linsolve . These solver functions have the flexibility to handle complicated problems. See Troubleshoot Equation Solutions from solve Function.

Can you use MATLAB to solve equations? ›

Solve an Equation

If eqn is an equation, solve(eqn, x) solves eqn for the symbolic variable x . Use the == operator to specify the familiar quadratic equation and solve it using solve .

Can Navier Stokes be solved numerically? ›

The Navier-Stokes equations can be solved numerically using methods such as the method of lines and finite element discretization. The Navier-Stokes equations can be solved numerically using modeling approaches such as FDM, FVM, or FEM.

What are the numerical methods for solving equations? ›

Other commonly used numerical methods for solving equations include Newton's method, the bisection method, and the secant method. These methods use iterative approaches to finding the solution where each iteration yields a better approximation than the previous.

Which solver to use in Simulink? ›

You must use a continuous solver to solve a model that contains both continuous and discrete states because discrete solvers cannot handle continuous states. If, on the other hand, you select a continuous solver for a model with no states or discrete states only, Simulink software uses a discrete solver.

How to use Simulink in MATLAB? ›

Create a Simulink Model
  1. In the MATLAB® Home tab, click the Simulink button.
  2. Click Blank Model, and then Create Model. ...
  3. On the Simulation tab, click Library Browser.
  4. In the Library Browser: ...
  5. Make the following block-to-block connections: ...
  6. Double-click the Transfer Fcn block. ...
  7. Double-click the Signal Generator block.

What is the command to solve an equation in MATLAB? ›

Syntax
  1. S = solve(eqn,var) S = solve(eqn,var,Name,Value)
  2. Y = solve(eqns,vars) Y = solve(eqns,vars,Name,Value)
  3. [y1,...,yN] = solve(eqns,vars) [y1,...,yN] = solve(eqns,vars,Name,Value) [y1,...,yN,parameters,conditions] = solve(eqns,vars,'ReturnConditions',true)

Can MATLAB do algebra? ›

Linear algebra functions in MATLAB® provide fast, numerically robust matrix calculations. Capabilities include a variety of matrix factorizations, linear equation solving, computation of eigenvalues or singular values, and more.

How to simulate a Simulink model from MATLAB? ›

A prefered way to run a simulation from MATLAB is to use the SimulationInput object.
  1. simIn = Simulink.SimulationInput("Model_Name"); %create object.
  2. simIn = simIn.setVariable("my_Parameter",2); %example of setting a parameter override.
  3. out = sim(simIn); %run simulation, all results returned in "out"
Mar 16, 2017

How do you convert to numerical in MATLAB? ›

To convert text to numeric values, use the str2double function. It treats string arrays, character vectors, and cell arrays of character vectors consistently. You can also use the double function for string arrays.

How to solve a system of differential equations numerically in MATLAB? ›

Solve System of Differential Equations

First, represent u and v by using syms to create the symbolic functions u(t) and v(t) . Define the equations using == and represent differentiation using the diff function. Solve the system using the dsolve function which returns the solutions as elements of a structure.

How to solve PDE numerically in MATLAB? ›

pdeval
  1. The numerical solution produced by sol = pdepe(m,@pdefun,@pdeic,@pdebc,xmesh,tspan) uses the coordinate symmetry m and spatial mesh xmesh to return a 3-D matrix of the solution values sol . ...
  2. The input vector usol = sol(i,:,k) is the value of component k of the solution at time tspan(i) .

What is the command in MATLAB to obtain the solution of a function numerically? ›

An equation or a system of equations can have multiple solutions. To find these solutions numerically, use the function vpasolve . For polynomial equations, vpasolve returns all solutions. For nonpolynomial equations, vpasolve returns the first solution it finds.

References

Top Articles
Latest Posts
Article information

Author: Mrs. Angelic Larkin

Last Updated:

Views: 5319

Rating: 4.7 / 5 (47 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Mrs. Angelic Larkin

Birthday: 1992-06-28

Address: Apt. 413 8275 Mueller Overpass, South Magnolia, IA 99527-6023

Phone: +6824704719725

Job: District Real-Estate Facilitator

Hobby: Letterboxing, Vacation, Poi, Homebrewing, Mountain biking, Slacklining, Cabaret

Introduction: My name is Mrs. Angelic Larkin, I am a cute, charming, funny, determined, inexpensive, joyous, cheerful person who loves writing and wants to share my knowledge and understanding with you.