Pde Matlab PDF
Pde Matlab PDF
Pde Matlab PDF
User's Guide
R2018b
How to Contact MathWorks
Phone: 508-647-7000
Getting Started
1
Partial Differential Equation Toolbox Product Description . . . 1-2
Key Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
v
Create Basic Shapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10
Create Names for the Basic Shapes . . . . . . . . . . . . . . . . . . . 2-12
Set Formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-13
Create Geometry and Remove Face Boundaries . . . . . . . . . . 2-13
Decomposed Geometry Data Structure . . . . . . . . . . . . . . . . . 2-15
vi Contents
Specify 3-D PDE Coefficients in Function Form . . . . . . . . . . . 2-85
vii
View, Edit, and Delete PDE Coefficients . . . . . . . . . . . . . . . . 2-157
View Coefficients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-157
Delete Existing Coefficients . . . . . . . . . . . . . . . . . . . . . . . . 2-159
Change a Coefficient Assignment . . . . . . . . . . . . . . . . . . . . 2-160
viii Contents
Solve PDEs with Nonconstant Boundary Conditions . . . . . . 2-193
Geometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-193
Scalar Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-194
System of PDEs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-196
Solving PDEs
3
von Mises Effective Stress and Displacements . . . . . . . . . . . . . 3-3
ix
Vibration of Square Plate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-61
x Contents
Poisson's Equation with Point Source and Adaptive Mesh
Refinement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-172
xi
Solve Poisson's Equation on a Grid . . . . . . . . . . . . . . . . . . . . 3-264
xii Contents
Plot the Solution in the PDE Modeler App . . . . . . . . . . . . . . . 4-29
Additional Plot Control Options . . . . . . . . . . . . . . . . . . . . . . . 4-32
Tooltip Displays for Mesh and Plots . . . . . . . . . . . . . . . . . . . 4-34
xiii
1
Getting Started
Partial Differential Equation Toolbox provides functions for solving structural mechanics,
heat transfer, and general partial differential equations (PDEs) using finite element
analysis.
You can perform linear static analysis to compute deformation, stress, and strain. For
modeling structural dynamics and vibration, the toolbox provides a direct time integration
solver. You can analyze a component’s structural characteristics by performing modal
analysis to find natural frequencies and mode shapes. You can model conduction-
dominant heat transfer problems to calculate temperature distributions, heat fluxes, and
heat flow rates through surfaces. You can also solve standard problems such as diffusion,
electrostatics, and magnetostatics, as well as custom PDEs.
Partial Differential Equation Toolbox lets you import 2D and 3D geometries from STL or
mesh data. You can automatically generate meshes with triangular and tetrahedral
elements. You can solve PDEs by using the finite element method, and postprocess results
to explore and analyze them.
Key Features
• Structural analysis, including linear static, dynamic, and modal analysis
• Heat transfer analysis for conduction-dominant problems
• General linear and nonlinear PDEs for stationary, time-dependent, and eigenvalue
problems
• 2D and 3D geometry import from STL files and mesh data
• Automatic meshing using triangular and tetrahedral elements with linear or quadratic
basis functions
• User-defined functions for specifying PDE coefficients, boundary conditions, and initial
conditions
• Plotting and animating results, as well as derived and interpolated values
1-2
Equations You Can Solve Using Legacy Functions
Note THIS PAGE DESCRIBES THE LEGACY WORKFLOW. New features might not be
compatible with the legacy workflow. For the corresponding step in the recommended
workflow, see “Equations You Can Solve Using PDE Toolbox” on page 1-6.
-— ◊ ( c—u ) + au = f
expressed in Ω, which we shall refer to as the elliptic equation, regardless of whether its
coefficients and boundary conditions make the PDE problem elliptic in the mathematical
sense. Analogously, we shall use the terms parabolic equation and hyperbolic equation for
equations with spatial operators like the previous one, and first and second order time
derivatives, respectively. Ω is a bounded domain in the plane or is a bounded 3-D region.
c, a, f, and the unknown u are scalar, complex valued functions defined on Ω. c can be a
matrix function on Ω (see “c Coefficient for Systems” on page 2-131). The software can
also handle the parabolic PDE
∂u
d - — ◊ ( c— u ) + au = f
∂t
∂ 2u
d - — ◊ ( c— u) + au = f
∂t2
-— ◊ ( c—u ) + au = l du
-— ◊ ( c(u)— u) + a( u) u = f (u)
1-3
1 Getting Started
where c, a, and f are functions of the unknown solution u and of its gradient ∇u. The
parabolic and hyperbolic equation solvers also solve nonlinear and time-dependent
problems.
Note Before solving a nonlinear elliptic PDE, from the Solve menu in the PDE Modeler
app, select Parameters. Then, select the Use nonlinear solver check box and click OK.
For eigenvalue problems, the coefficients cannot depend on the solution u or its gradient.
All solvers can handle the system case of N coupled equations. You can solve N = 1 or 2
equations using the PDE Modeler app, and any number of equations using command-line
functions. For example, N = 2 elliptic equations:
For the elliptic problem, an adaptive mesh refinement algorithm is implemented. It can
also be used in conjunction with the nonlinear solver. In addition, a fast solver for
Poisson's equation on a rectangular grid is available.
n is the outward unit normal. g, q, h, and r are complex-valued functions defined on ∂Ω.
r
(The eigenvalue problem is a homogeneous problem, i.e., g = 0, r = 0.) In the nonlinear
case, the coefficients g, q, h, and r can depend on u, and for the hyperbolic and parabolic
PDE, the coefficients can depend on time. For the two-dimensional system case, Dirichlet
boundary condition is
1-4
Equations You Can Solve Using Legacy Functions
h11u1 + h12u2 = r1
h21u1 + h22u2 = r2
h11u1 + h12u2 = r1
n · ( c11— u1 ) + n · ( c12— u2 ) + q11u1 + q12u2 = g1 + h11 m
r r
where µ is computed such that the Dirichlet boundary condition is satisfied. Dirichlet
boundary conditions are also called essential boundary conditions, and Neumann
boundary conditions are also called natural boundary conditions.
For advanced, nonstandard applications you can transfer the description of domains,
boundary conditions etc. to your MATLAB® workspace. From there you use Partial
Differential Equation Toolbox functions for managing data on unstructured meshes. You
have full access to the mesh generators, FEM discretizations of the PDE and boundary
conditions, interpolation functions, etc. You can design your own solvers or use FEM to
solve subproblems of more complex algorithms. See also “Solve PDEs Programmatically”
on page 3-258.
1-5
1 Getting Started
∂ 2u ∂u
m +d - —·( c—u ) + au = f
2 ∂t
∂t
- —·( c— u) + au = l du
or
- —·( c— u) + au = l 2mu
For scalar PDEs, there are two choices of boundary conditions for each edge or face:
hu = r,
where h and r can be functions of space (x, y, and, in 3-D case, z), the solution u, and
time. Often, you take h = 1, and set r to the appropriate value.
• Generalized Neumann boundary conditions — On the edge or face the solution u
satisfies the equation
n ·( c— u) + qu = g
r
n is the outward unit normal. q and g are functions defined on ∂Ω, and can be
r
functions of x, y, and, in 3-D case, z, the solution u, and, for time-dependent equations,
time.
∂2 u ∂u
m +d - —·( c ƒ —u ) + au = f
2 ∂t
∂t
1-6
Equations You Can Solve Using PDE Toolbox
- —·( c ƒ — u ) + au = l du
or
- —·( c ƒ — u ) + au = l 2mu
The coefficients m, d, c, a, and f can be functions of location (x, y, and, in 3-D, z), and,
except for eigenvalue problems, they also can be functions of the solution u or its
gradient. For eigenvalue problems, the coefficients cannot depend on the solution u or its
gradient.
For scalar equations, all the coefficients except c are scalar. The coefficient c represents a
2-by-2 matrix in 2-D geometry, or a 3-by-3 matrix in 3-D geometry. For systems of N
equations, the coefficients m, d, and a are N-by-N matrices, f is an N-by-1 vector, and c is
a 2N-by-2N tensor (2-D geometry) or a 3N-by-3N tensor (3-D geometry). For the meaning
of c ƒ u , see “c Coefficient for specifyCoefficients” on page 2-110.
When both m and d are 0, the PDE is stationary. When either m or d are nonzero, the
problem is time-dependent. When any coefficient depends on the solution u or its
gradient, the problem is called nonlinear.
For systems of PDEs, there are generalized versions of the Dirichlet and Neumann
boundary conditions:
N
Ê ∂ ∂ ∂ ∂ ˆ
 ÁË cos(a )ci, j,1,1 ∂x + cos(a)ci, j ,1,2 ∂y + sin(a)ci, j ,2,1 ∂x + sin(a)ci, j,2,2 ∂y ˜¯ u j
j =1
1-7
1 Getting Started
For 3-D systems, the notation n · ( c ƒ — u ) means the N-by-1 vector with (i,1)-
component
N
Ê ∂ ∂ ∂ ˆ
 ÁË sin (j ) cos (q ) ci, j ,1,1 ∂x + sin (j ) cos (q ) ci, j,1,2 ∂y + sin (j )cos (q ) ci, j ,1,3 ∂z ˜¯ u j
j =1
N
Ê ∂ ∂ ∂ ˆ
+  ÁË sin (j ) sin (q ) ci, j,2,1 ∂x + sin (j )s in (q ) ci, j ,2,2 ∂y + sin (j ) sin (q ) ci, j,2,3 ∂z ˜¯ u j
j =1
N
Ê ∂ ∂ ∂ ˆ
+  ÁË cos (q ) ci, j,3,1 ∂x + cos (q ) ci, j,3,2 ∂y + cos (q ) ci, j ,3,3 ∂z ˜¯ u j
j =1
For each edge or face segment, there are a total of N boundary conditions.
See Also
Related Examples
• “Solve Problems Using PDEModel Objects” on page 2-6
• “f Coefficient for specifyCoefficients” on page 2-107
• “c Coefficient for specifyCoefficients” on page 2-110
• “m, d, or a Coefficient for specifyCoefficients” on page 2-149
1-8
Common Toolbox Applications
In addition to solving generic scalar PDEs and generic systems of PDEs with vector
valued u, Partial Differential Equation Toolbox provides tools for solving PDEs that occur
in these common applications in engineering and science:
The PDE Modeler app lets you specify PDE coefficients and boundary conditions in terms
of physical entities. For example, you can specify Young's modulus in structural
mechanics problems.
The application mode can be selected directly from the pop-up menu in the upper right
part of the PDE Modeler app or by selecting an application from the Application
submenu in the Options menu. Changing the application resets all PDE coefficients and
boundary conditions to the default values for that specific application mode.
When using an application mode, the generic PDE coefficients are replaced by
application-specific parameters such as Young's modulus for problems in structural
1-9
1 Getting Started
Note In the User entry options in the Plot Selection dialog box, the solution and its
derivatives are always referred to as u, ux, and uy (v, vx, and vy for the system cases)
even if the application mode is nongeneric and the solution of the application-specific
PDE normally is named, e.g., V or T.
The PDE Modeler app lets you solve problems with vector valued u of dimension two.
However, you can use functions to solve problems for any dimension of u.
1-10
Solve 2-D PDEs Using the PDE Modeler App
You can specify the coefficients at any time before solving the PDE because the
coefficients are independent of the geometry and the boundaries. If the PDE
coefficients are material-dependent, specify them by double-clicking each particular
region.
6 Generate a triangular mesh by selecting Initialize Mesh from the Mesh menu.
Using the same menu, you can also refine mesh, display node and triangle labels, and
control mesh parameters, letting you generate a mesh that is fine enough to
adequately resolve the important features in the geometry, but is coarse enough to
run in a reasonable amount of time and memory. See “Specify Mesh Parameters in
the PDE Modeler App” on page 4-20.
7 Solve the PDE by clicking the = button or by selecting Solve PDE from the Solve
menu. To use a solver with non-default parameters, select Parameters from the
Solve menu to. The resulting dialog box lets you:
1-11
1 Getting Started
• Invoke and control the nonlinear and adaptive solvers for elliptic problems.
• Specify the initial values, and the times for which to generate the output for
parabolic and hyperbolic problems.
• Specify the interval in which to search for eigenvalues for eigenvalue problems.
See “Adjust Solve Parameters in the PDE Modeler App” on page 4-22.
8 When you solve the PDE, the app automatically plots the solution using the default
settings. To customize the plot or plot other physical properties calculated using the
solution, select Parameters from the Plot menu. See “Plot the Solution in the PDE
Modeler App” on page 4-29.
Tips
After solving the problem, you can:
• Export the solution or the mesh or both to the MATLAB workspace for further analysis.
• Visualize other properties of the solution.
• Change the PDE and recompute the solution.
• Change the mesh and recompute the solution. If you select Initialize Mesh, the mesh
is initialized; if you select Refine Mesh, the current mesh is refined. From the Mesh
menu, you can also jiggle the mesh and undo previous mesh changes. You also can use
the adaptive mesh refiner and solver, adaptmesh. This option tries to find a mesh that
fits the solution.
• Change the boundary conditions. To return to the mode where you can select
boundaries, use the ∂Ω button or the Boundary Mode option from the Boundary
menu.
• Change the geometry. You can switch to the draw mode again by selecting Draw
Mode from the Draw menu or by clicking one of the Draw Mode icons to add another
shape.
The following are the shortcuts that you can use to skip one or more steps. In general, the
PDE Modeler app adds the necessary steps automatically.
• If you do not create a geometry, the PDE Modeler app uses an L-shaped geometry with
the default boundary conditions.
• If you initialize the mesh while in the draw mode, the PDE Modeler app first
decomposes the geometry using the current set formula and assigns the default
boundary condition to the outer boundaries. After that, it generate the mesh.
1-12
See Also
• If you refine the mesh before initializing it, the PDE Modeler app first initializes the
mesh.
• If you solve the PDE without generating a mesh, the PDE Modeler app initializes a
mesh before solving the PDE.
• If you select a plot type and choose to plot the solution, the PDE Modeler app checks if
the solution to the current PDE is available. If not, the PDE Modeler app first solves
the current PDE. The app displays the solution using the selected plot options.
• If do not specify the coefficients and use the default Generic Scalar application mode,
the PDE Modeler app solves the default PDE, which is Poisson's equation:
–Δu = 10.
This corresponds to the generic elliptic PDE with c = 1, a = 0, and f = 10. The default
PDE settings depend on the application mode.
See Also
Related Examples
• “Poisson’s Equation with Complex 2-D Geometry” on page 1-14
• “Poisson's Equation on Unit Disk” on page 3-150
• “Conductive Media DC” on page 3-123
• “Minimal Surface Problem” on page 3-166
1-13
1 Getting Started
To start the PDE Modeler app, type the command pdeModeler at the MATLAB prompt.
The PDE Modeler app looks similar to the following figure, with exception of the grid.
Turn on the grid by selecting Grid from the Options menu. Also, enable the “snap-to-
grid” feature by selecting Snap from the Options menu. The “snap-to-grid” feature
simplifies aligning the solid objects.
1-14
Poisson’s Equation with Complex 2-D Geometry
The first step is to draw the geometry on which you want to solve the PDE. The PDE
Modeler app provides four basic types of solid objects: polygons, rectangles, circles, and
ellipses. The objects are used to create a Constructive Solid Geometry model (CSG
model). Each solid object is assigned a unique label, and by the use of set algebra, the
resulting geometry can be made up of a combination of unions, intersections, and set
differences. By default, the resulting CSG model is the union of all solid objects.
To select a solid object, either click the button with an icon depicting the solid object that
you want to use, or select the object by using the Draw pull-down menu. In this case,
1-15
1 Getting Started
Next, draw a circle by clicking the button with the ellipse icon with the + sign, and then
click-and-drag in a similar way, starting near the point (–.5,0) with radius .4, using the
right mouse button, starting at the circle center.
1-16
Poisson’s Equation with Complex 2-D Geometry
The resulting CSG model is the union of the rectangle R1 and the circle C1, described by
set algebra as R1+C1. The area where the two objects overlap is clearly visible as it is
drawn using a darker shade of gray. The object that you just drew—the circle—has a black
border, indicating that it is selected. A selected object can be moved, resized, copied, and
deleted. You can select more than one object by Shift+clicking the objects that you want
to select. Also, a Select All option is available from the Edit menu.
Finally, add two more objects, a rectangle R2 from (.5,–.6) to (1,1), and a circle C2
centered at (.5,.2) with radius .2. The desired CSG model is formed by subtracting the
circle C2 from the union of the other three objects. You do this by editing the set formula
that by default is the union of all objects: C1+R1+R2+C2. You can type any other valid
1-17
1 Getting Started
set formula into Set formula edit field. Click in the edit field and use the keyboard to
change the set formula to
(R1+C1+R2)-C2
If you want, you can save this CSG model as a file. Use the Save As option from the File
menu, and enter a filename of your choice. It is good practice to continue to save your
model at regular intervals using Save. All the additional steps in the process of modeling
and solving your PDE are then saved to the same file. This concludes the drawing part.
You can now define the boundary conditions for the outer boundaries. Enter the boundary
mode by clicking the ∂Ω icon or by selecting Boundary Mode from the Boundary menu.
You can now remove subdomain borders and define the boundary conditions.
1-18
Poisson’s Equation with Complex 2-D Geometry
The gray edge segments are subdomain borders induced by the intersections of the
original solid objects. Borders that do not represent borders between, e.g., areas with
differing material properties, can be removed. From the Boundary menu, select the
Remove All Subdomain Borders option. All borders are then removed from the
decomposed geometry.
The boundaries are indicated by colored lines with arrows. The color reflects the type of
boundary condition, and the arrow points toward the end of the boundary segment. The
direction information is provided for the case when the boundary condition is
parametrized along the boundary. The boundary condition can also be a function of x and
y, or simply a constant. By default, the boundary condition is of Dirichlet type: u = 0 on
the boundary.
Dirichlet boundary conditions are indicated by red color. The boundary conditions can
also be of a generalized Neumann (blue) or mixed (green) type. For scalar u, however, all
boundary conditions are either of Dirichlet or the generalized Neumann type. You select
the boundary conditions that you want to change by clicking to select one boundary
segment, by Shift+clicking to select multiple segments, or by using the Edit menu option
Select All to select all boundary segments. The selected boundary segments are
indicated by black color.
For this problem, change the boundary condition for all the circle arcs. Select them by
using the mouse and Shift+click those boundary segments.
1-19
1 Getting Started
In the Boundary Condition dialog box, select the Neumann condition type, and enter -5
in the edit box for the boundary condition parameter g. To define a pure Neumann
condition, leave the q parameter at its default value, 0. When you click the OK button,
notice how the selected boundary segments change to blue to indicate Neumann
boundary condition.
1-20
Poisson’s Equation with Complex 2-D Geometry
Next, specify the PDE itself through a dialog box that is accessed by clicking the button
with the PDE icon or by selecting PDE Specification from the PDE menu. In PDE mode,
you can also access the PDE Specification dialog box by double-clicking a subdomain.
That way, different subdomains can have different PDE coefficient values. This problem,
however, consists of only one subdomain.
In the dialog box, you can select the type of PDE (elliptic, parabolic, hyperbolic, or
eigenmodes) and define the applicable coefficients depending on the PDE type. This
problem consists of an elliptic PDE defined by the equation
-— ◊ ( c—u ) + au = f
1-21
1 Getting Started
Finally, create the triangular mesh that Partial Differential Equation Toolbox software
uses in the Finite Element Method (FEM) to solve the PDE. The triangular mesh is
created and displayed when clicking the button with the icon or by selecting the
Mesh menu option Initialize Mesh. If you want a more accurate solution, the mesh can
be successively refined by clicking the button with the four triangle icon (the Refine
button) or by selecting the Refine Mesh option from the Mesh menu.
Using the Jiggle Mesh option, the mesh can be jiggled to improve the triangle quality.
Parameters for controlling the jiggling of the mesh, the refinement method, and other
mesh generation parameters can be found in a dialog box that is opened by selecting
Parameters from the Mesh menu. You can undo any change to the mesh by selecting the
Mesh menu option Undo Mesh Change.
Initialize the mesh, then refine it once and finally jiggle it once.
1-22
Poisson’s Equation with Complex 2-D Geometry
We are now ready to solve the problem. Click the = button or select Solve PDE from the
Solve menu to solve the PDE. The solution is then plotted. By default, the plot uses
interpolated coloring and a linear color map. A color bar is also provided to map the
different shades to the numerical values of the solution. If you want, the solution can be
exported as a vector to the MATLAB main workspace.
1-23
1 Getting Started
There are many more plot modes available to help you visualize the solution. Click the
button with the 3-D solution icon or select Parameters from the Plot menu to access the
dialog box for selection of the different plot options. Several plot styles are available, and
the solution can be plotted in the PDE Modeler app or in a separate figure as a 3-D plot.
1-24
Poisson’s Equation with Complex 2-D Geometry
Now, select a plot where the color and the height both represent u. Choose interpolated
shading and use the continuous (interpolated) height option. The default colormap is the
cool colormap; a pop-up menu lets you select from a number of different colormaps.
Finally, click the Plot button to plot the solution; click the Close button to save the plot
setup as the current default. The solution is plotted as a 3-D plot in a separate figure
window.
The following solution plot is the result. You can use the mouse to rotate the plot in 3-D.
By clicking-and-dragging the axes, the angle from which the solution is viewed can be
changed.
1-25
1 Getting Started
1-26
Finite Element Method Basics
-— ◊ ( c—u ) + au = f on domain W
The first step in FEM is to convert the original differential (strong) form of the PDE into
an integral (weak) form by multiplying with test function v and integrating over the
domain Ω.
The test functions are chosen from a collection of functions (functional space) that vanish
on the Dirichlet portion of the boundary, v = 0 on ∂W D . Above equation can be thought of
as weighted averaging of the residue using all possible weighting functions v . The
collection of functions that are admissible solutions, u, of the weak form of PDE are
chosen so that they satisfy the Dirichlet BC, u = r on ∂W D .
W ∂W N ∂W D W
1-27
1 Getting Started
Use the Neumann boundary condition to substitute for second term on the left side of the
equation. Also, note that v = 0 on ∂W D nullifies the third term. The resulting equation is:
Note that all manipulations up to this stage are performed on continuum Ω, the global
domain of the problem. Therefore, the collection of admissible functions and trial
functions span infinite-dimensional functional spaces. Next step is to discretize the weak
form by subdividing Ω into smaller subdomains or elements W e , where W = »W e . This
step is equivalent to projection of the weak form of PDEs onto a finite-dimensional
subspace. Using the notations uh and vh to represent the finite-dimensional equivalent of
admissible and trial functions defined on W e , you can write the discretized weak form of
the PDE as:
Next, let ϕi, with i = 1, 2, ... , Np, be the piecewise polynomial basis functions for the
subspace containing the collections uh and vh , then any particular uh can be expressed
as a linear combination of basis functions:
Np
uh = Â Uifi
1
Here Ui are yet undetermined scalar coefficients. Substituting uh into to the discretized
weak form of PDE and using each vh = j i as test functions and performing integration
over element yields a system of Np equations in terms of Np unknowns Ui.
Note that finite element method approximates a solution by minimizing the associated
error function. The minimizing process automatically finds the linear combination of basis
functions which is closest to the solution u.
FEM yields a system KU = F where the matrix K and the right side F contain integrals in
terms of the test functions ϕi, ϕj, and the coefficients c, a, f, q, and g defining the problem.
1-28
Finite Element Method Basics
The solution vector U contains the expansion coefficients of uh, which are also the values
of uh at each node xk (k = 1,2 for a 2-D problem or k = 1,2,3 for a 3-D problem) since
uh(xk) = Ui.
FEM techniques are also used to solve more general problems, such as:
∂u
d - — ◊ ( c— u ) + au = f
∂t
can be approximated by
N
uh ( x, t) = Â Ui (t)fi (x)
i =1
dU
M + KU = F
dt
d2U
M + KU = F
dt2
• Eigenvalue problems. Solve
-— ◊ ( c—u ) + au = l du
for the unknowns u and λ, where λ is a complex number. Using the FEM discretization,
you solve the algebraic eigenvalue problem KU = λMU to find uh as an approximation
to u. To solve eigenvalue problems, use solvepdeeig.
• Nonlinear problems. If the coefficients c, a, f, q, or g are functions of u or ∇u, the PDE
is called nonlinear and FEM yields a nonlinear system K(U)U = F(U).
1-29
1 Getting Started
2 For each element, substitutes the original PDE problem by a set of simple equations
that locally approximate the original equations. Applies boundary conditions for
boundaries of each element. For stationary linear problems where the coefficients do
not depend on the solution or its gradient, the result is a linear system of equations.
For stationary problems where the coefficients depend on the solution or its gradient,
the result is a system of nonlinear equations. For time-dependent problems, the result
is a set of ODEs.
3 Assembles the resulting equations and boundary conditions into a global system of
equations that models the entire problem.
4 Solves the resulting system of algebraic equations or ODEs using linear solvers or
numerical integration, respectively. The toolbox internally calls appropriate MATLAB
solvers for this task.
References
[1] Cook, Robert D., David S. Malkus, and Michael E. Plesha. Concepts and Applications of
Finite Element Analysis. 3rd edition. New York, NY: John Wiley & Sons, 1989.
[2] Gilbert Strang and George Fix. An Analysis of the Finite Element Method. 2nd edition.
Wellesley, MA: Wellesley-Cambridge Press, 2008.
See Also
assembleFEMatrices | solvepde | solvepdeeig
1-30
2
2-2
Solve Problems Using Legacy PDEModel Objects
Note THIS PAGE DESCRIBES THE LEGACY WORKFLOW. New features might not be
compatible with the legacy workflow. For the corresponding step in the recommended
workflow, see “Solve Problems Using PDEModel Objects” on page 2-6.
1 Put your problem in the correct form for Partial Differential Equation Toolbox solvers.
For details, see “Equations You Can Solve Using Legacy Functions” on page 1-3. If
you need to convert your problem to divergence form, see “Put Equations in
Divergence Form” on page 2-72.
2 Create a PDEModel model container. For scalar PDEs, use createpde with no
arguments.
model = createpde;
If N is the number of equations in your system, use createpde with input argument
N.
model = createpde(N);
3 Import the geometry into model. For details, see “STL File Import” on page 2-47 or
“Three Ways to Create 2-D Geometry” on page 2-8. For example:
2-3
2 Setting Up Your PDE
f = [1;2];
a = 0;
c = [1;3;5];
generateMesh(model);
9 Call the appropriate solver. For example:
u = assempde(model,c,a,f);
• For elliptic problems whose coefficients do not depend on the solution u, use
assempde.
• For elliptic problems whose coefficients depend on the solution u, use
pdenonlin.
• For parabolic problems, use parabolic.
• For hyperbolic problems, use hyperbolic.
• For eigenvalue problems, use pdeeig.
For definitions of the problems that these solvers address, see “Equations You Can
Solve Using Legacy Functions” on page 1-3.
10 Examine the solution. See “Plot 3-D Solutions and Their Gradients” on page 3-277 or
pdeplot.
2-4
See Also
See Also
applyBoundaryCondition | createpde | generateMesh | geometryFromEdges |
importGeometry | pdegplot | pdeplot | pdeplot3D
2-5
2 Setting Up Your PDE
If N is the number of equations in your system, use createpde with input argument
N.
model = createpde(N);
3 Import or create the geometry. For details, see “STL File Import” on page 2-47 or
“Three Ways to Create 2-D Geometry” on page 2-8.
importGeometry(model,'geometry.stl'); % importGeometry for 3-D
geometryFromEdges(model,g); % geometryFromEdges for 2-D
4 View the geometry so that you know the labels of the boundaries.
pdegplot(model,'FaceLabels','on') % 'FaceLabels' for 3-D
pdegplot(model,'EdgeLabels','on') % 'EdgeLabels' for 2-D
To see labels of a 3-D model, you might need to rotate the model, or make it
transparent, or zoom in on it. See “STL File Import” on page 2-47.
5 Create the boundary conditions. For details, see “Specify Boundary Conditions” on
page 2-181.
% 'face' for 3-D
applyBoundaryCondition(model,'dirichlet','face',[2,3,5],'u',[0,0]);
% 'edge' for 2-D
applyBoundaryCondition(model,'neumann','edge',[1,4],'g',1,'q',eye(2));
2-6
See Also
generateMesh(model);
9 Call the appropriate solver. For all problems except for eigenvalue problems, call
solvepde.
result = solvepdeeig(model);
10 Examine the solution. See “Plot 2-D Solutions and Their Gradients” on page 3-266
and “Plot 3-D Solutions and Their Gradients” on page 3-277.
See Also
applyBoundaryCondition | createpde | generateMesh | geometryFromEdges |
importGeometry | pdegplot | pdeplot | pdeplot3D
Related Examples
• “Plot 3-D Solutions and Their Gradients” on page 3-277
2-7
2 Setting Up Your PDE
• Use the PDE Modeler app to draw basic shapes (rectangles, circles, ellipses, and
polygons) and combine them with set intersection and unions to obtain the final
geometry. You can then export the geometry to your MATLAB workspace, or continue
to work in the app. For details, see “2-D Geometry Creation in PDE Modeler App” on
page 4-3.
• Use the decsg function to create geometry at the command line as follows:
• Specify matrices that represent the basic shapes (rectangles, circles, ellipses, and
polygons).
• Give each shape a label.
• Specify a “set formula” that describes the intersections, unions, and set differences
of the basic shapes.
decsg allows you to describe any geometry that you can make from the basic shapes
(rectangles, circles, ellipses, and polygons). For details, see “2-D Geometry Creation at
Command Line” on page 2-10.
• Specify a function that describes the geometry. The function must be in the form
described in “Parametrized Function for 2-D Geometry Creation” on page 2-17.
2-8
Three Ways to Create 2-D Geometry
2-9
2 Setting Up Your PDE
To describe your geometry through Constructive Solid Geometry (CSG) modeling, use
three data structures.
1 A matrix whose columns describe the basic shapes. When you export geometry from
the PDE Modeler app, this matrix has the default name gd (geometry description).
See “Create Basic Shapes” on page 2-10.
2 A matrix whose columns contain names for the basic shapes. Pad the columns with
zeros or 32 (blanks) so that every column has the same length. See “Create Names
for the Basic Shapes” on page 2-12.
3 A set of characters describing the unions, intersections, and set differences of the
basic shapes that make the geometry. See “Set Formula” on page 2-13.
Circle
Row Value
1 1 (indicates a circle)
2 x-coordinate of circle center
3 y-coordinate of circle center
4 Radius (strictly positive)
2-10
2-D Geometry Creation at Command Line
Polygon
Row Value
1 2 (indicates a polygon)
2 Number of line segments n
3 through 3+n-1 x-coordinate of edge starting points
3+n through 2*n+2 y-coordinate of edge starting points
Note Your polygon cannot contain any self-intersections. To check whether your polygon
satisfies this restriction, use the csgchk function.
Rectangle
Row Value
1 3 (indicates a rectangle)
2 4 (number of line segments)
3 through 6 x-coordinate of edge starting points
7 through 10 y-coordinate of edge starting points
The encoding of a rectangle is the same as that of a polygon, except that the first row is 3
instead of 2.
Ellipse
Row Value
1 4 (indicates an ellipse)
2 x-coordinate of ellipse center
3 y-coordinate of ellipse center
4 First semiaxis length (strictly positive)
5 Second semiaxis length (strictly positive)
6 Angle in radians from x axis to first semiaxis
For example, specify a matrix that has a rectangle with a circular end cap and another
circular excision. First, create a rectangle and two adjoining circles.
2-11
2 Setting Up Your PDE
rect1 = [3
4
-1
1
1
-1
0
0
-0.5
-0.5];
C1 = [1
1
-0.25
0.25];
C2 = [1
-1
-0.25
0.25];
Append extra zeros to the circles so they have the same number of rows as the rectangle.
C1 = [C1;zeros(length(rect1) - length(C1),1)];
C2 = [C2;zeros(length(rect1) - length(C2),1)];
gd = [rect1,C1,C2];
One easy way to create the names is by specifying a character array whose rows contain
the names, and then taking the transpose. Use the char function to create the array.
char pads the rows as needed so all have the same length. Continuing the example, give
names for the three shapes.
ns = char('rect1','C1','C2');
ns = ns';
2-12
2-D Geometry Creation at Command Line
Set Formula
Obtain the final geometry by writing a set of characters that describes the unions and
intersections of basic shapes. Use + for union, * for intersection, - for set difference, and
parentheses for grouping. + and * have the same grouping precedence. - has higher
grouping precedence.
Continuing the example, specify the union of the rectangle and C1, and subtract C2.
sf = '(rect1+C1)-C2';
[dl,bt] = decsg(gd,sf,ns);
pdegplot(dl,'EdgeLabels','on','FaceLabels','on')
xlim([-1.5,1.5])
axis equal
2-13
2 Setting Up Your PDE
2-14
2-D Geometry Creation at Command Line
2-15
2 Setting Up Your PDE
2-16
Parametrized Function for 2-D Geometry Creation
Required Syntax
For basic information on creating a 2-D geometry, see “Three Ways to Create 2-D
Geometry” on page 2-8.
A geometry function describes the curves that bound the geometry regions. A curve is a
parametrized function (x(t),y(t)). The variable t ranges over a fixed interval. For best
results, t must be proportional to the arc length plus a constant.
You must specify at least two curves for each geometric region. For example, the
'circleg' geometry function, which is available in Partial Differential Equation Toolbox,
uses four curves to describe a circle. Curves can intersect only at the beginning or end of
parameter intervals.
2-17
2 Setting Up Your PDE
• The arrows by curves 1 and 2 show region 1 to the left and region 0 to the right.
• The arrows by curves 3 and 4 show region 0 to the left and region 1 to the right.
• The arrows by curves 5 and 6 show region 0 to the left and region 1 to the right.
• The arrows by curves 7 and 8 show region 1 to the left and region 0 to the right.
2-18
Parametrized Function for 2-D Geometry Creation
A geometry function must have at least two segments. To satisfy this requirement, break
up the circle into four segments.
2-19
2 Setting Up Your PDE
•
•
•
Now that you have a parametrization, write the geometry function. Save this function file
as circlefunction.m on your MATLAB® path. This geometry is simple to create
because the parametrization does not change depending on the segment number.
Plot the geometry displaying the edge numbers and the face label.
pdegplot(@circlefunction,'EdgeLabels','on','FaceLabels','on')
axis equal
2-20
Parametrized Function for 2-D Geometry Creation
ezpolar('2*(1+cos(Phi))')
2-21
2 Setting Up Your PDE
The following are the four ways to parametrize the cardioid as a function of the arc
length:
• Use the pdearcl function with a polygonal approximation to the geometry. This
approach is general, accurate enough, and computationally fast.
• Use the integral and fzero functions to compute the arc length. This approach is more
computationally costly, but can be accurate without requiring you to choose an
arbitrary polygon.
• Use an analytic calculation of the arc length. This approach is the best when it applies,
but there are many cases where it does not apply.
2-22
Parametrized Function for 2-D Geometry Creation
• Use a parametrization that is not proportional to the arc length plus a constant. This
approach is the simplest, but can yield a distorted mesh that does not give the most
accurate solution to your PDE problem.
Polygonal Approximation
The finite element method uses a triangular mesh to approximate the solution to a PDE
numerically. You can avoid loss in accuracy by taking a sufficiently fine polygonal
approximation to the geometry. The pdearcl function maps between parametrization and
arc length in a form well suited to a geometry function. Write the following geometry
function for the cardioid.
function [x,y] = cardioid1(bs,s)
% CARDIOID1 Geometry file defining the geometry of a cardioid.
if nargin == 0
x = 4; % four segments in boundary
return
end
if nargin == 1
dl = [0 pi/2 pi 3*pi/2
pi/2 pi 3*pi/2 2*pi
1 1 1 1
0 0 0 0];
x = dl(:,bs);
return
end
x = zeros(size(s));
y = zeros(size(s));
if numel(bs) == 1 % bs might need scalar expansion
bs = bs*ones(size(s)); % expand bs
end
2-23
2 Setting Up Your PDE
y(:) = r.*sin(th);
end
pdegplot('cardioid1','EdgeLabels','on')
axis equal
The built-in cardg function gives a slightly different version of this technique.
2-24
Parametrized Function for 2-D Geometry Creation
You can write an integral for the arc length of a curve. If the parametrization is in terms
of and , then the arc length is
For a given value , you can find as the root of the equation . The fzero
function solves this type of nonlinear equation.
if nargin == 0
x = 4; % four segments in boundary
return
end
if nargin == 1
dl = [0 pi/2 pi 3*pi/2
pi/2 pi 3*pi/2 2*pi
1 1 1 1
0 0 0 0];
x = dl(:,bs);
return
end
x = zeros(size(s));
y = zeros(size(s));
if numel(bs) == 1 % bs might need scalar expansion
bs = bs*ones(size(s)); % expand bs
end
2-25
2 Setting Up Your PDE
x(ii) = r*cos(theta);
y(ii) = r*sin(theta);
end
cbs = find(bs >= 3); % lower half of cardioid
s(cbs) = 2*pi - s(cbs);
for ii = cbs(:)'
theta = fzero(@(rr)fun(rr)-s(ii)*sscale/pi,[0,pi]);
r = 2*(1 + cos(theta));
x(ii) = r*cos(theta);
y(ii) = -r*sin(theta);
end
end
pdegplot('cardioid2','EdgeLabels','on')
axis equal
2-26
Parametrized Function for 2-D Geometry Creation
The geometry looks identical to the polygonal approximation. This integral version takes
much longer to calculate than the polygonal version.
You also can find an analytic expression for the arc length as a function of the
parametrization. Then you can give the parametrization in terms of arc length. For
example, find an analytic expression for the arc length by using Symbolic Math Toolbox™.
syms t real
r = 2*(1+cos(t));
x = r*cos(t);
y = r*sin(t);
2-27
2 Setting Up Your PDE
arcl = simplify(sqrt(diff(x)^2+diff(y)^2));
s = int(arcl,t,0,t,'IgnoreAnalyticConstraints',true)
s =
8*sin(t/2)
In terms of the arc length s, the parameter t is t = 2*asin(s/8), where s ranges from
0 to 8, corresponding to t ranging from 0 to . For s between 8 and 16, by symmetry of
the cardioid, t = pi + 2*asin((16-s)/8). Furthermore, you can express x and y in
terms of s by these analytic calculations.
syms s real
th = 2*asin(s/8);
r = 2*(1 + cos(th));
r = expand(r)
r =
4 - s^2/16
x = r*cos(th);
x = simplify(expand(x))
x =
s^4/512 - (3*s^2)/16 + 4
y = r*sin(th);
y = simplify(expand(y))
y =
(s*(64 - s^2)^(3/2))/512
Now that you have analytic expressions for x and y in terms of the arc length s, write the
geometry function.
2-28
Parametrized Function for 2-D Geometry Creation
if nargin == 0
x = 4; % four segments in boundary
return
end
if nargin == 1
dl = [0 4 8 12
4 8 12 16
1 1 1 1
0 0 0 0];
x = dl(:,bs);
return
end
x = zeros(size(s));
y = zeros(size(s));
if numel(bs) == 1 % bs might need scalar expansion
bs = bs*ones(size(s)); % expand bs
end
pdegplot('cardioid3','EdgeLabels','on')
axis equal
2-29
2 Setting Up Your PDE
This analytic geometry looks slightly smoother than the previous versions. However, the
difference is inconsequential in terms of calculations.
You also can write a geometry function where the parameter is not proportional to the arc
length. This approach can yield a distorted mesh.
if nargin == 0
x = 4; % four segments in boundary
2-30
Parametrized Function for 2-D Geometry Creation
return
end
if nargin == 1
dl = [0 pi/2 pi 3*pi/2
pi/2 pi 3*pi/2 2*pi
1 1 1 1
0 0 0 0];
x = dl(:,bs);
return
end
pdegplot('cardioid4','EdgeLabels','on')
axis equal
2-31
2 Setting Up Your PDE
The labels are not evenly spaced on the edges because the parameter is not proportional
to the arc length.
Examine the default mesh for each of the four methods of creating a geometry.
subplot(2,2,1)
model = createpde;
geometryFromEdges(model,@cardioid1);
generateMesh(model);
pdeplot(model)
title('Polygons')
axis equal
subplot(2,2,2)
2-32
Parametrized Function for 2-D Geometry Creation
model = createpde;
geometryFromEdges(model,@cardioid2);
generateMesh(model);
pdeplot(model)
title('Integral')
axis equal
subplot(2,2,3)
model = createpde;
geometryFromEdges(model,@cardioid3);
generateMesh(model);
pdeplot(model)
title('Analytic')
axis equal
subplot(2,2,4)
model = createpde;
geometryFromEdges(model,@cardioid4);
generateMesh(model);
pdeplot(model)
title('Distorted')
axis equal
2-33
2 Setting Up Your PDE
The distorted mesh looks a bit less regular than the other meshes. It has some very
narrow triangles near the cusp of the cardioid. Nevertheless, all of the meshes appear to
be usable.
2-34
Parametrized Function for 2-D Geometry Creation
has a circular hole centered at (1,-1) and of radius 1/2. The following is the code of the
geometry function.
2-35
2 Setting Up Your PDE
x(cbs) = s(cbs);
y(cbs) = zeros(size(cbs));
cbs = find(bs > 5); % Inner circle radius 0.25 center (1,-1)
x(cbs) = 1 + 0.25*cos(s(cbs));
y(cbs) = -1 + 0.25*sin(s(cbs));
end
pdegplot(@cardg3,'EdgeLabels','on','FaceLabels','on')
axis equal
2-36
Parametrized Function for 2-D Geometry Creation
When a 2-D geometry function requires additional parameters, you cannot use a standard
anonymous function approach because geometry functions return a varying number of
arguments. Instead, you can use global variables or nested functions. In most cases, the
recommended approach is to use nested functions.
The example solves a Poisson's equation with zero Dirichlet boundary conditions on all
boundaries. The geometry is a cardioid with an elliptic hole that has a center at (1,-1) and
2-37
2 Setting Up Your PDE
variable semiaxes. To set up and solve the PDE model with this geometry, use a nested
function. Here, the parent function accepts the lengths of the semiaxes, rr and ss, as
input parameters. The reason to nest cardioidWithEllipseGeom within
cardioidWithEllipseModel is that nested functions share the workspace of their
parent functions. Therefore, the cardioidWithEllipseGeom function can access the
values of rr and ss that you pass to cardioidWithEllipseModel.
function cardioidWithEllipseModel(rr,ss)
applyBoundaryCondition(model,'dirichlet','Edge',1:8,'u',0);
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',0,'f',1);
generateMesh(model);
u = solvepde(model);
figure
pdeplot(model,'XYData',u.NodalSolution)
axis equal
else
display('Semiaxes values must be positive numbers.')
end
if nargin == 0
x = 8; % eight segments in boundary
return
end
if nargin == 1
% Cardioid
dlc = [ 0 4 8 12
4 8 12 16
1 1 1 1
0 0 0 0];
% Ellipse
dle = [0 pi/2 pi 3*pi/2
pi/2 pi 3*pi/2 2*pi
0 0 0 0
2-38
Parametrized Function for 2-D Geometry Creation
1 1 1 1];
% Combine the edge matrices
dl = [dlc,dle];
x = dl(:,bs);
return
end
x = zeros(size(s));
y = zeros(size(s));
if numel(bs) == 1 % Does bs need scalar expansion?
bs = bs*ones(size(s)); % Expand bs
end
end
end
When calling cardioidWithEllipseModel, ensure that the semiaxes values are small
enough, so that the elliptic hole appears entirely within the outer cardioid. Otherwise, the
geometry becomes invalid.
For example, call the function for the ellipse with the major semiaxis rr = 0.5 and the
minor semiaxis ss = 0.25. This function call returns the following geometry and the
solution.
cardioidWithEllipseModel(0.5,0.25)
2-39
2 Setting Up Your PDE
2-40
Parametrized Function for 2-D Geometry Creation
2-41
2 Setting Up Your PDE
t = pi/12:pi/12:2*pi;
pgon = polyshape({[-0.5 -0.5 0.5 0.5], 0.25*cos(t)}, ...
{[0.5 -0.5 -0.5 0.5], 0.25*sin(t)})
pgon =
polyshape with properties:
plot(pgon)
axis equal
2-42
Geometry from polyshape
tr = triangulation(pgon);
model = createpde;
With the triangulation data as a mesh, use the geometryFromMesh function to create a
geometry. Plot the geometry.
tnodes = tr.Points';
telements = tr.ConnectivityList';
2-43
2 Setting Up Your PDE
geometryFromMesh(model,tnodes,telements);
pdegplot(model)
figure
pdemesh(model)
2-44
Geometry from polyshape
Because the triangulation data resulted in a low-quality mesh, generate a new finer mesh
for further analysis.
generateMesh(model)
ans =
FEMesh with properties:
2-45
2 Setting Up Your PDE
GeometricOrder: 'quadratic'
figure
pdemesh(model)
2-46
STL File Import
View the geometry examples included with Partial Differential Equation Toolbox.
model = createpde;
importGeometry(model,'Torus.stl');
pdegplot(model,'FaceLabels','on')
2-47
2 Setting Up Your PDE
model = createpde;
importGeometry(model,'Block.stl');
pdegplot(model,'FaceLabels','on')
model = createpde;
importGeometry(model,'Plate10x10x1.stl');
pdegplot(model,'FaceLabels','on')
2-48
STL File Import
model = createpde;
importGeometry(model,'Tetrahedron.stl');
pdegplot(model,'FaceLabels','on')
2-49
2 Setting Up Your PDE
model = createpde;
importGeometry(model,'BracketWithHole.stl');
pdegplot(model,'FaceLabels','on')
2-50
STL File Import
model = createpde;
importGeometry(model,'BracketTwoHoles.stl');
pdegplot(model,'FaceLabels','on')
2-51
2 Setting Up Your PDE
To see hidden portions of the geometry, rotate the figure using the Rotate 3D button
. You can rotate the angle bracket to obtain the following view.
2-52
STL File Import
model = createpde;
importGeometry(model,'ForearmLink.stl');
pdegplot(model,'FaceLabels','on');
2-53
2 Setting Up Your PDE
To view hidden faces, set FaceAlpha to a value less than 1, such as 0.5.
pdegplot(model,'FaceLabels','on','FaceAlpha',0.5)
2-54
STL File Import
When you import a planar STL geometry, the toolbox converts it to a 2-D geometry by
mapping it to the X-Y plane.
model = createpde;
importGeometry(model,'PlateHolePlanar.stl');
pdegplot(model,'EdgeLabels','on')
2-55
2 Setting Up Your PDE
2-56
Geometry from Triangulated Mesh
The tetmesh file that ships with your software contains a 3-D mesh. Load the data into
your Workspace.
load tetmesh
size(tet)
ans = 1×2
4969 4
size(X)
ans = 1×2
1456 3
nodes = X';
elements = tet';
model = createpde();
geometryFromMesh(model,nodes,elements);
model.Mesh
2-57
2 Setting Up Your PDE
ans =
FEMesh with properties:
2-58
Geometry from Triangulated Mesh
load MultidomainMesh2D
model = createpde;
geometryFromMesh(model,nodes,elements,ElementIdToRegionId);
pdegplot(model,'FaceLabels','on')
2-59
2 Setting Up Your PDE
2-60
Geometry from alphaShape
Create a unit disk. Remove all the mesh grid points that fall inside the unit disk, and
include the unit disk points.
t = (pi/24:pi/24:2*pi)';
x = cos(t);
y = sin(t);
circShp = alphaShape(x,y,2);
in = inShape(circShp,xg,yg);
xg = [xg(~in); cos(t)];
yg = [yg(~in); sin(t)];
Create 3-D copies of the remaining mesh grid points, with the z-coordinates ranging from
0 through 1. Combine the points into an alphaShape object.
zg = ones(numel(xg),1);
xg = repmat(xg,5,1);
yg = repmat(yg,5,1);
zg = zg*(0:.25:1);
zg = zg(:);
shp = alphaShape(xg,yg,zg);
[elements,nodes] = boundaryFacets(shp);
nodes = nodes';
elements = elements';
2-61
2 Setting Up Your PDE
model = createpde();
geometryFromMesh(model,nodes,elements);
pdegplot(model,'FaceLabels','on','FaceAlpha',0.5)
generateMesh(model);
2-62
Cuboids, Cylinders, and Spheres
All cells in a geometry must be of the same type: either cuboids, or cylinders, or spheres.
These functions do not combine cells of different types in one geometry.
Single Sphere
Create a geometry that consists of a single sphere and include this geometry in a PDE
model.
Use the multisphere function to create a single sphere. The resulting geometry consists
of one cell.
gm = multisphere(5)
gm =
DiscreteGeometry with properties:
NumCells: 1
NumFaces: 1
NumEdges: 0
NumVertices: 0
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
2-63
2 Setting Up Your PDE
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
pdegplot(model,'CellLabels','on')
2-64
Cuboids, Cylinders, and Spheres
Create the geometry by using the multicuboid function. The resulting geometry
consists of three cells.
gm =
DiscreteGeometry with properties:
2-65
2 Setting Up Your PDE
NumCells: 3
NumFaces: 18
NumEdges: 36
NumVertices: 24
model = createpde
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
pdegplot(model,'CellLabels','on','FaceAlpha',0.5)
2-66
Cuboids, Cylinders, and Spheres
Stacked Cylinders
Create a geometry that consists of three stacked cylinders and include this geometry in a
PDE model.
Create the geometry by using the multicylinder function with the ZOffset argument.
The resulting geometry consists of four cells stacked on top of each other.
gm =
DiscreteGeometry with properties:
2-67
2 Setting Up Your PDE
NumCells: 4
NumFaces: 9
NumEdges: 5
NumVertices: 5
model = createpde
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
pdegplot(model,'CellLabels','on','FaceAlpha',0.5)
2-68
Cuboids, Cylinders, and Spheres
Hollow Cylinder
Create a hollow cylinder and include it as a geometry in a PDE model.
Create a hollow cylinder by using the multicylinder function with the Void argument.
The resulting geometry consists of one cell.
gm = multicylinder([9 10],10,'Void',[true,false])
gm =
DiscreteGeometry with properties:
NumCells: 1
2-69
2 Setting Up Your PDE
NumFaces: 4
NumEdges: 4
NumVertices: 4
model = createpde
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
pdegplot(model,'CellLabels','on','FaceAlpha',0.5)
2-70
Cuboids, Cylinders, and Spheres
2-71
2 Setting Up Your PDE
In this section...
“Coefficient Matching for Divergence Form” on page 2-72
“Boundary Conditions Can Affect the c Coefficient” on page 2-73
“Some Equations Cannot Be Converted” on page 2-74
-— ◊ ( c—u ) + au = f
or variants that have derivatives with respect to time, or that have eigenvalues, or are
systems of equations. These equations are in divergence form, where the differential
operator begins —· . The coefficients a, c, and f are functions of position (x, y, z) and
possibly of the solution u.
However, you can have equations in a form with all the derivatives explicitly expanded,
such as
∂ 2u (1 + y ) ∂ 2u
2 2
(1 + x2 ) ∂ u
- 3 xy + =0
∂x2 ∂ x∂ y 2 ∂y2
In order to transform this expanded equation into toolbox format, you can try to match
the coefficients of the equation in divergence form to the expanded form. In divergence
form, if
Êc c3 ˆ
c=Á 1 ˜
Ë c2 c4 ¯
then
2-72
Put Equations in Divergence Form
Matching coefficients in the uxx and uyy terms in -— ◊ ( c—u ) to the equation, you get
c1 = - ( 1 + x2 )
c4 = - ( 1 + y2 ) / 2
Then looking at the coefficients of ux and uy, which should be zero, you get
Ê ∂c1 ∂ c2 ˆ ∂c2
Á + ˜ = -2 x +
Ë ∂x ∂y ¯ ∂y
so
c2 = 2 xy.
Ê ∂c3 ∂c4 ˆ ∂c3
Á + ˜= -y
Ë ∂x ∂ y ¯ ∂x
so
c3 = xy
-— ◊ ( c—u ) = 0
n ·( c— u) + qu = g
r
So when you derive a divergence form of the c coefficient, keep in mind that this
coefficient appears elsewhere.
2-73
2 Setting Up Your PDE
For example, consider the 2-D Poisson equation –uxx – uyy = f. Obviously, you can take
c = 1. But there are other c matrices that lead to the same equation: any that have
c(2) + c(3) = 0.
Ê Ê c c ˆ Ê ux ˆ ˆ
— ·( c— u ) = — · Á Á 1 3 ˜ ÁÁ ˜˜ ˜
Á c c u ˜
ËË 2 4 ¯ Ë y ¯ ¯
∂ ∂
= ( c1ux + c3 uy ) + ( c2 ux + c4 uy )
∂x ∂y
= c1uxx + c4u yy + ( c2 + c3 ) uxy
n ·( c— u) = 2
r
the boundary condition depends on which version of c you use. In this case, make sure
that you take a version of c that is compatible with both the equation and the boundary
condition.
-— ◊ ( c—u ) + au = f
∂2 u cos( x + y) ∂ 2u 1 ∂ 2u
+ + =0
∂x2 4 ∂x∂y 2 ∂ y2
By simple coefficient matching, you see that the coefficients c1 and c4 are –1 and –1/2
respectively. However, there are no c2 and c3 that satisfy the remaining equations,
2-74
See Also
- cos( x + y)
c2 + c3 =
4
∂ c1 ∂c2 ∂c2
+ = =0
∂x ∂y ∂y
∂ c3 ∂ c4 ∂c3
+ = =0
∂x ∂y ∂x
See Also
Related Examples
• “Equations You Can Solve Using PDE Toolbox” on page 1-6
• “Solve Problems Using PDEModel Objects” on page 2-6
2-75
2 Setting Up Your PDE
Note THIS PAGE DESCRIBES THE LEGACY WORKFLOW. New features might not be
compatible with the legacy workflow. For the corresponding step in the recommended
workflow, see the recommended examples on the “PDE Coefficients” page.
• 'x' — x-coordinate
• 'y' — y-coordinate
• 'z' — z-coordinate (3-D geometry)
• 'u' — Solution of equation
• 'ux' — Derivative of u in the x-direction
• 'uy' — Derivative of u in the y-direction
• 'uz' — Derivative of u in the z-direction (3-D geometry)
• 't' — Time (parabolic and hyperbolic equations)
• 'sd' — Subdomain number (not used in 3-D geometry)
For example, you could use this vector of characters to represent a coefficient:
Note Use .*, ./, and .^ for multiplication, division, and exponentiation operations. The
text expressions operate on row vectors, so the operations must make sense for row
vectors. For 2-D geometry, the row vectors are the values at the triangle centroids in the
mesh.
You can write MATLAB functions for coefficients as well as plain text expressions. For
example, suppose your coefficient f is given by the file fcoeff.m:
function f = fcoeff(x,y,t,sd)
2-76
Specify Scalar PDE Coefficients in Character Form
u1 = parabolic(u0,tlist,b,p,e,t,c,a,'fcoeff(x,y,t,sd)',d)
Caution In function form, t represents triangles, and time represents time. In character
form, t represents time, and triangles do not enter into the form.
There is a simple way to write a text expression for multiple subdomains without using
'sd' or a function. Separate the formulas for the different subdomains with the '!'
character. Generally use the same number of expressions as subdomains. However, if an
expression does not depend on the subdomain number, you can give just one expression.
The coefficient c is a 2-by-2 matrix. You can give c in any of the following forms:
Ê c 0ˆ
Á ˜
Ë0 c¯
• Two-element column vector or two-row text array — The software interprets c as a
diagonal matrix:
Ê c(1) 0 ˆ
Á ˜
Ë 0 c(2) ¯
• Three-element column vector or three-row text array — The software interprets c as a
symmetric matrix:
Ê c(1) c(2) ˆ
Á ˜
Ë c(2) c(3) ¯
• Four-element column vector or four-row text array — The software interprets c as a
full matrix:
2-77
2 Setting Up Your PDE
Ê c(1) c( 3) ˆ
Á ˜
Ë c(2) c(4 ) ¯
c = char('x.^2+y.^2',...
'cos(x.*y)',...
'u./(1+x.^2+y.^2)')
To include subdomains separated by '!', include the '!' in each row. For example,
Caution Do not use spaces when specifying coefficients in the PDE Modeler app. The
parser can misinterpret a space as a vector separator, as when a MATLAB vector uses a
space to separate elements of a vector.
For elliptic problems, when you include 'u', 'ux', 'uy', or 'uz', you must use the
pdenonlin solver instead of assempde. In the PDE Modeler app, select Solve >
Parameters > Use nonlinear solver.
2-78
Coefficients for Scalar PDEs in PDE Modeler App
• x — x-coordinate
• y — y-coordinate
• u — Solution of equation
• ux — Derivative of u in the x-direction
• uy — Derivative of u in the y-direction
• t — Time (parabolic and hyperbolic equations)
• sd — Subdomain number
For elliptic problems, when you include u, ux, or uy, you must use the nonlinear solver.
Select Solve > Parameters > Use nonlinear solver.
Note
2-79
2 Setting Up Your PDE
• Do not use quotes or unnecessary spaces in your entries. The parser can misinterpret
a space as a vector separator, as when a MATLAB vector uses a space to separate
elements of a vector.
• Use .*, ./, and .^ for multiplication, division, and exponentiation operations. The text
expressions operate on row vectors, so the operations must make sense for row
vectors. The row vectors are the values at the triangle centroids in the mesh.
You can write MATLAB functions for coefficients as well as plain text expressions. For
example, suppose your coefficient f is given by the file fcoeff.m.
function f = fcoeff(x,y,t,sd)
The coefficient c is a 2-by-2 matrix. You can give 1-, 2-, 3-, or 4-element matrix
expressions. Separate the expressions for elements by spaces. These expressions mean:
•
Ê c 0ˆ
1-element expression: Á ˜
Ë0 c¯
•
Ê c(1) 0 ˆ
2-element expression: Á ˜
Ë 0 c(2) ¯
2-80
See Also
•
Ê c(1) c(2) ˆ
3-element expression: Á ˜
Ë c(2) c(3) ¯
•
Ê c(1) c( 3) ˆ
4-element expression: Á ˜
Ë c(2) c(4 ) ¯
For example, c is a symmetric matrix with constant diagonal entries and cos(xy) as the
off-diagonal terms:
∂u Ê Ê 1 .1 cos( xy) ˆ ˆ
- —·Á Á ˜ —u ˜ = 10 .
∂t Ë Ë cos( xy) 5 .5 ¯ ¯
See Also
Related Examples
• “Enter Coefficients in the PDE Modeler App” on page 2-93
2-81
2 Setting Up Your PDE
Note THIS PAGE DESCRIBES THE LEGACY WORKFLOW. New features might not be
compatible with the legacy workflow. For the corresponding step in the recommended
workflow, see the recommended examples on the “PDE Coefficients” page.
coeff = coeffunction(p,t,u,time)
Your program evaluates the return coeff as a row vector of the function values at the
centroids of the triangles t. For help calculating these values, see “Calculate Coefficients
in Function Form” on page 2-83.
• p and t are the node points and triangles of the mesh. For a description of these data
structures, see “Mesh Data” on page 2-241. In brief, each column of p contains the x-
and y-values of a point, and each column of t contains the indices of three points in p
and the subdomain label of that triangle.
• u is a row vector containing the solution at the points p. u is [] if the coefficients do
not depend on the solution or its derivatives.
• time is the time of the solution, a scalar. time is [] if the coefficients do not depend
on time.
Caution In function form, t represents triangles, and time represents time. In character
form, t represents time, and triangles do not enter into the form.
2-82
Specify 2-D Scalar Coefficients in Function Form
If your coefficients depend on u or time, then when u or time are NaN, ensure that the
corresponding coeff consist of a vector of NaN of the correct size. This signals to solvers,
such as parabolic, to use a time-dependent or solution-dependent algorithm.
For elliptic problems, if any coefficient depends on u or its gradient, you must use the
pdenonlin solver instead of assempde. In the PDE Modeler app, select Solve >
Parameters > Use nonlinear solver.
The x- and y-values of the centroid of a triangle t are the mean values of the entries of the
points p in t. To get row vectors xpts and ypts containing the mean values:
Interpolated u
The pdeintrp function linearly interpolates the values of u at the centroids of t, based
on the values at the points p.
The output uintrp is a row vector with the same number of columns as t. Use uintrp
as the solution value in your coefficient calculations.
Gradient or Derivatives of u
2-83
2 Setting Up Your PDE
The outputs ux and uy are row vectors with the same number of columns as t.
Subdomains
If your coefficients depend on the subdomain label, check the subdomain number for each
triangle. Subdomains are the last (fourth) row of the triangle matrix. So the row vector of
subdomain numbers is:
subd = t(4,:);
You can see the subdomain labels by using the pdegplot function with the
SubdomainLabels name-value pair set to 'on':
pdegplot(g,'SubdomainLabels','on')
2-84
Specify 3-D PDE Coefficients in Function Form
Note THIS PAGE DESCRIBES THE LEGACY WORKFLOW. New features might not be
compatible with the legacy workflow. For the corresponding step in the recommended
workflow, see the recommended examples on the “PDE Coefficients” page.
Usually, the simplest way to give coefficients as the result of a program is to use a
character expression. For this approach, see “Specify Scalar PDE Coefficients in
Character Form” on page 2-76. For more detailed control over coefficients, though, you
can write coefficients in function form.
coeff = myfun(location,state)
• location.x
• location.y
• location.z
The fields represent the x-, y-, and z- coordinates of points for which your function
calculates coefficient values. The location fields are row vectors.
• state is a structure with these fields:
• state.u
• state.ux
• state.uy
• state.uz
• state.t
The state.u field represents the current value of the solution u. The state.ux,
state.uy, and state.uz fields are estimates of the solution’s partial derivatives (∂u/
∂x, ∂u/∂y, and ∂u/∂z) at the corresponding points of the location structure. The solution
2-85
2 Setting Up Your PDE
and gradient estimates are row vectors. The state.t field is a scalar representing
time for the parabolic and hyperbolic solvers.
Your function must compute in a vectorized fashion. In other words, it must return the
matrix of values for every point in location. For example, in an N = 1 problem where
the f coefficient is 1 + x2, one possible function is:
fcoeff = 1 + location.x.^2;
To pass this coefficient to the parabolic solver, set the coefficient to @ffunction. For
example:
f = @ffunction;
% Assume the other inputs are defined
u = parabolic(u0,tlist,model,c,a,f,d);
If you need a constant value, use the size of location.x as the number of columns of the
matrix. For an N = 3 problem:
fcoeff = ones(3,length(location.x));
2-86
Solve PDE with Coefficients in Functional Form
Note THIS PAGE DESCRIBES THE LEGACY WORKFLOW. New features might not be
compatible with the legacy workflow. For the corresponding step in the recommended
workflow, see the recommended examples on the “PDE Coefficients” page.
This example shows how to write PDE coefficients in character form and in functional
form for 2-D geometry.
Geometry
The geometry is a rectangle with a circular hole. Create a PDE model container, and
incorporate the geometry into the container.
model = createpde(1);
2-87
2 Setting Up Your PDE
PDE Coefficients
The PDE is parabolic,
• d=5
• a=0
2-88
Solve PDE with Coefficients in Functional Form
Boundary Conditions
The boundary conditions on the outer boundary (segments 1 through 4) are Dirichlet,
with the value , where is time. Suppose the circular boundary
(segments 5 through 8) has a generalized Neumann condition, with and
.
myufun = @(region,state)state.time*(region.x - region.y);
mygfun = @(region,state)(region.x.^2 + region.y.^2);
applyBoundaryCondition(model,'edge',1:4,'u',myufun,'Vectorized','on');
applyBoundaryCondition(model,'edge',5:8,'q',1,'g',mygfun,'Vectorized','on');
The boundary conditions are the same as in “Boundary Conditions for Scalar PDE” on
page 2-204. That description uses the older function form for specifying boundary
conditions, which is no longer recommended. This description uses the recommended
object form.
Initial Conditions
2-89
2 Setting Up Your PDE
u0 = 0;
Mesh
Create the mesh.
generateMesh(model,'GeometricOrder','linear');
tlist = linspace(0,1,50);
Solution
Solve the parabolic PDE.
d = 5;
a = 0;
f = 'framp(t)';
c = '1 + x.^2 + y.^2';
u = parabolic(u0,tlist,model,c,a,f,d);
2-90
Solve PDE with Coefficients in Functional Form
function f = framp2(p,t,u,time)
2-91
2 Setting Up Your PDE
end
f = 10*f;
end
f = @framp2;
u = parabolic(u0,tlist,model,c,a,f,d);
You can also write a function for the coefficient c, though it is more complicated than the
character formulation. function c = cfunc(p,t,u,time)
c = 1 + xpts.^2 + ypts.^2;
end
c = @cfunc;
u = parabolic(u0,tlist,model,c,a,f,d);
2-92
Enter Coefficients in the PDE Modeler App
Caution: Do not include spaces when you specify your coefficients the PDE Modeler app.
The parser can misinterpret a space as a vector separator, as when a MATLAB vector uses
a space to separate elements of a vector.
∂u
d - — ◊ ( c— u ) + au = f
∂t
• d=5
• a=0
• f is a linear ramp up to 10, holds at 10, then ramps back down to 0:
Ï10 t 0 £ t £ 0.1
Ô
f = 10 * Ì1 0.1 £ t £ 0 .9
Ô10 - 10t 0.9 £ t £ 1
Ó
• c = 1 +.x2 + y2
Write the following file framp.m and save it on your MATLAB path.
function f = framp(t)
if t <= 0.1
f = 10*t;
elseif t <= 0.9
f = 1;
else
f = 10-10*t;
end
f = 10*f;
Open the PDE Modeler app, either by typing pdeModeler at the command line, or
selecting PDE from the Apps menu.
2-93
2 Setting Up Your PDE
• c = 1 + x.^2 + y.^2
• a=0
• f = framp(t)
• d=5
The PDE Modeler app interprets all inputs as vectors of characters. Therefore, do not
include quotes for the c or f coefficients.
Select Draw > Draw Mode, then draw a rectangle centered at (0,0) extending to 1 in the
x-direction and 0.4 in the y-direction.
2-94
Enter Coefficients in the PDE Modeler App
Click a segment of the outer rectangle, then Shift-click the other three segments so that
all four segments of the rectangle are selected.
Fill in the resulting dialog box as pictured, with Dirichlet boundary conditions h = 1 and r
= t*(x-y). Click OK.
2-95
2 Setting Up Your PDE
Select the four segments of the inner circle using Shift-click, and double-click one of the
segments.
Select Neumann boundary conditions, and set g = x.^2+y.^2 and q = 1. Click OK.
2-96
Enter Coefficients in the PDE Modeler App
Click to refine the mesh. Click again to get an even finer mesh.
Select Mesh > Jiggle Mesh to improve the quality of the mesh.
Set the time interval and initial condition by selecting Solve > Parameters and setting
Time = linspace(0,1,50) and u(t0) = 0. Click OK.
2-97
2 Setting Up Your PDE
2-98
Enter Coefficients in the PDE Modeler App
2-99
2 Setting Up Your PDE
See Also
Related Examples
• “Coefficients for Scalar PDEs in PDE Modeler App” on page 2-79
2-100
Systems in the PDE Modeler App
2-101
2 Setting Up Your PDE
Enter character expressions for coefficients using the form in “Coefficients for Scalar
PDEs in PDE Modeler App” on page 2-79, with additional options for nonlinear equations.
The additional options are:
Note For elliptic problems, when you include coefficients u(i), ux(i), or uy(i), you
must use the nonlinear solver. Select Solve > Parameters > Use nonlinear solver.
For higher-dimensional systems, do not use the PDE Modeler app. Represent your
problem coefficients at the command line.
You can enter scalars into the c matrix, corresponding to these equations:
If you need matrix versions of any of the cij coefficients, enter expressions separated by
spaces. You can give 1-, 2-, 3-, or 4-element matrix expressions. These mean:
•
Ê c 0ˆ
1-element expression: Á ˜
Ë0 c¯
•
Ê c(1) 0 ˆ
2-element expression: Á ˜
Ë 0 c(2) ¯
•
Ê c(1) c(2) ˆ
3-element expression: Á ˜
Ë c(2) c(3) ¯
•
Ê c(1) c( 3) ˆ
4-element expression: Á ˜
Ë c(2) c(4 ) ¯
2-102
Systems in the PDE Modeler App
For example, these expressions show one of each type (1-, 2-, 3-, and 4-element
expressions)
Ê Ê 4 + cos( xy) 0 ˆ ˆ Ê Ê -1 0 ˆ ˆ
- —·Á Á ˜ —u1 ˜ - —·Á Á ˜ —u2 ˜ = 1
ËË 0 4 + cos( xy) ¯ ¯ ËË 0 1 ¯ ¯
Ê Ê .1 .2 ˆ ˆ ÊÊ 7 .6 ˆ ˆ
-—·Á Á ˜ —u1 ˜ - —·Á Á ˜ —u2 ˜ = 2
Ë Ë .2 .3 ¯ ¯ Ë Ë .5 exp( x - y) ¯ ¯
2-103
2 Setting Up Your PDE
Note THIS PAGE DESCRIBES THE LEGACY WORKFLOW. New features might not be
compatible with the legacy workflow. For the corresponding step in the recommended
workflow, see “f Coefficient for specifyCoefficients” on page 2-107.
-— ◊ ( c ƒ — u ) + au = f
f = [3;4;10];
• A character array with N rows. The rows of the character array are MATLAB
expressions as described in “Specify Scalar PDE Coefficients in Character Form” on
page 2-76, with additional options for nonlinear equations. The additional options are:
Pad the rows with spaces so each row has the same number of characters (char does
this automatically). For example, if N = 3, f could be:
f = char('sin(x)+cos(y)', ...
'cosh(x.*y)*(1+u(1).^2)', ...
'x.*y./(1+x.^2+y.^2)')
f =
sin(x) + cos(y)
cosh(x.*y)*(1 + u(1).^2)
x.*y./(1 + x.^2 + y.^2)
• For 2-D geometry, a function as described in “Specify 2-D Scalar Coefficients in
Function Form” on page 2-82. The function should return a matrix of size N-by-Nt,
where Nt is the number of triangles in the mesh. The function should evaluate f at the
2-104
f Coefficient for Systems
function f = fcoeffunction(p,t,u,time)
N = 3; % Number of equations
% Triangle point indices
it1 = t(1,:);
it2 = t(2,:);
it3 = t(3,:);
Because this function depends on the solution u, if the equation is elliptic, use the
pdenonlin solver. The initial value can be all 0s in the case of Dirichlet boundary
conditions:
2-105
2 Setting Up Your PDE
2-106
f Coefficient for specifyCoefficients
∂ 2u ∂u
m +d - —·( c—u ) + au = f
2 ∂t
∂t
or in similar equations. The question is how to write the coefficient f for inclusion in the
PDE model via specifyCoefficients.
N is the number of equations, see “Equations You Can Solve Using PDE Toolbox” on page
1-6. Give f as either of the following:
• location.x
• location.y
• location.z
• location.subdomain
The fields x, y, and z represent the x-, y-, and z- coordinates of points for which
your function calculates coefficient values. The subdomain field represents the
subdomain numbers, which currently apply only to 2-D models. The location fields
are row vectors.
2-107
2 Setting Up Your PDE
• state.u
• state.ux
• state.uy
• state.uz
• state.time
The state.u field represents the current value of the solution u. The state.ux,
state.uy, and state.uz fields are estimates of the solution’s partial derivatives
(∂u/∂x, ∂u/∂y, and ∂u/∂z) at the corresponding points of the location structure. The
solution and gradient estimates are N-by-Nr matrices. The state.time field is a
scalar representing time for time-dependent models.
function f = fcoeffunction(location,state)
N = 3; % Number of equations
nr = length(location.x); % Number of columns
f = zeros(N,nr); % Allocate f
È x - y + u(1) ˘
f = 1 + tanh( ∂u(1) / ∂ x) + tanh(∂ u( 3) / ∂y) ˙
Í
Í ˙
Í 2 2 ˙
Î (5 + u(3)) x + y ˚
See Also
Related Examples
• “m, d, or a Coefficient for specifyCoefficients” on page 2-149
2-108
See Also
2-109
2 Setting Up Your PDE
∂ 2u ∂u
m +d - —·( c—u ) + au = f
2 ∂t
∂t
The topic applies to the recommended workflow for including coefficients in your model
using specifyCoefficients.
For 2-D systems, c is a tensor with 4N2 elements. For 3-D systems, c is a tensor with 9N2
elements. For a definition of the tensor elements, see “Definition of the c Tensor
Elements” on page 2-111. N is the number of equations, see “Equations You Can Solve
Using PDE Toolbox” on page 1-6.
To write the coefficient c for inclusion in the PDE model via specifyCoefficients,
give c as either of the following:
ccoeffunction(location,state)
• N1 is the length of the vector representing the c coefficient. There are several
possible values of N1, detailed in “Some c Vectors Can Be Short” on page 2-113.
For 2-D geometry, 1 ≤ N1 ≤ 4N2, and for 3-D geometry, 1 ≤ N1 ≤ 9N2.
2-110
c Coefficient for specifyCoefficients
• Nr is the number of points in the location that the solver passes. Nr is equal to the
length of the location.x or any other location field. The function should
evaluate c at these points.
For 2-D systems, the notation — ◊ (c ƒ —u ) represents an N-by-1 matrix with an (i,1)-
component
N
Ê ∂ ∂ ∂ ∂ ∂ ∂ ∂ ∂ ˆ
 ÁË ∂x ci, j ,1,1 ∂x + ∂x ci, j ,1,2 ∂y + ∂y ci, j,2,1 ∂x + ∂y ci, j ,2,2 ∂y ˜¯u j
j =1
For 3-D systems, the notation — ◊ (c ƒ —u ) represents an N-by-1 matrix with an (i,1)-
component
N
Ê ∂ ∂ ∂ ∂ ∂ ∂ ˆ
 ÁË ∂x ci, j ,1,1 ∂x + ∂x ci, j ,1,2 ∂y + ∂x ci, j,1,3 ∂z ˜¯ u j
j =1
N
Ê ∂ ∂ ∂ ∂ ∂ ∂ ˆ
+  ÁË ∂y ci, j,2,1 ∂x + ∂y ci, j ,2,2 ∂y + ∂y ci, j,2,3 ∂z ˜¯ u j
j =1
N
Ê ∂ ∂ ∂ ∂ ∂ ∂ ˆ
+  ÁË ∂z ci, j ,3,1 ∂x + ∂z ci, j ,3,2 ∂y + ∂z ci, j,3,3 ∂z ˜¯ u j
j =1
All representations of the c coefficient begin with a “flattening” of the tensor to a matrix.
For 2-D systems, the N-by-N-by-2-by-2 tensor flattens to a 2N-by-2N matrix, where the
matrix is logically an N-by-N matrix of 2-by-2 blocks.
2-111
2 Setting Up Your PDE
Ê c(1,1,1,1) c(1,1,1, 2) c(1, 2,1,1) c(1, 2,1, 2) L c(1, N ,1,1) c(1, N ,1, 2) ˆ
Á ˜
Á c(1,1, 2,1) c(1,1, 2, 2) c(1, 2, 2, 1) c(1, 2, 2, 2) L c(1, N, 2, 1) c(1, N , 2, 2) ˜
Á ˜
Á ˜
Á c( 2,1, 1,1) c(2, 1,1, 2) c( 2, 2,1, 1) c( 2, 2, 1, 2) L c( 2, N ,1, 1) c( 2, N , 1, 2) ˜
Á c(2,1, 2,1) c(2,1, 2, 2) c(2, 2, 2,1) c(2, 2, 2, 2) L c(2, N , 2,1) c(2, N , 2, 2) ˜
Á ˜
Á ˜
Á M M M M O M M ˜
Á ˜
Á c( N ,1, 1,1) c( N , 1,1, 2) c( N , 2,1, 1) c( N , 2, 1, 2) L c( N , N ,1, 1) c( N, N , 1, 2) ˜
Á ˜
Ë c( N ,1, 2,1) c( N ,1, 2, 2) c( N , 2, 2,1) c(( N , 2, 2, 2) L c( N , N , 2,1) c( N , N , 2, 2) ¯
For 3-D systems, the N-by-N-by-3-by-3 tensor flattens to a 3N-by-3N matrix, where the
matrix is logically an N-by-N matrix of 3-by-3 blocks.
Ê c(1, 1, 1,1) c(1, 1,1, 2) c(1, 1, 1, 3) c(1, 2, 1,1) c(1, 2, 1, 2) c(1, 2, 1, 3) L c(1, N , 1, 1) c(1, N , 1, 2) c(1, N , 1, 3) ˆ
Á ˜
Á c(1, 1, 2, 1) c(1, 1, 2, 2) c(1, 1, 2, 3) c(1, 2, 2, 1) c(1, 2, 2, 2) c(1, 2, 2, 3) L c(1, N , 2, 1) c(1, N , 2, 2) c(1, N , 2, 3) ˜
Á c(1, 1, 3, 1) c(1, 1, 3, 2) c(1, 1, 3, 3) c(1, 2, 3, 1) c(1, 2, 3,, 2) c(1, 2, 3, 3) L c(1, N , 3, 1) c(1, N , 3, 2) c(1, N , 3, 3) ˜
Á ˜
Á ˜
Á c(2, 1, 1, 1) c( 2, 1, 1, 2) c(2, 1, 1, 3) c(2, 2, 1, 1) c(2, 2, 1, 2) c(2, 2, 1, 3) L c(2, N , 1, 1) c(2, N , 1, 2) c(2, N , 1, 3) ˜
Á ˜
Á c(2, 1, 2, 1) c(2, 1, 2, 2) c( 2, 1, 2, 3) c(2, 2, 2, 1) c(2, 2, 2, 2) c(2, 2, 2, 3) L c(2, N , 2, 1) c(2, N , 2, 2) c(2, N , 2, 3) ˜
Á ˜
Á c(2, 1, 3, 1) c(2, 1, 3, 2) c( 2, 1, 3, 3) c(2, 2, 3, 1) c(2, 2, 3, 2) c(2, 2, 3, 3) L c(2, N , 3, 1) c(2, N , 3, 2) c(2, N , 3, 3) ˜
Á M M M M M M O M M M ˜
Á ˜
Á c( N , 1, 1, 1) c( N , 1,, 1, 2) c( N , 1, 1, 3) c( N , 2, 1, 1) c( N , 2, 1, 2) c(N , 2, 1, 3) L c( N , N , 1, 1) c( N , N , 1, 2) c( N , N , 1, 3) ˜
Á c( N , 1, 2, 1) c( N , 1, 2, 2) c( N , 1, 2, 3) c(N , 2, 2, 1) c( N , 2, 2, 2) c( N , 2, 2, 3) L c( N , N , 2, 1) c( N , N , 2, 2) c( N , N , 2, 3) ˜
ÁÁ ˜
Ë c( N , 1, 3, 1) c( N , 1, 3, 2) c( N , 1, 3, 3) c(N , 2, 3, 1) c( N , 2, 3, 2) c( N , 2, 3, 3) L c( N , N , 3, 1) c( N , N , 3, 2) c( N , N , 3, 3) ˜¯
These matrices further get flattened into a column vector. First the N-by-N matrices
of 2-by-2 and 3-by-3 blocks are transformed into "vectors" of 2-by-2 and 3-by-3 blocks.
Then the blocks are turned into vectors in the usual column-wise way.
The coefficient vector c relates to the tensor c as follows. For 2-D systems,
2-112
c Coefficient for specifyCoefficients
2-D Systems
2-113
2 Setting Up Your PDE
The software interprets a scalar c as a diagonal matrix, with c(i,i,1,1) and c(i,i,2,2) equal
to the scalar, and all other entries 0.
Êc 0 0 0 L 0 0ˆ
Á ˜
Á0 c 0 0 L 0 0˜
Á ˜
Á ˜
Á0 0 c 0 L 0 0˜
Á0 0 0 c L 0 0˜
Á ˜
Á ˜
ÁM M M M O M M˜
Á ˜
Á0 0 0 0 L c 0˜
Á ˜
Ë0 0 0 0 L 0 c¯
The software interprets a two-element column vector c as a diagonal matrix, with c(i,i,1,1)
and c(i,i,2,2) as the two entries, and all other entries 0.
Ê c(1) 0 0 0 L 0 0 ˆ
Á ˜
Á 0 c(2) 0 0 L 0 0 ˜
Á ˜
Á ˜
Á 0 0 c(1) 0 L 0 0 ˜
Á 0 0 0 c(2) L 0 0 ˜
Á ˜
Á ˜
Á M M M M O M M ˜
Á ˜
Á 0 0 0 0 L c(1) 0 ˜
Á ˜
Ë 0 0 0 0 L 0 c( 2) ¯
2-114
c Coefficient for specifyCoefficients
Ê c(1) c(2) 0 0 L 0 0 ˆ
Á ˜
Á c(2) c(3) 0 0 L 0 0 ˜
Á ˜
Á ˜
Á 0 0 c(1) c(2) L 0 0 ˜
Á 0 0 c(2) c(3) L 0 0 ˜
Á ˜
Á ˜
Á M M M M O M M ˜
Á ˜
Á 0 0 0 0 L c(1) c( 2) ˜
Á ˜
Ë 0 0 0 0 L c( 2) c( 3) ¯
Ê c(1) c( 3) 0 0 L 0 0 ˆ
Á ˜
Á c(2) c(4 ) 0 0 L 0 0 ˜
Á ˜
Á ˜
Á 0 0 c(1) c( 3) L 0 0 ˜
Á 0 0 c(2) c( 4) L 0 0 ˜
Á ˜
Á ˜
Á M M M M O M M ˜
Á ˜
Á 0 0 0 0 L c(1) c(3) ˜
Á ˜
Ë 0 0 0 0 L c( 2) c( 4) ¯
2-115
2 Setting Up Your PDE
Ê c(1) 0 0 0 L 0 0 ˆ
Á ˜
Á 0 c(1) 0 0 L 0 0 ˜
Á ˜
Á ˜
Á 0 0 c(2) 0 L 0 0 ˜
Á 0 0 0 c(2) L 0 0 ˜
Á ˜
Á ˜
Á M M M M O M M ˜
Á ˜
Á 0 0 0 0 L c( N ) 0 ˜
Á ˜
Ë 0 0 0 0 L 0 c( N ) ¯
Caution If N = 2, 3, or 4, the 2-, 3-, or 4-element column vector form takes precedence
over the N-element form. For example, if N = 3, and you have a c matrix of the form
Ê c1 0 0 0 0 0 ˆ
Á ˜
Á 0 c1 0 0 0 0 ˜
Á 0 0 c2 0 0 0 ˜
Á ˜
Á 0 0 0 c2 0 0 ˜
Á 0 0 0 0 c3 0 ˜
ÁÁ ˜˜
Ë 0 0 0 0 0 c3 ¯
you cannot use the N-element form of c. Instead, you must use the 2N-element form. If
you give c as the vector [c1;c2;c3], the software interprets c as a 3-element form:
Ê c1 c2 0 0 0 0 ˆ
Á ˜
Á c2 c3 0 0 0 0 ˜
Á 0 0 c1 c2 0 0 ˜
Á ˜
Á 0 0 c2 c3 0 0 ˜
Á 0 0 0 0 c1 c2 ˜
ÁÁ ˜˜
Ë 0 0 0 0 c2 c3 ¯
2-116
c Coefficient for specifyCoefficients
Ê c(1) 0 0 0 L 0 0 ˆ
Á ˜
Á 0 c(2) 0 0 L 0 0 ˜
Á ˜
Á ˜
Á 0 0 c(3) 0 L 0 0 ˜
Á 0 0 0 c(4) L 0 0 ˜
Á ˜
Á ˜
Á M M M M O M M ˜
Á ˜
Á 0 0 0 0 L c(2 N - 1) 0 ˜
Á ˜
Ë 0 0 0 0 L 0 c(2 N ) ¯
Caution If N = 2, the 4-element form takes precedence over the 2N-element form. For
example, if your c matrix is
Ê c1 0 0 0 ˆ
Á ˜
Á 0 c2 0 0 ˜
Á 0 0 c3 0 ˜
Á ˜
Ë 0 0 0 c4 ¯
you cannot give c as [c1;c2;c3;c4], because the software interprets this vector as the
4-element form
Ê c1 c3 0 0 ˆ
Á ˜
Á c2 c4 0 0 ˜
Á 0 0 c1 c3 ˜
Á ˜
Ë 0 0 c2 c4 ¯
2-117
2 Setting Up Your PDE
Ê c(1) c(2) 0 0 L 0 0 ˆ
Á ˜
Á c(2) c(3) 0 0 L 0 0 ˜
Á ˜
Á ˜
Á 0 0 c(4) c( 5) L 0 0 ˜
Á 0 0 c(5) c(6 ) L 0 0 ˜
Á ˜
Á ˜
Á M M M M O M M ˜
Á ˜
Á 0 0 0 0 L c(3 N - 2) c( 3 N - 1) ˜
Á ˜
Ë 0 0 0 0 L c( 3 N - 1) c(3 N ) ¯
Ê c(1) c( 3) 0 0 L 0 0 ˆ
Á ˜
Á c(2) c(4 ) 0 0 L 0 0 ˜
Á ˜
Á ˜
Á 0 0 c(5) c(7) L 0 0 ˜
Á 0 0 c(6) c(8 ) L 0 0 ˜
Á ˜
Á ˜
Á M M M M O M M ˜
Á ˜
Á 0 0 0 0 L c(4 N - 3) c(4 N - 1) ˜
Á ˜
Ë 0 0 0 0 L c(4 N - 2) c(4 N ) ¯
2-118
c Coefficient for specifyCoefficients
3-D Systems
2-119
2 Setting Up Your PDE
The software interprets a scalar c as a diagonal matrix, with c(i,i,1,1), c(i,i,2,2), and c(i,i,
3,3) equal to the scalar, and all other entries 0.
Êc 0 0 0 0 0 L 0 0 0ˆ
Á ˜
Á0 c 0 0 0 0 L 0 0 0˜
Á0 0 c 0 0 0 L 0 0 0˜
Á ˜
Á ˜
Á0 0 0 c 0 0 L 0 0 0˜
Á ˜
Á0 0 0 0 c 0 L 0 0 0˜
Á0 0 0 0 0 c L 0 0 0˜
Á ˜
ÁM M M M M M O M M M˜
Á ˜
Á0 0 0 0 0 0 L c 0 0˜
Á0 0 0 0 0 0 L 0 c 0˜
ÁÁ ˜
Ë0 0 0 0 0 0 L 0 0 c ˜¯
The software interprets a three-element column vector c as a diagonal matrix, with c(i,i,
1,1), c(i,i,2,2), and c(i,i,3,3) as the three entries, and all other entries 0.
2-120
c Coefficient for specifyCoefficients
Ê c(1) 0 0 0 0 0 L 0 0 0 ˆ
Á ˜
Á 0 c(2) 0 0 0 0 L 0 0 0 ˜
Á 0 0 c(3) 0 0 0 L 0 0 0 ˜
Á ˜
Á ˜
Á 0 0 0 c(1) 0 0 L 0 0 0 ˜
Á ˜
Á 0 0 0 0 c(2) 0 L 0 0 0 ˜
Á 0 0 0 0 0 c(3) L 0 0 0 ˜
Á ˜
Á M M M M M M O M M M ˜
Á ˜
Á 0 0 0 0 0 0 L c(1) 0 0 ˜
Á 0 0 0 0 0 0 L 0 c( 2) 0 ˜
ÁÁ ˜
Ë 0 0 0 0 0 0 L 0 0 c( 3) ˜¯
c(i,i,1,1) = c(1)
c(i,i,2,2) = c(3)
c(i,i,1,2) = c(i,i,2,1) = c(2)
c(i,i,1,3) = c(i,i,3,1) = c(4)
c(i,i,2,3) = c(i,i,3,2) = c(5)
c(i,i,3,3) = c(6).
2-121
2 Setting Up Your PDE
2-122
c Coefficient for specifyCoefficients
Ê c(1) 0 0 0 0 0 L 0 0 0 ˆ
Á ˜
Á 0 c(1) 0 0 0 0 L 0 0 0 ˜
Á 0 0 c(1) 0 0 0 L 0 0 0 ˜
Á ˜
Á ˜
Á 0 0 0 c(2) 0 0 L 0 0 0 ˜
Á ˜
Á 0 0 0 0 c(2) 0 L 0 0 0 ˜
Á 0 0 0 0 0 c(2) L 0 0 0 ˜
Á ˜
Á M M M M M M O M M M ˜
Á ˜
Á 0 0 0 0 0 0 L c( N ) 0 0 ˜
Á 0 0 0 0 0 0 L 0 c( N) 0 ˜
ÁÁ ˜
Ë 0 0 0 0 0 0 L 0 0 c( N ) ˜¯
Caution If N = 3, 6, or 9, the 3-, 6-, or 9-element column vector form takes precedence
over the N-element form. For example, if N = 3, and you have a c matrix of the form
Ê c(1) 0 0 0 0 0 0 0 ˆ
0
Á ˜
Á 0 c(1) 0 0 0 0 0 0 0 ˜
Á 0 0 c(1) 0 0 0 0 0 0 ˜
Á ˜
Á ˜
Á 0 0 0 c(2) 0 0 0 0 0 ˜
Á ˜
Á 0 0 0 0 c(2) 0 0 0 0 ˜
Á 0 0 0 0 0 c(2) 0 0 0 ˜
Á ˜
Á ˜
Á ˜
Á 0 0 0 0 0 0 c(3) 0 0 ˜
Á 0 0 0 0 0 0 0 c(3) 0 ˜
ÁÁ ˜
Ë 0 0 0 0 0 0 0 0 c(3) ˜¯
you cannot use the N-element form of c. If you give c as the vector [c1;c2;c3], the
software interprets c as a 3-element form:
2-123
2 Setting Up Your PDE
Ê c(1) 0 0 0 0 0 0 0 ˆ
0
Á ˜
Á 0 c(2) 0 0 0 0 0 0 0
˜
Á 0 0 c(3) 0 0 0 0 0 ˜
0
Á ˜
Á ˜
Á 0 0 0 c(1) 0 0 0 0 0 ˜
Á ˜
Á 0 0 0 0 c(2) 0 0 0 0 ˜
Á 0 0 0 0 0 c(3) 0 0 0 ˜
Á ˜
Á ˜
Á ˜
Á 0 0 0 0 0 0 c(1) 0 0 ˜
Á 0 0 0 0 0 0 0 c(2) 0 ˜
ÁÁ ˜
Ë 0 0 0 0 0 0 0 0 c(3) ˜¯
Ê c(1) 0 0 0 0 0 L 0 0 0 ˆ
Á ˜
Á 0 c (2) 0 0 0 0 L 0 0 0 ˜
Á 0 0 c(3) 0 0 0 L 0 0 0 ˜
Á ˜
Á ˜
Á 0 0 0 c(4) 0 0 L 0 0 0 ˜
Á ˜
Á 0 0 0 0 c( 5) 0 L 0 0 0 ˜
Á 0 0 0 0 0 c( 6) L 0 0 0 ˜
Á ˜
Á M M M M M M O M M M ˜
Á ˜
Á 0 0 0 0 0 0 L c( 3 N - 2) 0 0 ˜
Á 0 0 0 0 0 0 L 0 c(3 N - 1) 0 ˜
ÁÁ ˜
Ë 0 0 0 0 0 0 L 0 0 c(3 N ) ˜¯
2-124
c Coefficient for specifyCoefficients
Caution If N = 3, the 9-element form takes precedence over the 3N-element form. For
example, if your c matrix is
Ê c(1) 0 0 0 0 0 0 0 ˆ
0
Á ˜
Á 0 c(2) 0 0 0 0 0 0 0
˜
Á 0 0 c(3) 0 0 0 0 0 ˜
0
Á ˜
Á ˜
Á 0 0 0 c(4) 0 0 0 0 0 ˜
Á ˜
Á 0 0 0 0 c( 5) 0 0 0 0 ˜
Á 0 0 0 0 0 c( 6) 0 0 0 ˜
Á ˜
Á ˜
Á ˜
Á 0 0 0 0 0 0 c(7) 0 0 ˜
Á 0 0 0 0 0 0 0 c(8) 0 ˜
ÁÁ ˜
Ë 0 0 0 0 0 0 0 0 c(9) ˜¯
2-125
2 Setting Up Your PDE
• 9N-element form —
[c1;0;0;0;c2;0;0;0;c3;c4;0;0;0;c5;0;0;0;c6;c7;0;0;0;c8;0;0;0;c9]
2-126
c Coefficient for specifyCoefficients
2-127
2 Setting Up Your PDE
Functional Form
If your c coefficient is not constant, represent it as a function of the form
ccoeffunction(location,state)
• N1 is the number of coefficients you pass to the solver. There are several possible
values of N1, detailed in “Some c Vectors Can Be Short” on page 2-113. For 2-D
geometry, 1 ≤ N1 ≤ 4N2, and for 3-D geometry, 1 ≤ N1 ≤ 9N2.
• Nr is the number of points in the location that the solver passes. Nr is equal to the
length of the location.x or any other location field. The function should evaluate
c at these points.
specifyCoefficients(model,'c',@ccoeffunction,...)
• location.x
• location.y
• location.z
• location.subdomain
The fields x, y, and z represent the x-, y-, and z- coordinates of points for which your
function calculates coefficient values. The subdomain field represents the subdomain
numbers, which currently apply only to 2-D models. The location fields are row
vectors.
• state is a structure with these fields:
• state.u
• state.ux
• state.uy
• state.uz
• state.time
2-128
c Coefficient for specifyCoefficients
The state.u field represents the current value of the solution u. The state.ux,
state.uy, and state.uz fields are estimates of the solution’s partial derivatives (∂u/
∂x, ∂u/∂y, and ∂u/∂z) at the corresponding points of the location structure. The solution
and gradient estimates are N-by-Nr matrices. The state.time field is a scalar
representing time for time-dependent models.
For example, suppose N = 3, and you have 2-D geometry. Suppose your c matrix is of the
form
È1 2 ˘
Í2 8 ˙
Í ˙
Í ˙
Í ˙
Í u(2) ˙
1 + x2 + y2
Í 1 + u(1)2 + u(3) 2 ˙
c= Í ˙
Í u(2)
1 + x2 + y2 ˙
Í 2
1 + u(1) + u(3) 2 ˙
Í ˙
Í ˙
Í s1 ( x, y) -1 ˙
Í ˙
ÍÎ -1 s1 ( x, y) ˙˚
Ê c(1) c(2) 0 0 L 0 0 ˆ
Á ˜
Á c(2) c(3) 0 0 L 0 0 ˜
Á ˜
Á ˜
Á 0 0 c(4) c( 5) L 0 0 ˜
Á 0 0 c(5) c(6 ) L 0 0 ˜
Á ˜
Á ˜
Á M M M M O M M ˜
Á ˜
Á 0 0 0 0 L c(3 N - 2) c( 3 N - 1) ˜
Á ˜
Ë 0 0 0 0 L c( 3 N - 1) c(3 N ) ¯
2-129
2 Setting Up Your PDE
n1 = 9;
nr = numel(location.x);
cmatrix = zeros(n1,nr);
cmatrix(1,:) = ones(1,nr);
cmatrix(2,:) = 2*ones(1,nr);
cmatrix(3,:) = 8*ones(1,nr);
cmatrix(4,:) = 1+location.x.^2 + location.y.^2;
cmatrix(5,:) = state.u(2,:)./(1 + state.u(1,:).^2 + state.u(3,:).^2);
cmatrix(6,:) = cmatrix(4,:);
cmatrix(7,:) = 5*location.subdomain;
cmatrix(8,:) = -ones(1,nr);
cmatrix(9,:) = cmatrix(7,:);
To include this function as your c coefficient, pass the function handle @ccoeffunction:
specifyCoefficients(model,'c',@ccoeffunction,...
See Also
Related Examples
• “Solve Problems Using PDEModel Objects” on page 2-6
• “f Coefficient for specifyCoefficients” on page 2-107
• “m, d, or a Coefficient for specifyCoefficients” on page 2-149
• “Deflection of Piezoelectric Actuator” on page 3-13
2-130
c Coefficient for Systems
Note THIS PAGE DESCRIBES THE LEGACY WORKFLOW. New features might not be
compatible with the legacy workflow. For the corresponding step in the recommended
workflow, see “c Coefficient for specifyCoefficients” on page 2-110.
In this section...
“c as Tensor, Matrix, and Vector” on page 2-131
“2-D Systems” on page 2-134
“3-D Systems” on page 2-140
-— ◊ ( c ƒ — u ) + au = f
For 2-D systems, the coefficient c is an N-by-N-by-2-by-2 tensor with components c(i,j,k,l).
N is the number of equations (see “Equations You Can Solve Using Legacy Functions” on
page 1-3). For 3-D systems, c is an N-by-N-by-3-by-3 tensor.
For 2-D systems, the notation — ◊ (c ƒ —u ) represents an N-by-1 matrix with an (i,1)-
component
N
Ê ∂ ∂ ∂ ∂ ∂ ∂ ∂ ∂ ˆ
 ÁË ∂x ci, j ,1,1 ∂x + ∂x ci, j ,1,2 ∂y + ∂y ci, j,2,1 ∂x + ∂y ci, j ,2,2 ∂y ˜¯u j
j =1
For 3-D systems, the notation — ◊ (c ƒ —u ) represents an N-by-1 matrix with an (i,1)-
component
2-131
2 Setting Up Your PDE
N
Ê ∂ ∂ ∂ ∂ ∂ ∂ ˆ
 ÁË ∂x ci, j ,1,1 ∂x + ∂x ci, j ,1,2 ∂y + ∂x ci, j,1,3 ∂z ˜¯ u j
j =1
N
Ê ∂ ∂ ∂ ∂ ∂ ∂ ˆ
+  ÁË ∂y ci, j,2,1 ∂x + ∂y ci, j ,2,2 ∂y + ∂y ci, j,2,3 ∂z ˜¯ u j
j =1
N
Ê ∂ ∂ ∂ ∂ ∂ ∂ ˆ
+  ÁË ∂z ci, j ,3,1 ∂x + ∂z ci, j ,3,2 ∂y + ∂z ci, j,3,3 ∂z ˜¯ u j
j =1
All representations of the c coefficient begin with a “flattening” of the tensor to a matrix.
For 2-D systems, the N-by-N-by-2-by-2 tensor flattens to a 2N-by-2N matrix, where the
matrix is logically an N-by-N matrix of 2-by-2 blocks.
Ê c(1,1,1,1) c(1,1,1, 2) c(1, 2,1,1) c(1, 2,1, 2) L c(1, N ,1,1) c(1, N ,1, 2) ˆ
Á ˜
Á c(1,1, 2,1) c(1,1, 2, 2) c(1, 2, 2, 1) c(1, 2, 2, 2) L c(1, N, 2, 1) c(1, N , 2, 2) ˜
Á ˜
Á ˜
Á c( 2,1, 1,1) c(2, 1,1, 2) c( 2, 2,1, 1) c( 2, 2, 1, 2) L c( 2, N ,1, 1) c( 2, N , 1, 2) ˜
Á c(2,1, 2,1) c(2,1, 2, 2) c(2, 2, 2,1) c(2, 2, 2, 2) L c(2, N , 2,1) c(2, N , 2, 2) ˜
Á ˜
Á ˜
Á M M M M O M M ˜
Á ˜
Á c( N ,1, 1,1) c( N , 1,1, 2) c( N , 2,1, 1) c( N , 2, 1, 2) L c( N , N ,1, 1) c( N, N , 1, 2) ˜
Á ˜
Ë c( N ,1, 2,1) c( N ,1, 2, 2) c( N , 2, 2,1) c(( N , 2, 2, 2) L c( N , N , 2,1) c( N , N , 2, 2) ¯
For 3-D systems, the N-by-N-by-3-by-3 tensor flattens to a 3N-by-3N matrix, where the
matrix is logically an N-by-N matrix of 3-by-3 blocks.
Ê c(1, 1, 1,1) c(1, 1,1, 2) c(1, 1, 1, 3) c(1, 2, 1,1) c(1, 2, 1, 2) c(1, 2, 1, 3) L c(1, N , 1, 1) c(1, N , 1, 2) c(1, N , 1, 3) ˆ
Á ˜
Á c(1, 1, 2, 1) c(1, 1, 2, 2) c(1, 1, 2, 3) c(1, 2, 2, 1) c(1, 2, 2, 2) c(1, 2, 2, 3) L c(1, N , 2, 1) c(1, N , 2, 2) c(1, N , 2, 3) ˜
Á c(1, 1, 3, 1) c(1, 1, 3, 2) c(1, 1, 3, 3) c(1, 2, 3, 1) c(1, 2, 3,, 2) c(1, 2, 3, 3) L c(1, N , 3, 1) c(1, N , 3, 2) c(1, N , 3, 3) ˜
Á ˜
Á ˜
Á c(2, 1, 1, 1) c( 2, 1, 1, 2) c(2, 1, 1, 3) c(2, 2, 1, 1) c(2, 2, 1, 2) c(2, 2, 1, 3) L c(2, N , 1, 1) c(2, N , 1, 2) c(2, N , 1, 3) ˜
Á ˜
Á c(2, 1, 2, 1) c(2, 1, 2, 2) c( 2, 1, 2, 3) c(2, 2, 2, 1) c(2, 2, 2, 2) c(2, 2, 2, 3) L c(2, N , 2, 1) c(2, N , 2, 2) c(2, N , 2, 3) ˜
Á ˜
Á c(2, 1, 3, 1) c(2, 1, 3, 2) c( 2, 1, 3, 3) c(2, 2, 3, 1) c(2, 2, 3, 2) c(2, 2, 3, 3) L c(2, N , 3, 1) c(2, N , 3, 2) c(2, N , 3, 3) ˜
Á M M M M M M O M M M ˜
Á ˜
Á c( N , 1, 1, 1) c( N , 1,, 1, 2) c( N , 1, 1, 3) c( N , 2, 1, 1) c( N , 2, 1, 2) c(N , 2, 1, 3) L c( N , N , 1, 1) c( N , N , 1, 2) c( N , N , 1, 3) ˜
Á c( N , 1, 2, 1) c( N , 1, 2, 2) c( N , 1, 2, 3) c(N , 2, 2, 1) c( N , 2, 2, 2) c( N , 2, 2, 3) L c( N , N , 2, 1) c( N , N , 2, 2) c( N , N , 2, 3) ˜
ÁÁ ˜
Ë c( N , 1, 3, 1) c( N , 1, 3, 2) c( N , 1, 3, 3) c(N , 2, 3, 1) c( N , 2, 3, 2) c( N , 2, 3, 3) L c( N , N , 3, 1) c( N , N , 3, 2) c( N , N , 3, 3) ˜¯
2-132
c Coefficient for Systems
These matrices further get flattened into a column vector. First the N-by-N matrices
of 2-by-2 and 3-by-3 blocks are transformed into "vectors" of 2-by-2 and 3-by-3 blocks.
Then the blocks are turned into vectors in the usual column-wise way.
The coefficient vector c relates to the tensor c as follows. For 2-D systems,
Often, your tensor c has structure, such as symmetric or block diagonal. In many cases,
you can represent c using a smaller vector than one with 4N2 components for 2-D or 9N2
components for 3-D.
The number of rows in the matrix can differ from 4N2 for 2-D or 9N2 for 3-D, as described
in “2-D Systems” on page 2-134 and “3-D Systems” on page 2-140.
In function form for 2-D systems, the number of columns is Nt, which is the number of
triangles or tetrahedra in the mesh. The function should evaluate c at the triangle or
tetrahedron centroids, as in “Specify 2-D Scalar Coefficients in Function Form” on page 2-
82. Give solvers the function name as 'filename', or as a function handle @filename,
2-133
2 Setting Up Your PDE
where filename.m is a file on your MATLAB path. For details on writing the function,
see “Calculate Coefficients in Function Form” on page 2-83.
For the function form of coefficients of 3-D systems, see “Specify 3-D PDE Coefficients in
Function Form” on page 2-85.
2-D Systems
• “Scalar c, 2-D Systems” on page 2-134
• “Two-Element Column Vector c, 2-D Systems” on page 2-135
• “Three-Element Column Vector c, 2-D Systems” on page 2-135
• “Four-Element Column Vector c, 2-D Systems” on page 2-135
• “N-Element Column Vector c, 2-D Systems” on page 2-136
• “2N-Element Column Vector c, 2-D Systems” on page 2-137
• “3N-Element Column Vector c, 2-D Systems” on page 2-138
• “4N-Element Column Vector c, 2-D Systems” on page 2-138
• “2N(2N+1)/2-Element Column Vector c, 2-D Systems” on page 2-139
• “4N2-Element Column Vector c, 2-D Systems” on page 2-139
The software interprets a scalar c as a diagonal matrix, with c(i,i,1,1) and c(i,i,2,2) equal
to the scalar, and all other entries 0.
Êc 0 0 0 L 0 0ˆ
Á ˜
Á0 c 0 0 L 0 0˜
Á ˜
Á ˜
Á0 0 c 0 L 0 0˜
Á0 0 0 c L 0 0˜
Á ˜
Á ˜
ÁM M M M O M M˜
Á ˜
Á0 0 0 0 L c 0˜
Á ˜
Ë0 0 0 0 L 0 c¯
2-134
c Coefficient for Systems
The software interprets a two-element column vector c as a diagonal matrix, with c(i,i,1,1)
and c(i,i,2,2) as the two entries, and all other entries 0.
Ê c(1) 0 0 0 L 0 0 ˆ
Á ˜
Á 0 c(2) 0 0 L 0 0 ˜
Á ˜
Á ˜
Á 0 0 c(1) 0 L 0 0 ˜
Á 0 0 0 c(2) L 0 0 ˜
Á ˜
Á ˜
Á M M M M O M M ˜
Á ˜
Á 0 0 0 0 L c(1) 0 ˜
Á ˜
Ë 0 0 0 0 L 0 c( 2) ¯
Ê c(1) c(2) 0 0 L 0 0 ˆ
Á ˜
Á c(2) c(3) 0 0 L 0 0 ˜
Á ˜
Á ˜
Á 0 0 c(1) c(2) L 0 0 ˜
Á 0 0 c(2) c(3) L 0 0 ˜
Á ˜
Á ˜
Á M M M M O M M ˜
Á ˜
Á 0 0 0 0 L c(1) c( 2) ˜
Á ˜
Ë 0 0 0 0 L c( 2) c( 3) ¯
2-135
2 Setting Up Your PDE
Ê c(1) c( 3) 0 0 L 0 0 ˆ
Á ˜
Á c(2) c(4 ) 0 0 L 0 0 ˜
Á ˜
Á ˜
Á 0 0 c(1) c( 3) L 0 0 ˜
Á 0 0 c(2) c( 4) L 0 0 ˜
Á ˜
Á ˜
Á M M M M O M M ˜
Á ˜
Á 0 0 0 0 L c(1) c(3) ˜
Á ˜
Ë 0 0 0 0 L c( 2) c( 4) ¯
Ê c(1) 0 0 0 L 0 0 ˆ
Á ˜
Á 0 c(1) 0 0 L 0 0 ˜
Á ˜
Á ˜
Á 0 0 c(2) 0 L 0 0 ˜
Á 0 0 0 c(2) L 0 0 ˜
Á ˜
Á ˜
Á M M M M O M M ˜
Á ˜
Á 0 0 0 0 L c( N ) 0 ˜
Á ˜
Ë 0 0 0 0 L 0 c( N ) ¯
Caution If N = 2, 3, or 4, the 2-, 3-, or 4-element column vector form takes precedence
over the N-element form. For example, if N = 3, and you have a c matrix of the form
Ê c1 0 0 0 0 0 ˆ
Á ˜
Á 0 c1 0 0 0 0 ˜
Á 0 0 c2 0 0 0 ˜
Á ˜
Á 0 0 0 c2 0 0 ˜
Á 0 0 0 0 c3 0 ˜
ÁÁ ˜˜
Ë 0 0 0 0 0 c3 ¯
2-136
c Coefficient for Systems
you cannot use the N-element form of c. Instead, you must use the 2N-element form. If
you give c as the vector [c1;c2;c3], the software interprets c as a 3-element form:
Ê c1 c2 0 0 0 0 ˆ
Á ˜
Á c2 c3 0 0 0 0 ˜
Á 0 0 c1 c2 0 0 ˜
Á ˜
Á 0 0 c2 c3 0 0 ˜
Á 0 0 0 0 c1 c2 ˜
ÁÁ ˜˜
Ë 0 0 0 0 c2 c3 ¯
Ê c(1) 0 0 0 L 0 0 ˆ
Á ˜
Á 0 c(2) 0 0 L 0 0 ˜
Á ˜
Á ˜
Á 0 0 c(3) 0 L 0 0 ˜
Á 0 0 0 c(4) L 0 0 ˜
Á ˜
Á ˜
Á M M M M O M M ˜
Á ˜
Á 0 0 0 0 L c(2 N - 1) 0 ˜
Á ˜
Ë 0 0 0 0 L 0 c(2 N ) ¯
Caution If N = 2, the 4-element form takes precedence over the 2N-element form. For
example, if your c matrix is
Ê c1 0 0 0 ˆ
Á ˜
Á 0 c2 0 0 ˜
Á 0 0 c3 0 ˜
Á ˜
Ë 0 0 0 c4 ¯
2-137
2 Setting Up Your PDE
you cannot give c as [c1;c2;c3;c4], because the software interprets this vector as the
4-element form
Ê c1 c3 0 0 ˆ
Á ˜
Á c2 c4 0 0 ˜
Á 0 0 c1 c3 ˜
Á ˜
Ë 0 0 c2 c4 ¯
Ê c(1) c(2) 0 0 L 0 0 ˆ
Á ˜
Á c(2) c(3) 0 0 L 0 0 ˜
Á ˜
Á ˜
Á 0 0 c(4) c( 5) L 0 0 ˜
Á 0 0 c(5) c(6 ) L 0 0 ˜
Á ˜
Á ˜
Á M M M M O M M ˜
Á ˜
Á 0 0 0 0 L c(3 N - 2) c( 3 N - 1) ˜
Á ˜
Ë 0 0 0 0 L c( 3 N - 1) c(3 N ) ¯
2-138
c Coefficient for Systems
Ê c(1) c( 3) 0 0 L 0 0 ˆ
Á ˜
Á c(2) c(4 ) 0 0 L 0 0 ˜
Á ˜
Á ˜
Á 0 0 c(5) c(7) L 0 0 ˜
Á 0 0 c(6) c(8 ) L 0 0 ˜
Á ˜
Á ˜
Á M M M M O M M ˜
Á ˜
Á 0 0 0 0 L c(4 N - 3) c(4 N - 1) ˜
Á ˜
Ë 0 0 0 0 L c(4 N - 2) c(4 N ) ¯
2-139
2 Setting Up Your PDE
3-D Systems
• “Scalar c, 3-D Systems” on page 2-140
• “Three-Element Column Vector c, 3-D Systems” on page 2-141
• “Six-Element Column Vector c, 3-D Systems” on page 2-141
• “Nine-Element Column Vector c, 3-D Systems” on page 2-142
• “N-Element Column Vector c, 3-D Systems” on page 2-143
• “3N-Element Column Vector c, 3-D Systems” on page 2-144
• “6N-Element Column Vector c, 3-D Systems” on page 2-146
• “9N-Element Column Vector c, 3-D Systems” on page 2-146
• “3N(3N+1)/2-Element Column Vector c, 3-D Systems” on page 2-147
• “9N2-Element Column Vector c, 3-D Systems” on page 2-147
The software interprets a scalar c as a diagonal matrix, with c(i,i,1,1), c(i,i,2,2), and c(i,i,
3,3) equal to the scalar, and all other entries 0.
2-140
c Coefficient for Systems
Êc 0 0 0 0 0 L 0 0 0ˆ
Á ˜
Á0 c 0 0 0 0 L 0 0 0˜
Á0 0 c 0 0 0 L 0 0 0˜
Á ˜
Á ˜
Á0 0 0 c 0 0 L 0 0 0˜
Á ˜
Á0 0 0 0 c 0 L 0 0 0˜
Á0 0 0 0 0 c L 0 0 0˜
Á ˜
ÁM M M M M M O M M M˜
Á ˜
Á0 0 0 0 0 0 L c 0 0˜
Á0 0 0 0 0 0 L 0 c 0˜
ÁÁ ˜
Ë0 0 0 0 0 0 L 0 0 c ˜¯
The software interprets a three-element column vector c as a diagonal matrix, with c(i,i,
1,1), c(i,i,2,2), and c(i,i,3,3) as the three entries, and all other entries 0.
Ê c(1) 0 0 0 0 0 L 0 0 0 ˆ
Á ˜
Á 0 c (2) 0 0 0 0 L 0 0 0 ˜
Á 0 0 c(3) 0 0 0 L 0 0 0 ˜
Á ˜
Á ˜
Á 0 0 0 c(1) 0 0 L 0 0 0 ˜
Á ˜
Á 0 0 0 0 c(2) 0 L 0 0 0 ˜
Á 0 0 0 0 0 c(3) L 0 0 0 ˜
Á ˜
Á M M M M M M O M M M ˜
Á ˜
Á 0 0 0 0 0 0 L c(1) 0 0 ˜
Á 0 0 0 0 0 0 L 0 c( 2) 0 ˜
ÁÁ ˜
Ë 0 0 0 0 0 0 L 0 0 c( 3) ˜¯
c(i,i,1,1) = c(1)
2-141
2 Setting Up Your PDE
c(i,i,2,2) = c(3)
c(i,i,1,2) = c(i,i,2,1) = c(2)
c(i,i,1,3) = c(i,i,3,1) = c(4)
c(i,i,2,3) = c(i,i,3,2) = c(5)
c(i,i,3,3) = c(6).
2-142
c Coefficient for Systems
Ê c(1) 0 0 0 0 0 L 0 0 0 ˆ
Á ˜
Á 0 c (1) 0 0 0 0 L 0 0 0 ˜
Á 0 0 c(1) 0 0 0 L 0 0 0 ˜
Á ˜
Á ˜
Á 0 0 0 c(2) 0 0 L 0 0 0 ˜
Á ˜
Á 0 0 0 0 c(2) 0 L 0 0 0 ˜
Á 0 0 0 0 0 c(2) L 0 0 0 ˜
Á ˜
Á M M M M M M O M M M ˜
Á ˜
Á 0 0 0 0 0 0 L c( N ) 0 0 ˜
Á 0 0 0 0 0 0 L 0 c( N) 0 ˜
ÁÁ ˜
Ë 0 0 0 0 0 0 L 0 0 c( N ) ˜¯
Caution If N = 3, 6, or 9, the 3-, 6-, or 9-element column vector form takes precedence
over the N-element form. For example, if N = 3, and you have a c matrix of the form
Ê c(1) 0 0 0 0 0 0 0 ˆ
0
Á ˜
Á 0 c(1) 0 0 0 0 0 0
0 ˜
Á 0 0 c(1) 0 0 0 0 0 0 ˜
Á ˜
Á ˜
Á 0 0 0 c(2) 0 0 0 0 0 ˜
Á ˜
Á 0 0 0 0 c(2) 0 0 0 0 ˜
Á 0 0 0 0 0 c(2) 0 0 0 ˜
Á ˜
Á ˜
Á ˜
Á 0 0 0 0 0 0 c(3) 0 0 ˜
Á 0 0 0 0 0 0 0 c(3) 0 ˜
ÁÁ ˜
Ë 0 0 0 0 0 0 0 0 c(3) ˜¯
you cannot use the N-element form of c. If you give c as the vector [c1;c2;c3], the
software interprets c as a 3-element form:
2-143
2 Setting Up Your PDE
Ê c(1) 0 0 0 0 0 0 0 ˆ
0
Á ˜
Á 0 c(2) 0 0 0 0 0 0 0
˜
Á 0 0 c(3) 0 0 0 0 0 ˜
0
Á ˜
Á ˜
Á 0 0 0 c(1) 0 0 0 0 0 ˜
Á ˜
Á 0 0 0 0 c(2) 0 0 0 0 ˜
Á 0 0 0 0 0 c(3) 0 0 0 ˜
Á ˜
Á ˜
Á ˜
Á 0 0 0 0 0 0 c(1) 0 0 ˜
Á 0 0 0 0 0 0 0 c(2) 0 ˜
ÁÁ ˜
Ë 0 0 0 0 0 0 0 0 c(3) ˜¯
Ê c(1) 0 0 0 0 0 L 0 0 0 ˆ
Á ˜
Á 0 c (2) 0 0 0 0 L 0 0 0 ˜
Á 0 0 c(3) 0 0 0 L 0 0 0 ˜
Á ˜
Á ˜
Á 0 0 0 c(4) 0 0 L 0 0 0 ˜
Á ˜
Á 0 0 0 0 c( 5) 0 L 0 0 0 ˜
Á 0 0 0 0 0 c( 6) L 0 0 0 ˜
Á ˜
Á M M M M M M O M M M ˜
Á ˜
Á 0 0 0 0 0 0 L c( 3 N - 2) 0 0 ˜
Á 0 0 0 0 0 0 L 0 c(3 N - 1) 0 ˜
ÁÁ ˜
Ë 0 0 0 0 0 0 L 0 0 c(3 N ) ˜¯
2-144
c Coefficient for Systems
Caution If N = 3, the 9-element form takes precedence over the 3N-element form. For
example, if your c matrix is
Ê c(1) 0 0 0 0 0 0 0 ˆ
0
Á ˜
Á 0 c(2) 0 0 0 0 0 0 0
˜
Á 0 0 c(3) 0 0 0 0 0 ˜
0
Á ˜
Á ˜
Á 0 0 0 c(4) 0 0 0 0 0 ˜
Á ˜
Á 0 0 0 0 c( 5) 0 0 0 0 ˜
Á 0 0 0 0 0 c( 6) 0 0 0 ˜
Á ˜
Á ˜
Á ˜
Á 0 0 0 0 0 0 c(7) 0 0 ˜
Á 0 0 0 0 0 0 0 c(8) 0 ˜
ÁÁ ˜
Ë 0 0 0 0 0 0 0 0 c(9) ˜¯
2-145
2 Setting Up Your PDE
• 9N-element form —
[c1;0;0;0;c2;0;0;0;c3;c4;0;0;0;c5;0;0;0;c6;c7;0;0;0;c8;0;0;0;c9]
2-146
c Coefficient for Systems
2-147
2 Setting Up Your PDE
2-148
m, d, or a Coefficient for specifyCoefficients
In this section...
“Coefficients m, d, or a” on page 2-149
“Short m, d, or a vectors” on page 2-150
“Nonconstant m, d, or a” on page 2-151
Coefficients m, d, or a
This section describes how to write the m, d, or a coefficients in the system of equations
∂2 u ∂u
m +d - —·( c ƒ —u ) + au = f
2 ∂t
∂t
- —·( c ƒ — u ) + au = l du
or
- —·( c ƒ — u ) + au = l 2mu
The topic applies to the recommended workflow for including coefficients in your model
using specifyCoefficients.
If there are N equations in the system, then these coefficients represent N-by-N matrices.
For constant (numeric) coefficient matrices, represent each coefficient using a column
vector with N2 components. This column vector represents, for example, m(:).
Note The d coefficient takes a special matrix form when m is nonzero. See “d Coefficient
When m is Nonzero” on page 5-925.
2-149
2 Setting Up Your PDE
Short m, d, or a vectors
Sometimes, your m, d, or a matrices are diagonal or symmetric. In these cases, you can
represent m, d, or a using a smaller vector than one with N2 components. The following
sections give the possibilities.
Scalar m, d, or a
Êa 0 L 0ˆ
Á ˜
Á0 a L 0˜
ÁM M O M˜
Á ˜
Ë 0 0 L a¯
Ê d(1) 0 L 0 ˆ
Á ˜
Á 0 d(2) L 0 ˜
Á M M O M ˜
Á ˜
Ë 0 0 L d( N ) ¯
2-150
m, d, or a Coefficient for specifyCoefficients
Ê d(1) d ( N + 1) L d( N 2 - N + 1) ˆ
Á ˜
Á d( 2) d( N + 2) L d ( N 2 - N + 2) ˜
Á ˜
Á M M O M ˜
Á 2 ˜
Ë d( N ) d( 2 N ) L d( N ) ¯
Nonconstant m, d, or a
Note If both m and d are nonzero, then d must be a constant scalar or vector, not a
function.
• N1 is the length of the vector representing the coefficient. There are several possible
values of N1, detailed in “Short m, d, or a vectors” on page 2-150. 1 ≤ N1 ≤ N2.
• Nr is the number of points in the location that the solver passes. Nr is equal to the
length of the location.x or any other location field. The function should evaluate
m, d, or a at these points.
2-151
2 Setting Up Your PDE
specifyCoefficients(model,'d',@dcoeffunction,...)
• location.x
• location.y
• location.z
• location.subdomain
The fields x, y, and z represent the x-, y-, and z- coordinates of points for which your
function calculates coefficient values. The subdomain field represents the subdomain
numbers, which currently apply only to 2-D models. The location fields are row
vectors.
• state is a structure with these fields:
• state.u
• state.ux
• state.uy
• state.uz
• state.time
The state.u field represents the current value of the solution u. The state.ux,
state.uy, and state.uz fields are estimates of the solution’s partial derivatives (∂u/
∂x, ∂u/∂y, and ∂u/∂z) at the corresponding points of the location structure. The solution
and gradient estimates are N-by-Nr matrices. The state.time field is a scalar
representing time for time-dependent models.
For example, suppose N = 3, and you have 2-D geometry. Suppose your d matrix is of the
form
È 1 s1 ( x, y) x2 + y2 ˘
Í ˙
d = Í s1 ( x, y) 4 -1 ˙
Í ˙
ÍÎ x2 + y2 -1 9 ˙˚
2-152
See Also
n1 = 6;
nr = numel(location.x);
dmatrix = zeros(n1,nr);
dmatrix(1,:) = ones(1,nr);
dmatrix(2,:) = 5*location.subdomain;
dmatrix(3,:) = 4*ones(1,nr);
dmatrix(4,:) = sqrt(location.x.^2 + location.y.^2);
dmatrix(5,:) = -ones(1,nr);
dmatrix(6,:) = 9*ones(1,nr);
To include this function as your d coefficient, pass the function handle @dcoeffunction:
specifyCoefficients(model,'d',@dcoeffunction,...
See Also
Related Examples
• “f Coefficient for specifyCoefficients” on page 2-107
• “c Coefficient for specifyCoefficients” on page 2-110
• “Solve Problems Using PDEModel Objects” on page 2-6
• “Deflection of Piezoelectric Actuator” on page 3-13
2-153
2 Setting Up Your PDE
Note THIS PAGE DESCRIBES THE LEGACY WORKFLOW. New features might not be
compatible with the legacy workflow. For the corresponding step in the recommended
workflow, see “m, d, or a Coefficient for specifyCoefficients” on page 2-149.
In this section...
“Coefficients a or d” on page 2-154
“Scalar a or d” on page 2-155
“N-Element Column Vector a or d” on page 2-155
“N(N+1)/2-Element Column Vector a or d” on page 2-155
“N2-Element Column Vector a or d” on page 2-156
Coefficients a or d
This section describes how to write the coefficients a or d in the equation
∂u
d - — ◊ ( c ƒ — u ) + au = f
∂t
or in similar equations. a and d are N-by-N matrices, where N is the number of equations,
see “Equations You Can Solve Using Legacy Functions” on page 1-3.
The number of rows in the matrix is either 1, N, N(N+1)/2, or N2, as described in the next
few sections. If you choose to express the coefficients in functional form, the number of
columns is Nt, which is the number of triangles in the mesh. The function should evaluate
a or d at the triangle centroids, as in “Specify 2-D Scalar Coefficients in Function Form”
on page 2-82. Give solvers the function name as 'filename', or as a function handle
@filename, where filename.m is a file on your MATLAB path. For details on how to
write the function, see “Calculate Coefficients in Function Form” on page 2-83.
Often, a or d have structure, either as symmetric or diagonal. In these cases, you can
represent a or d using fewer than N2 rows.
2-154
a or d Coefficient for Systems
Scalar a or d
The software interprets a scalar a or d as a diagonal matrix.
Êa 0 L 0ˆ
Á ˜
Á0 a L 0˜
ÁM M O M˜
Á ˜
Ë 0 0 L a¯
Ê d(1) 0 L 0 ˆ
Á ˜
Á 0 d(2) L 0 ˜
Á M M O M ˜
Á ˜
Ë 0 0 L d( N ) ¯
a =
sin(x) + cos(y)
cosh(x.*y)
x.*y./(1+x.^2+y.^2)
2-155
2 Setting Up Your PDE
Ê d(1) d ( N + 1) L d( N 2 - N + 1) ˆ
Á ˜
Á d( 2) d( N + 2) L d ( N 2 - N + 2) ˜
Á ˜
Á M M O M ˜
Á 2 ˜
Ë d( N ) d( 2 N ) L d( N ) ¯
2-156
View, Edit, and Delete PDE Coefficients
View Coefficients
A PDE model stores coefficients in its EquationCoefficients property. Suppose model
is the name of your model. Obtain the coefficients:
coeffs = model.EquationCoefficients;
To see the active coefficient assignment for a region, call the findCoefficients
function. For example, create a model and view the geometry.
model = createpde();
geometryFromEdges(model,@lshapeg);
pdegplot(model,'FaceLabels','on')
ylim([-1.1,1.1])
axis equal
2-157
2 Setting Up Your PDE
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',0,'f',2);
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',0,'f',3,'Face',2);
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',0,'f',4,'Face',3);
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',1,'f',3,'Face',2);
2-158
View, Edit, and Delete PDE Coefficients
coeffs = model.EquationCoefficients;
findCoefficients(coeffs,'Face',2)
ans =
CoefficientAssignment with properties:
RegionType: 'face'
RegionID: 2
m: 0
d: 0
c: 1
a: 1
f: 3
findCoefficients(coeffs,'Face',1)
ans =
CoefficientAssignment with properties:
RegionType: 'face'
RegionID: [1 2 3]
m: 0
d: 0
c: 1
a: 0
f: 2
The active coefficient assignment for region 1 includes all three regions, though this
assignment is no longer active for regions 2 and 3.
delete(model.EquationCoefficients)
2-159
2 Setting Up Your PDE
coefv = model.EquationCoefficients.CoefficientAssignments;
delete(coefv(2))
Tip You do not need to delete coefficients; you can override them by calling
specifyCoefficients again. However, deleting unused assignments can make your
model smaller.
coefh1 = specifyCoefficients(model,'m',m,'d',d,'c',c,'a',a,'f',f);
• Obtain the handle using findCoefficients. For example,
coeffs = model.EquationCoefficients;
coefh1 = findCoefficients(coeffs,'face',2);
You can change any property of the coefficient handle. For example,
coefh1.RegionID = [1,3];
coefh1.a = 2;
coefh1.c = @ccoeffun;
Note Editing an existing assignment in this way does not change its priority. For
example, if the active coefficient in region 3 was assigned after coefh1, then editing
coefh1 to include region 3 does not make coefh1 the active coefficient in region 3.
2-160
Set Initial Conditions
• For time-dependent problems, the initial condition is the solution u at the initial time,
and also the initial time-derivative if the m coefficient is nonzero. Set the initial
condition in the model using setInitialConditions.
• For nonlinear stationary problems, the initial condition is a guess or approximation of
the solution u at the initial iteration of the nonlinear solver. Set the initial condition in
the model using setInitialConditions.
If you do not specify the initial condition for a stationary problem, solvepde uses the
zero function for the initial iteration.
If N = 3, and the initial condition is 15 for the first equation, 0 for the second equation,
and –3 for the third equation, use the following commands.
u0 = [15,0,-3];
setInitialConditions(model,u0);
If the m coefficient is nonzero, give an initial condition for the time derivative as well. Set
this initial derivative in the same form as the first initial condition. For example, if the
initial derivative of the solution is [4,3,0], use the following commands.
u0 = [15,0,-3];
ut0 = [4,3,0];
setInitialConditions(model,u0,ut0);
2-161
2 Setting Up Your PDE
function u0 = initfun(location)
∂2 u È 3+ x ˘
- —·( —u ) = Í ˙
∂t2
Î 4 - x - y˚
È4 + x2 + y2 ˘
u(0) = Í ˙
ÍÎ 0 ˙˚
∂u È 0 ˘
(0) = Í ˙
∂t Îsin( xy) ˚
È 3+ x ˘
This problem has m = 1, c = 1, and f = Í ˙ . Because m is nonzero, give both an
initial value of u and an initial value of the - x - y˚
Î4 derivative of u.
Write the following function files. Save them to a location on your MATLAB path.
M = length(location.x);
uinit = zeros(2,M);
uinit(1,:) = 4 + location.x.^2 + location.y.^2;
M = length(location.x);
utinit = zeros(2,M);
utinit(2,:) = sin(location.x.*location.y);
u0 = @u0fun;
ut0 = @ut0fun;
setInitialConditions(model,u0,ut0);
2-162
See Also
results = solvepde(model,t0:tstep:t1);
If later you need to solve this PDE problem for times from t1 to t2, you can use results
to set initial conditions. If you do not explicitly specify the time step,
setInitialConditions uses results corresponding to the last solution time, t1.
setInitialConditions(model,results)
To use results for a particular solution time instead of the last one, specify the solution
time index as a third parameter of setInitialConditions. For example, to use the
solution at time t0 + 10*tstep, specify 11 as the third parameter.
setInitialConditions(model,results,11)
See Also
Related Examples
• “Solve Problems Using PDEModel Objects” on page 2-6
• “Wave Equation on Square Domain”
• “Inhomogeneous Heat Equation on Square Domain”
• “Heat Distribution in Circular Cylindrical Rod”
• “Heat Transfer Problem with Temperature-Dependent Properties”
• “Dynamic Analysis of Clamped Beam”
2-163
2 Setting Up Your PDE
inits = model.InitialConditions;
To see the active initial conditions assignment for a region, call the
findInitialConditions function. For example, create a model and view the geometry.
model = createpde();
geometryFromEdges(model,@lshapeg);
pdegplot(model,'FaceLabels','on')
ylim([-1.1,1.1])
axis equal
2-164
View, Edit, and Delete Initial Conditions
Specify constant initial conditions over all the regions in the model.
setInitialConditions(model,2);
setInitialConditions(model,3,'Face',2);
setInitialConditions(model,4,'Face',3);
ics = model.InitialConditions;
findInitialConditions(ics,'Face',2)
2-165
2 Setting Up Your PDE
ans =
GeometricInitialConditions with properties:
RegionType: 'face'
RegionID: 2
InitialValue: 3
InitialDerivative: []
findInitialConditions(ics,'Face',1)
ans =
GeometricInitialConditions with properties:
RegionType: 'face'
RegionID: [1 2 3]
InitialValue: 2
InitialDerivative: []
The active initial conditions assignment for region 1 includes all three regions, though
this assignment is no longer active for regions 2 and 3.
delete(model.InitialConditions)
icv = model.InitialConditions.InitialConditionAssignments;
delete(icv(2))
2-166
View, Edit, and Delete Initial Conditions
Tip You do not need to delete initial conditions; you can override them by calling
setInitialConditions again. However, deleting unused assignments can make your
model smaller.
ics1 = setInitialConditions(model,2);
• Obtain the handle using findInitialConditions. For example,
ics = model.InitialConditions;
ics1 = findInitialConditions(ics,'Face',2);
You can change any property of the initial conditions handle. For example,
ics1.RegionID = [1,3];
ics1.InitialValue = 2;
ics1.InitialDerivative = @ut0fun;
Note Editing an existing assignment in this way does not change its priority. For
example, if the active initial conditions in region 3 was assigned after ics1, then editing
ics1 to include region 3 does not make ics1 the active initial condition in region 3.
2-167
2 Setting Up Your PDE
Note THIS PAGE DESCRIBES THE LEGACY WORKFLOW. New features might not be
compatible with the legacy workflow. For the corresponding step in the recommended
workflow, see “Set Initial Conditions” on page 2-161.
• For the parabolic and hyperbolic solvers, the initial condition u0 is the solution u
at the initial time. You must specify the initial condition for these solvers. Pass the
initial condition in the first argument or arguments.
u = parabolic(u0,...
or
u = hyperbolic(u0,ut0,...
For the hyperbolic solver, you must also specify ut0, which is the value of the
derivative of u with respect to time at the initial time. ut0 has the same form as u0.
• For nonlinear elliptic problems, the initial condition u0 is a guess or approximation of
the solution u at the initial iteration of the pdenonlin nonlinear solver. You pass u0 in
the 'U0' name-value pair.
u = pdenonlin(b,p,e,t,c,a,f,'U0',u0)
If you do not specify initial conditions, pdenonlin uses the zero function for the initial
iteration.
• For scalar problems or systems of equations, give a scalar as the initial condition. For
example, set u0 to 5 for an initial condition of 5 in every component.
• For systems of N equations, give a character vector initial condition with N rows. For
example, if there are N = 3 equations, you can give initial conditions
u0 = char('3','-3','0').
2-168
Solve PDEs with Initial Conditions
xy cos( x)
u( x, y) =
1 + x2 + y2
then you can use this expression for the initial condition.
For a system of N > 1 equations, use a text array with one row for each component, such
as
char('x.^2 + 5*cos(x.*y)',...
'tanh(x.*y)./(1 + z.^2)')
Tip For reliability, the initial conditions and boundary conditions should be consistent.
The size of the column vector u0 depends on the number of equations, N, and on the
number of nodes in the mesh, Np.
For scalar u, specify a column vector of length Np. The value of element k corresponds to
the node p(k).
For a system of N equations, specify a column vector of N*Np elements. The first Np
elements contain the values of component 1, where the value of element k corresponds to
node p(k). The next Np points contain the values of component 2, etc. It can be
2-169
2 Setting Up Your PDE
convenient to first represent the initial conditions u0 as an Np-by-N matrix, where the first
column contains entries for component 1, the second column contains entries for
component 2, etc. The final representation of the initial conditions is u0(:).
For example, suppose you have a function myfun(x,y) that calculates the value of the
initial condition u0(x,y) as a row vector of length N for a 2-D problem. Suppose that p is
the usual mesh node data (see “Mesh Data” on page 2-241). Compute the initial
conditions for all mesh nodes p.
2-170
No Boundary Conditions Between Subdomains
• Boundaries between the interior of the region and the exterior of the region
• Boundaries between subdomains - these are boundaries in the interior of the region
For example, look at a rectangular region with a circular subdomain. The red numbers
are the subdomain labels, the black numbers are the edge segment labels.
% Set formula
sf = 'R1 + C1';
% Create geometry
gd = decsg(geom,sf,ns);
% View geometry
pdegplot(gd,'EdgeLabels','on','SubdomainLabels','on')
xlim([-1.1 1.1])
axis equal
2-171
2 Setting Up Your PDE
You need not give boundary conditions on segments 5, 6, 7, and 8, because these are
subdomain boundaries, not exterior boundaries.
However, if the circle is a hole, meaning it is not part of the region, then you do give
boundary conditions on segments 5, 6, 7, and 8.
2-172
Identify Boundary Labels
pdegplot(g,'EdgeLabels','on')
For example, look at the edge labels for a simple annulus geometry:
2-173
2 Setting Up Your PDE
2-174
Boundary Matrix for 2-D Geometry
Note THIS PAGE DESCRIBES THE LEGACY WORKFLOW. New features might not be
compatible with the legacy workflow. For the corresponding step in the recommended
workflow, see “Specify Boundary Conditions” on page 2-181.
For each column in the Decomposed Geometry matrix (see “Decomposed Geometry Data
Structure” on page 2-15) there must be a corresponding column in the Boundary
Condition matrix. The format of each column is:
The following rows contain text expressions representing the actual boundary condition
functions. The vectors of characters have the lengths according to above. The MATLAB
text expressions are stored in column-wise order with respect to matrices h and q. There
are no separation characters between the vectors of characters. You can insert MATLAB
expressions containing the following variables:
2-175
2 Setting Up Your PDE
It is not possible to explicitly refer to the time derivative of the solution in the boundary
conditions.
n · ( c—u ) = - x2
[1 0 1 5 '0' '-x.^2']'
u = x2 – y2
( h11 h12 ) u = r1
Êq q12 ˆ Ê g1 ˆ
n · ( c ƒ — u ) + Á 11 ˜u = Á ˜ + s
Ë q21 q22 ¯ Ë g2 ¯
2-176
Boundary Matrix for 2-D Geometry
2
1
lq11
lq21
lq12
lq22
lg1
lg2
lh11
lh12
lr1
q11 ...
q21 ...
q12 ...
q22 ...
g1 ...
g2 ...
h11 ...
h12 ...
r1 ...
lq11, lq21, . . . denote lengths of the MATLAB text expressions, and q11, q21, . . .
denote the actual expressions.
You can easily create your own examples by trying out the PDE Modeler app. Enter
boundary conditions by double-clicking on boundaries in boundary mode, and then export
the Boundary Condition matrix to the MATLAB workspace by selecting the Export
Decomposed Geometry, Boundary Cond's option from the Boundary menu.
2-177
2 Setting Up Your PDE
nbs = 4;
function assemb_example
% Use ASSEMB to find the boundary condition matrices.
2-178
Boundary Matrix for 2-D Geometry
Q =
G =
H =
(1,1) 1
(2,2) 1
(3,3) 1
(4,4) 1
(5,5) 1
(6,6) 1
(7,7) 1
(8,8) 1
(9,9) 1
(10,10) 1
(11,11) 1
(12,12) 1
(13,13) 1
(14,14) 1
(15,15) 1
(16,16) 1
R =
(1,1) 1.0000
(2,1) -1.0000
(3,1) 1.0000
(4,1) -1.0000
(5,1) 0.0000
(6,1) -0.0000
2-179
2 Setting Up Your PDE
(7,1) 0.0000
(8,1) -0.0000
(9,1) 0.7071
(10,1) -0.7071
(11,1) -0.7071
(12,1) 0.7071
(13,1) 0.7071
(14,1) -0.7071
(15,1) -0.7071
(16,1) 0.7071
Q and G are all zero sparse matrices because the problem has only Dirichlet boundary
conditions and neither generalized Neumann nor mixed boundary conditions apply.
See Also
Related Examples
• “Specify Boundary Conditions” on page 2-181
2-180
Specify Boundary Conditions
Now you can specify the boundary conditions for each edge or face. If you have a system
of PDEs, you can set a different boundary condition for each component on each boundary
edge or face. If the boundary condition is a function of position, time, or the solution u,
set boundary conditions by using the syntax in “Nonconstant Boundary Conditions” on
page 2-186.
If you do not specify a boundary condition for an edge or face, the default is the Neumann
boundary condition with the zero values for 'g' and 'q'.
The Dirichlet boundary condition implies that the solution u on a particular edge or face
satisfies the equation
hu = r,
where h and r are functions defined on ∂Ω, and can be functions of space (x, y, and, in 3-
D, z), the solution u, and, for time-dependent equations, time. Often, you take h = 1, and
set r to the appropriate value. You can specify Dirichlet boundary conditions as the value
of the solution u on the boundary or as a pair of the parameters h and r.
Suppose that you have a PDE model named model, and edges or faces [e1,e2,e3],
where the solution u must equal 2. Specify this boundary condition as follows.
2-181
2 Setting Up Your PDE
If the solution on edges or faces [e1,e2,e3] satisfies the equation 2u = 3, specify the
boundary condition as follows.
% For 3-D geometry:
applyBoundaryCondition(model,'dirichlet','Face',[e1,e2,e3],'r',3,'h',2);
% For 2-D geometry:
applyBoundaryCondition(model,'dirichlet','Edge',[e1,e2,e3],'r',3,'h',2);
Systems of PDEs
Suppose that you have a PDE model named model, and edge or face labels [e1,e2,e3]
where the first component of the solution u must equal 1, while the second and third
components must equal 2. Specify this boundary condition as follows.
% For 3-D geometry:
applyBoundaryCondition(model,'dirichlet','Face',[e1,e2,e3],...
'u',[1,2,2],'EquationIndex',[1,2,3]);
% For 2-D geometry:
applyBoundaryCondition(model,'dirichlet','Edge',[e1,e2,e3],...
'u',[1,2,2],'EquationIndex',[1,2,3]);
• The 'u' and 'EquationIndex' arguments must have the same length.
• If you exclude the 'EquationIndex' argument, the 'u' argument must have length
N.
• If you exclude the 'u' argument, applyBoundaryCondition sets the components in
'EquationIndex' to 0.
Suppose that you have a PDE model named model, and edge or face labels [e1,e2,e3]
where the first, second, and third components of the solution u must satisfy the equations
2u1 = 3, 4u2 = 5, and 6u3 = 7, respectively. Specify this boundary condition as follows.
H0 = [2 0 0;
0 4 0;
0 0 6];
R0 = [3;5;7];
% For 3-D geometry:
applyBoundaryCondition(model,'dirichlet', ...
2-182
Specify Boundary Conditions
'Face',[e1,e2,e3], ...
'h',H0,'r',R0);
% For 2-D geometry:
applyBoundaryCondition(model,'dirichlet', ...
'Edge',[e1,e2,e3], ...
'h',H0,'r',R0);
• The 'r' parameter must be a numeric vector of length N. If you do not specify 'r',
applyBoundaryCondition sets the values to 0.
• The 'h' parameter can be an N-by-N numeric matrix or a vector of length N2
corresponding to the linear indexing form of the N-by-N matrix. For details about the
linear indexing form, see “Array Indexing” (MATLAB). If you do not specify 'h',
applyBoundaryCondition sets the value to the identity matrix.
Generalized Neumann boundary conditions imply that the solution u on the edge or face
satisfies the equation
n ·( c— u) + qu = g
r
The coefficient c is the same as the coefficient of the second-order differential operator in
the PDE equation
-— ◊ ( c—u ) + au = f on domain W
n is the outward unit normal. q and g are functions defined on ∂Ω, and can be functions
r
of space (x, y, and, in 3-D, z), the solution u, and, for time-dependent equations, time.
Suppose that you have a PDE model named model, and edges or faces [e1,e2,e3]
where the solution u must satisfy the Neumann boundary condition with q = 2 and g =
3. Specify this boundary condition as follows.
2-183
2 Setting Up Your PDE
Systems of PDEs
N
Ê ∂ ∂ ∂ ∂ ˆ
 ÁË cos(a )ci, j,1,1 ∂x + cos(a)ci, j ,1,2 ∂y + sin(a)ci, j ,2,1 ∂x + sin(a)ci, j ,2,2 ∂y ˜¯ u j
j =1
For 3-D systems, the notation n · ( c ƒ — u ) means the N-by-1 vector with (i,1)-component
N
Ê ∂ ∂ ∂ ˆ
 ÁË sin (j ) cos (q ) ci, j ,1,1 ∂x + sin (j ) cos (q ) ci, j,1,2 ∂y + sin (j )cos (q ) ci, j ,1,3 ∂z ˜¯ u j
j =1
N
Ê ∂ ∂ ∂ ˆ
+  ÁË sin (j ) sin (q ) ci, j,2,1 ∂x + sin (j )s in (q ) ci, j ,2,2 ∂y + sin (j ) sin (q ) ci, j,2,3 ∂z ˜¯ u j
j =1
N
Ê ∂ ∂ ∂ ˆ
+  ÁË cos (q ) ci, j,3,1 ∂x + cos (q ) ci, j ,3,2 ∂y + cos (q ) ci, j ,3,3 ∂z ˜¯ u j
j =1
where the outward normal vector of the boundary n = ( sin(j) cos(q ),sin(j ) sin(q ),cos(j) ) .
For each edge or face segment, there are a total of N boundary conditions.
Suppose that you have a PDE model named model, and edges or faces [e1,e2,e3]
where the first component of the solution u must satisfy the Neumann boundary condition
with q = 2 and g = 3, and the second component must satisfy the Neumann boundary
condition with q = 4 and g = 5. Specify this boundary condition as follows.
Q = [2 0; 0 4];
G = [3;5];
% For 3-D geometry:
applyBoundaryCondition(model,'neumann','Face',[e1,e2,e3],'q',Q,'g',G);
2-184
Specify Boundary Conditions
• The 'g' parameter must be a numeric vector of length N. If you do not specify 'g',
applyBoundaryCondition sets the values to 0.
• The 'q' parameter can be an N-by-N numeric matrix or a vector of length N2
corresponding to the linear indexing form of the N-by-N matrix. For details about the
linear indexing form, see “Array Indexing” (MATLAB). If you do not specify 'q',
applyBoundaryCondition sets the values to 0.
Suppose that you have a PDE model named model, and edge or face labels [e1,e2,e3]
where the first component of the solution u must equal 11, the second component must
equal 22, and the third component must satisfy the Neumann boundary condition with q
= 3 and g = 4. Express this boundary condition as follows.
Q = [0 0 0; 0 0 0; 0 0 3];
G = [0;0;4];
% For 3-D geometry:
applyBoundaryCondition(model,'mixed','Face',[e1,e2,e3],...
'u',[11,22],'EquationIndex',[1,2],...
'q',Q,'g',G);
% For 2-D geometry:
applyBoundaryCondition(model,'mixed',...
'Edge',[e1,e2,e3],'u',[11,22],...
'EquationIndex',[1,2],'q',Q,'g',G);
Suppose that you have a PDE model named model, and edges or faces [e1,e2,e3]
where the first component of the solution u must satisfy the Dirichlet boundary condition
2u1 = 3, the second component must satisfy the Neumann boundary condition with q = 4
and g = 5, and the third component must satisfy the Neumann boundary condition with
q = 6 and g = 7. Express this boundary condition as follows.
h = [2 0 0; 0 0 0; 0 0 0];
r = [3;0;0];
2-185
2 Setting Up Your PDE
Q = [0 0 0; 0 4 0; 0 0 6];
G = [0;5;7];
% For 3-D geometry:
applyBoundaryCondition(model,'mixed', ...
'Face',[e1,e2,e3], ...
'h',h,'r',r,'q',Q,'g',G);
% For 2-D geometry:
applyBoundaryCondition(model,'mixed', ...
'Edge',[e1,e2,e3], ...
'h',h,'r',r,'q',Q,'g',G);
applyBoundaryCondition(model,'dirichlet', ...
'Edge',1, ...
'r',@myrfun);
applyBoundaryCondition(model,'neumann', ...
'Face',2, ...
'g',@mygfun,'q',@myqfun);
applyBoundaryCondition(model,'mixed', ...
'Edge',[3,4], ...
'u',@myufun, ...
'EquationIndex',[2,3]);
Partial Differential Equation Toolbox solvers pass the location and state data to your
function.
• location — A structure containing the following fields. If you pass a name-value pair
to applyBoundaryCondition with Vectorized set to 'on', then location can
contain several evaluation points. If you do not set Vectorized or use
Vectorized,'off', then solvers pass just one evaluation point in each call.
2-186
Specify Boundary Conditions
Furthermore, if there are Neumann conditions, then solvers pass the following data in
the location structure.
Your function returns bcMatrix. This matrix has the following form, depending on the
boundary condition type.
• 'u' — N1-by-M matrix, where each column corresponds to one evaluation point, and
M is the number of evaluation points. N1 is the length of the 'EquationIndex'
argument. If there is no 'EquationIndex' argument, then N1 = N.
• 'r' or 'g' — N-by-M matrix, where each column corresponds to one evaluation point,
and M is the number of evaluation points.
• 'h' or 'q' — N2-by-M matrix, where each column corresponds to one evaluation point
via linear indexing of the underlying N-by-N matrix, and M is the number of evaluation
points. Alternatively, an N-by-N-by-M array, where each evaluation point is an N-by-N
matrix. For details about linear indexing, see “Array Indexing” (MATLAB).
2-187
2 Setting Up Your PDE
Geometry
All the specifications use the same 2-D geometry, which is a rectangle with a circular hole.
% Set formula
sf = 'R1 - C1';
% Create geometry
g = decsg(geom,sf,ns);
2-188
Solve PDEs with Constant Boundary Conditions
Scalar Problem
Suppose that edge 3 has Dirichlet conditions with value 32, edge 1 has Dirichlet
conditions with value 72, and all other edges have Neumann boundary conditions with q
= 0, g = -1.
applyBoundaryCondition(model,'dirichlet','edge',3,'u',32);
applyBoundaryCondition(model,'dirichlet','edge',1,'u',72);
applyBoundaryCondition(model,'neumann','edge',[2,4:8],'g',-1);
2-189
2 Setting Up Your PDE
Solve an elliptic PDE with these boundary conditions with c = 1, a = 0, and f = 10.
Because the shorter rectangular side has length 0.8, to ensure that the mesh is not too
coarse choose a maximum mesh size Hmax = 0.1.
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',0,'f',10);
generateMesh(model,'Hmax',0.1);
results = solvepde(model);
u = results.NodalSolution;
pdeplot(model,'XYData',u,'ZData',u)
view(-23,8)
2-190
Solve PDEs with Constant Boundary Conditions
System of PDEs
Suppose that the system has N = 2.
model = createpde(2);
geometryFromEdges(model,g);
applyBoundaryCondition(model,'dirichlet','edge',3,'u',[32,72]);
applyBoundaryCondition(model,'dirichlet','edge',1,'u',[72,32]);
applyBoundaryCondition(model,'mixed','edge',4,'u',52,'EquationIndex',1,'g',[0,-1]);
Q2 = [1,2;3,4];
G2 = [5,-6];
applyBoundaryCondition(model,'neumann','edge',2,'q',Q2,'g',G2);
% The next step is optional, because it sets 'g' to its default value
applyBoundaryCondition(model,'neumann','edge',5:8,'g',[0,0]);
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',0,'f', [10;-10]);
generateMesh(model,'Hmax',0.1);
results = solvepde(model);
u = results.NodalSolution;
pdeplot(model,'XYData',u(:,2),'ZData',u(:,2))
2-191
2 Setting Up Your PDE
See Also
More About
• “Specify Boundary Conditions” on page 2-181
• “Solve PDEs with Nonconstant Boundary Conditions” on page 2-193
2-192
Solve PDEs with Nonconstant Boundary Conditions
Geometry
All the specifications use the same geometry, which is a rectangle with a circular hole.
% Set formula
sf = 'R1-C1';
% Create geometry
g = decsg(geom,sf,ns);
2-193
2 Setting Up Your PDE
Scalar Problem
• Edge 3 has Dirichlet conditions with value 32.
• Edge 1 has Dirichlet conditions with value 72.
• Edges 2 and 4 have Dirichlet conditions that linearly interpolate between edges 1 and
3.
• The circular edges (5 through 8) have Neumann conditions with q = 0, g = -1.
applyBoundaryCondition(model,'dirichlet','Edge',3,'u',32);
applyBoundaryCondition(model,'dirichlet','Edge',1,'u',72);
applyBoundaryCondition(model,'neumann','Edge',5:8,'g',-1); % q = 0 by default
2-194
Solve PDEs with Nonconstant Boundary Conditions
Edges 2 and 4 need functions that perform the linear interpolation. Each edge can use the
same function that returns the value .
Include the function for edges 2 and 4. To help speed the solver, allow a vectorized
evaluation.
applyBoundaryCondition(model,'dirichlet','Edge',[2,4],...
'u',myufunction,...
'Vectorized','on');
Solve an elliptic PDE with these boundary conditions, using the parameters c = 1, a =
0, and | f = 10|. Because the shorter rectangular side has length 0.8, to ensure that the
mesh is not too coarse choose a maximum mesh size Hmax = 0.1.
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',0,'f',10);
generateMesh(model,'Hmax',0.1);
results = solvepde(model);
u = results.NodalSolution;
pdeplot(model,'XYData',u)
2-195
2 Setting Up Your PDE
System of PDEs
Suppose that the system has N = 2.
2-196
Solve PDEs with Nonconstant Boundary Conditions
applyBoundaryCondition(model,'dirichlet','Edge',3,'u',[32,72]);
applyBoundaryCondition(model,'dirichlet','Edge',1,'u',[72,32]);
applyBoundaryCondition(model,'neumann','Edge',5:8,'g',[-10,-10]);
Write a function file myufun.m that incorporates these equations in the syntax described
in “Nonconstant Boundary Conditions” on page 2-186.
applyBoundaryCondition(model,'dirichlet','Edge',[2,4],...
'u',@myufun,...
'Vectorized','on');
Solve an elliptic PDE with these boundary conditions, with the parameters c = 1, a = 0,
and f = (10,-10). Because the shorter rectangular side has length 0.8, to ensure that
the mesh is not too coarse choose a maximum mesh size Hmax = 0.1.
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',0,'f',[10;-10]);
generateMesh(model,'Hmax',0.1);
results = solvepde(model);
u = results.NodalSolution;
subplot(1,2,1)
pdeplot(model,'XYData',u(:,1),'ZData',u(:,1),'ColorBar','off')
view(-9,24)
subplot(1,2,2)
pdeplot(model,'XYData',u(:,2),'ZData',u(:,2),'ColorBar','off')
view(-9,24)
2-197
2 Setting Up Your PDE
2-198
View, Edit, and Delete Boundary Conditions
BCs = model.BoundaryConditions;
To see the active boundary condition assignment for a region, call the
findBoundaryConditions function.
model = createpde(3);
importGeometry(model,'Block.stl');
pdegplot(model,'FaceLabels','on','FaceAlpha',0.5)
2-199
2 Setting Up Your PDE
Set zero Dirichlet conditions for all equations and all regions in the model.
applyBoundaryCondition(model,'dirichlet','Face',1:6,'u',[0,0,0]);
On face 3, set the Neumann boundary condition for equation 1 and Dirichlet boundary
condition for equations 2 and 3.
2-200
View, Edit, and Delete Boundary Conditions
View the boundary condition assignment for face 3. The result shows that the active
boundary condition is the last assignment.
BCs = model.BoundaryConditions;
findBoundaryConditions(BCs,'Face',3)
ans =
BoundaryCondition with properties:
BCType: 'mixed'
RegionType: 'Face'
RegionID: 3
r: [3x1 double]
h: [3x3 double]
g: [3x1 double]
q: [3x3 double]
u: []
EquationIndex: []
Vectorized: 'off'
findBoundaryConditions(BCs,'Face',1)
ans =
BoundaryCondition with properties:
BCType: 'dirichlet'
RegionType: 'Face'
RegionID: [1 2 3 4 5 6]
r: []
h: []
g: []
q: []
u: [0 0 0]
EquationIndex: []
Vectorized: 'off'
The active boundary conditions assignment for face 1 includes all six faces, though this
assignment is no longer active for face 3.
2-201
2 Setting Up Your PDE
To remove specific boundary conditions assignments from pdem, delete them from the
pdem.BoundaryConditions.BoundaryConditionAssignments vector. For example,
BCv = pdem.BoundaryConditions.BoundaryConditionAssignments;
delete(BCv(2))
Tip You do not need to delete boundary conditions; you can override them by calling
applyBoundaryCondition again. However, removing unused assignments can make
your model more concise.
bc1 =
BCType: 'dirichlet'
RegionType: 'Face'
RegionID: [1 2 3 4 5 6]
r: []
h: []
g: []
q: []
2-202
See Also
u: [0 0 0]
EquationIndex: []
Vectorized: 'off'
You can change any property of the boundary conditions handle. For example,
bc1.BCType = 'neumann';
bc1.u = [];
bc1.g = [0 0 0];
bc1.q = [0 0 0];
bc1
bc1 =
BCType: 'neumann'
RegionType: 'Face'
RegionID: [1 2 3 4 5 6]
r: []
h: []
g: [0 0 0]
q: [0 0 0]
u: []
EquationIndex: []
Vectorized: 'off'
Note Editing an existing assignment in this way does not change its priority. For
example, if the active boundary condition was assigned after bc1, then editing bc1 does
not make bc1 the active boundary condition.
See Also
Related Examples
• “Specify Boundary Conditions” on page 2-181
2-203
2 Setting Up Your PDE
Note THIS PAGE DESCRIBES THE LEGACY WORKFLOW. New features might not be
compatible with the legacy workflow. For the corresponding step in the recommended
workflow, see “Specify Boundary Conditions” on page 2-181.
To use this legacy syntax, write the functions using the templates in “Boundary
Conditions for Scalar PDE” on page 2-204 or “Boundary Conditions for PDE Systems” on
page 2-209.
hu = r,
where h and r can be functions of x, y, the solution u, the edge segment index, and, for
parabolic and hyperbolic equations, time.
n is the outward unit normal. g and q are functions defined on ∂Ω, and can be functions
r
of x, y, the solution u, the edge segment index, and, for parabolic and hyperbolic
equations, time.
[qmatrix,gmatrix,hmatrix,rmatrix] = pdebound(p,e,u,time)
2-204
Boundary Conditions by Writing Functions
Your function returns matrices qmatrix, gmatrix, hmatrix, and rmatrix, based on
these inputs:
If your boundary conditions do not depend on u or time, those inputs are []. If your
boundary conditions do depend on u or time, then when u or time are NaN, ensure that
the outputs such as qmatrix consist of matrices of NaN of the correct size. This signals to
solvers, such as parabolic, to use a time-dependent or solution-dependent algorithm.
Before specifying boundary conditions, you need to know the boundary labels. See
“Identify Boundary Labels” on page 2-173.
The PDE solver, such as assempde or adaptmesh, passes a matrix p of points and e of
edges. e has seven rows and ne columns, where you do not necessarily know in advance
the size ne.
• p is a 2-by-Np matrix, where p(1,k) is the x-coordinate of point k, and p(2,k) is the
y-coordinate of point k.
• e is a 7-by-ne matrix, where
e contains an entry for every finite element edge that lies on an exterior boundary.
2-205
2 Setting Up Your PDE
for k = 1:ne
x1 = p(1,e(1,k)); % x at first point in segment
x2 = p(1,e(2,k)); % x at second point in segment
xm = (x1 + x2)/2; % x at segment midpoint
y1 = p(2,e(1,k)); % y at first point in segment
y2 = p(2,e(2,k)); % y at second point in segment
ym = (y1 + y2)/2; % y at segment midpoint
switch e(5,k)
case {some_edge_labels}
% Fill in hmatrix,rmatrix or qmatrix,gmatrix
case {another_list_of_edge_labels}
% Fill in hmatrix,rmatrix or qmatrix,gmatrix
otherwise
% Fill in hmatrix,rmatrix or qmatrix,gmatrix
end
end
For each column k in e, entry k of rmatrix is the value of rmatrix at the first point in
the edge, and entry ne + k is the value at the second point in the edge. For example, if
r = x2 + y4, then write these lines:
The syntax for hmatrix is identical: entry k of hmatrix is the value of r at the first point
in the edge, and entry k + ne is the value at the second point in the edge.
For each column k in e, entry k of qmatrix is the value of qmatrix at the midpoint in
the edge. For example, if q = x2 + y4, then write these lines:
The syntax for gmatrix is identical: entry k of gmatrix is the value of gmatrix at the
midpoint in the edge.
If the coefficients depend on the solution u, use the element u(e(1,k)) as the solution
value at the first point of edge k, and u(e(2,k)) as the solution value at the second
point of edge k.
For example, consider the following geometry, a rectangle with a circular hole.
2-206
Boundary Conditions by Writing Functions
R1 = [3,4,-1,1,1,-1,-.4,-.4,.4,.4]';
% Circle is code 1, center (.5,0), radius .2
C1 = [1,.5,0,.2]';
% Pad C1 with zeros to enable concatenation with R1
C1 = [C1;zeros(length(R1)-length(C1),1)];
geom = [R1,C1];
% Set formula
sf = 'R1-C1';
% Create geometry
gd = decsg(geom,sf,ns);
% View geometry
pdegplot(gd,'EdgeLabels','on')
xlim([-1.1 1.1])
axis equal
2-207
2 Setting Up Your PDE
Suppose the boundary conditions on the outer boundary (segments 1 through 4) are
Dirichlet, with the value u(x,y) = t(x – y), where t is time. Suppose the circular boundary
(segments 5 through 8) has a generalized Neumann condition, with q = 1 and g = x2 + y2.
2-208
Boundary Conditions by Writing Functions
for k = 1:ne
x1 = p(1,e(1,k)); % x at first point in segment
x2 = p(1,e(2,k)); % x at second point in segment
xm = (x1 + x2)/2; % x at segment midpoint
y1 = p(2,e(1,k)); % y at first point in segment
y2 = p(2,e(2,k)); % y at second point in segment
ym = (y1 + y2)/2; % y at segment midpoint
switch e(5,k)
case {1,2,3,4} % rectangle boundaries
hmatrix(k) = 1;
hmatrix(k+ne) = 1;
rmatrix(k) = time*(x1 - y1);
rmatrix(k+ne) = time*(x2 - y2);
otherwise % same as case {5,6,7,8}, circle boundaries
qmatrix(k) = 1;
gmatrix(k) = xm^2 + ym^2;
end
end
hu = r
n · ( c ƒ — u ) + qu = g + h ¢m
N
Ê ∂ ∂ ∂ ∂ ˆ
 ÁË cos(a )ci, j,1,1 ∂x + cos(a)ci, j ,1,2 ∂y + sin(a)ci, j ,2,1 ∂x + sin(a)ci, j,2,2 ∂y ˜¯ u j
j =1
where the outward normal vector of the boundary n = ( cos(a ),sin(a ) ) . For each edge
segment there are M Dirichlet conditions and the h-matrix is M-by-N, M ≥ 0. The
generalized Neumann condition contains a source h ¢m where the solver computes
Lagrange multipliers µ such that the Dirichlet conditions are satisfied.
2-209
2 Setting Up Your PDE
[qmatrix,gmatrix,hmatrix,rmatrix] = pdebound(p,e,u,time)
Your function returns matrices qmatrix, gmatrix, hmatrix, and rmatrix, based on
these inputs:
If your boundary conditions do not depend on u or time, those inputs are []. If your
boundary conditions do depend on u or time, then when u or time are NaN, ensure that
the outputs such as qmatrix consist of matrices of NaN of the correct size. This signals to
solvers, such as parabolic, to use a time-dependent or solution-dependent algorithm.
Before specifying boundary conditions, you need to know the boundary labels. See
“Identify Boundary Labels” on page 2-173.
• p is a 2-by-Np matrix, where p(1,k) is the x-coordinate of point k, and p(2,k) is the
y-coordinate of point k.
• e is a 7-by-ne matrix, where
e contains an entry for every finite element edge that lies on an exterior boundary.
Let N be the dimension of the system of PDEs; see “Equations You Can Solve Using
Legacy Functions” on page 1-3. Use the following template for your boundary file.
function [qmatrix,gmatrix,hmatrix,rmatrix] = pdebound(p,e,u,time)
2-210
Boundary Conditions by Writing Functions
qmatrix = zeros(N^2,ne);
gmatrix = zeros(N,ne);
hmatrix = zeros(N^2,2*ne);
rmatrix = zeros(N,2*ne);
for k = 1:ne
x1 = p(1,e(1,k)); % x at first point in segment
x2 = p(1,e(2,k)); % x at second point in segment
xm = (x1 + x2)/2; % x at segment midpoint
y1 = p(2,e(1,k)); % y at first point in segment
y2 = p(2,e(2,k)); % y at second point in segment
ym = (y1 + y2)/2; % y at segment midpoint
switch e(5,k)
case {some_edge_labels}
% Fill in hmatrix,rmatrix or qmatrix,gmatrix
case {another_list_of_edge_labels}
% Fill in hmatrix,rmatrix or qmatrix,gmatrix
otherwise
% Fill in hmatrix,rmatrix or qmatrix,gmatrix
end
end
For the boundary file, you represent the matrix h for each edge segment as a vector,
taking the matrix column-wise, as hmatrix(:). Column k of hmatrix corresponds to the
matrix at the first edge point e(1,k), and column k + ne corresponds to the matrix at
the second edge point e(2,k).
Similarly, you represent each vector r for an edge as a column in the matrix rmatrix.
Column k corresponds to the vector at the first edge point e(1,k), and column k + ne
corresponds to the vector at the second edge point e(2,k).
Represent the entries for the matrix q for each edge segment as a vector, qmatrix(:),
similar to the matrix hmatrix(:). Similarly, represent g for each edge segment is a
column vector in the matrix gmatrix. Unlike h and r, which have two columns for each
segment, q and g have just one column for each segment, which is the value of the
function at the midpoint of the edge segment.
For example, consider the following geometry, a rectangle with a circular hole.
% Rectangle is code 3, 4 sides,
% followed by x-coordinates and then y-coordinates
R1 = [3,4,-1,1,1,-1,-.4,-.4,.4,.4]';
% Circle is code 1, center (.5,0), radius .2
2-211
2 Setting Up Your PDE
C1 = [1,.5,0,.2]';
% Pad C1 with zeros to enable concatenation with R1
C1 = [C1;zeros(length(R1)-length(C1),1)];
geom = [R1,C1];
% Set formula
sf = 'R1-C1';
% Create geometry
gd = decsg(geom,sf,ns);
% View geometry
pdegplot(gd,'EdgeLabels','on')
xlim([-1.1 1.1])
axis equal
2-212
Boundary Conditions by Writing Functions
2-213
2 Setting Up Your PDE
Ê0 1 1 ˆ
Á ˜
q = Á 0 0 0˜
Á 1 1 0˜
Ë ¯
and
Ê 1 + x2 ˆ
Á ˜
g =Á 0 ˜
ÁÁ 2 ˜˜
Ë1 + y ¯
• On the circular segments (numbers 5–8),
Ê 0 1 + x2 2 + y2 ˆ
Á ˜
q=Á 0 0 0 ˜
ÁÁ ˜
Ë1 + x
4
1 + y4 0 ˜¯
and
Ê cos(p x) ˆ
Á ˜
g =Á 0 ˜
Á tanh( x + y) ˜
Ë ¯
N = 3;
ne = size(e,2); % number of edges
qmatrix = zeros(N^2,ne);
gmatrix = zeros(N,ne);
hmatrix = zeros(N^2,2*ne);
rmatrix = zeros(N,2*ne);
for k = 1:ne
x1 = p(1,e(1,k)); % x at first point in segment
x2 = p(1,e(2,k)); % x at second point in segment
xm = (x1 + x2)/2; % x at segment midpoint
y1 = p(2,e(1,k)); % y at first point in segment
2-214
Boundary Conditions by Writing Functions
qk = zeros(N);
qk(1,2) = 1;
qk(1,3) = 1;
qk(3,1) = 1;
qk(3,2) = 1;
qk = qk(:);
qmatrix(:,k) = qk;
gk = zeros(N,1);
gk(1) = 1+xm^2;
gk(3) = 1+ym^2;
gmatrix(:,k) = gk;
case {5,6,7,8}
hk = zeros(N);
hk(2,2) = 1;
hk = hk(:);
hmatrix(:,k) = hk;
hmatrix(:,k+ne) = hk;
qk = zeros(N);
qk(1,2) = 1+xm^2;
qk(1,3) = 2+ym^2;
qk(3,1) = 1+xm^4;
qk(3,2) = 1+ym^4;
qk = qk(:);
2-215
2 Setting Up Your PDE
qmatrix(:,k) = qk;
gk = zeros(N,1);
gk(1) = cos(pi*xm);
gk(3) = tanh(xm*ym);
gmatrix(:,k) = gk;
end
end
2-216
Generate Mesh
Generate Mesh
The generateMesh function creates a triangular mesh for a 2-D geometry and a
tetrahedral mesh for a 3-D geometry. By default, the mesh generator uses internal
algorithms to choose suitable sizing parameters for a particular geometry. You also can
use additional arguments to specify the following parameters explicitly:
• Target maximum mesh edge length, which is an approximate upper bound on the mesh
edge lengths. Note that occasionally, some elements can have edges longer than this
parameter.
• Target minimum mesh edge length, which is an approximate lower bound on the mesh
edge lengths. Note that occasionally, some elements can have edges shorter than this
parameter.
• Mesh growth rate, which is the rate at which the mesh size increases away from the
small parts of the geometry. The value must be between 1 and 2. This ratio
corresponds to the edge length of two successive elements. The default value is 1.5,
that is, the mesh size increases by 50%.
• Quadratic or linear geometric order. A quadratic element has nodes at its corners and
edge centers, while a linear element has nodes only at its corners.
model = createpde;
importGeometry(model,'PlateSquareHolePlanar.stl');
pdegplot(model)
2-217
2 Setting Up Your PDE
Generate a default mesh. For this geometry, the default target maximum and minimum
mesh edge lengths are 8.9443 and 4.4721, respectively.
mesh_default = generateMesh(model)
mesh_default =
FEMesh with properties:
2-218
Generate Mesh
GeometricOrder: 'quadratic'
For comparison, create a mesh with the target maximum element edge length of 20.
mesh_Hmax = generateMesh(model,'Hmax',20)
mesh_Hmax =
FEMesh with properties:
2-219
2 Setting Up Your PDE
figure
pdemesh(mesh_Hmax)
Now create a mesh with the target minimum element edge length of 0.5.
mesh_Hmin = generateMesh(model,'Hmin',0.5)
2-220
Generate Mesh
mesh_Hmin =
FEMesh with properties:
figure
pdemesh(mesh_Hmin)
2-221
2 Setting Up Your PDE
Create a mesh, specifying both the maximum and minimum element edge lengths instead
of using the default values.
mesh_HminHmax = generateMesh(model,'Hmax',20,'Hmin',0.5)
mesh_HminHmax =
FEMesh with properties:
figure
pdemesh(mesh_HminHmax)
2-222
Generate Mesh
Create a mesh with the same maximum and minimum element edge lengths, but with the
growth rate of 1.9 instead of the default value of 1.5.
mesh_Hgrad = generateMesh(model,'Hmax',20,'Hmin',0.5,'Hgrad',1.9)
mesh_Hgrad =
FEMesh with properties:
2-223
2 Setting Up Your PDE
GeometricOrder: 'quadratic'
figure
pdemesh(mesh_Hgrad)
You also can choose the geometric order of the mesh. The toolbox can generate meshes
made up of quadratic or linear elements. By default, it uses quadratic meshes, which have
nodes at both the edge centers and corner nodes.
mesh_quadratic = generateMesh(model,'Hmax',50);
figure
pdemesh(mesh_quadratic,'NodeLabels','on')
2-224
Generate Mesh
hold on
plot(mesh_quadratic.Nodes(1,:),mesh_quadratic.Nodes(2,:),'ok','MarkerFaceColor','g')
To save memory or solve a 2-D problem using a legacy solver, override the default
quadratic geometric order. Legacy PDE solvers require linear triangular meshes for 2-D
geometries.
mesh_linear = generateMesh(model,'Hmax',50,'GeometricOrder','linear');
figure
pdemesh(mesh_linear,'NodeLabels','on')
hold on
plot(mesh_linear.Nodes(1,:),mesh_linear.Nodes(2,:),'ok','MarkerFaceColor','g')
2-225
2 Setting Up Your PDE
2-226
Find Mesh Elements and Nodes by Location
2-227
2 Setting Up Your PDE
thermalProperties(thermalmodel,'ThermalConductivity',1);
thermalBC(thermalmodel,'Edge',4,'Temperature',20);
thermalBC(thermalmodel,'Edge',1,'Temperature',-10);
Generate a mesh and solve the problem. For this example, use a linear mesh to better see
the nodes on the mesh plots. Additional nodes on a quadratic mesh make it difficult to see
the plots in this example clearly.
mesh = generateMesh(thermalmodel,'GeometricOrder','linear');
thermalresults = solve(thermalmodel);
The solver finds the temperatures and temperature gradients at all nodal locations. Plot
the temperatures.
pdeplot(thermalmodel,'XYData',thermalresults.Temperature)
axis equal
2-228
Find Mesh Elements and Nodes by Location
Suppose you need to analyze the results around the center hole more closely. First, find
the nodes and elements located next to the hole by using the findNodes and
findElements functions. For example, find nodes and elements located within the radius
of 2.5 from the center [5 10].
Nr = findNodes(mesh,'radius',[5 10],2.5);
Er = findElements(mesh,'radius',[5 10],2.5);
Highlight the nodes within this radius on the mesh plot using a green marker.
figure
pdemesh(thermalmodel)
hold on
plot(mesh.Nodes(1,Nr),mesh.Nodes(2,Nr),'or','MarkerFaceColor','g')
2-229
2 Setting Up Your PDE
Find the minimal and maximal temperatures within the specified radius.
[Temps_disk] = thermalresults.Temperature(Nr);
[T_min,index_min] = min(Temps_disk);
[T_max,index_max] = max(Temps_disk);
T_min
T_min = -2.1698
T_max
T_max = 12.2420
Find the IDs of the nodes corresponding to the minimal and maximal temperatures. Plot
these nodes on the mesh plot.
2-230
Find Mesh Elements and Nodes by Location
nodeIDmin = Nr(index_min);
nodeIDmax = Nr(index_max);
figure
pdemesh(thermalmodel)
hold on
plot(mesh.Nodes(1,nodeIDmin),mesh.Nodes(2,nodeIDmin),'or','MarkerFaceColor','b')
plot(mesh.Nodes(1,nodeIDmax),mesh.Nodes(2,nodeIDmax),'or','MarkerFaceColor','r')
Now highlight the elements within the specified radius on the mesh plot using a green
marker.
figure
pdemesh(thermalmodel)
2-231
2 Setting Up Your PDE
hold on
pdemesh(mesh.Nodes,mesh.Elements(:,Er),'EdgeColor','green')
figure
pdeplot(mesh.Nodes,mesh.Elements(:,Er),'XYData',thermalresults.Temperature)
2-232
Find Mesh Elements and Nodes by Location
2-233
2 Setting Up Your PDE
Typically, PDE solvers work best with meshes made up of elements that have an
equilateral shape. Such meshes are ideal. In reality, creating an ideal mesh for most 2-D
and 3-D geometries is impossible because geometries have tiny or narrow regions and
sharp angles. For such regions, a mesh generator creates meshes with some elements
that are much smaller than the rest of mesh elements or have drastically different side
lengths.
Checking if the mesh is of good quality before running an analysis is a good practice,
especially for simulations that take a long time. The toolbox provides the meshQuality
function for this task.
meshQuality evaluates the shape quality of mesh elements and returns numbers from 0
to 1 for each mesh element. The value 1 corresponds to the optimal shape of the element.
By default, the meshQuality function combines several criteria when evaluating the
shape quality. In addition to the default metric, you can use the aspect-ratio metric,
which is based solely on the ratio of the minimum dimension of an element to its
maximum dimension.
model = createpde;
importGeometry(model,'Torus.stl');
pdegplot(model)
camlight right
2-234
Assess Quality of Mesh Elements
2-235
2 Setting Up Your PDE
hold on
pdemesh(mesh.Nodes,mesh.Elements(:,elemIDs),'FaceColor','blue','EdgeColor','blue')
Determine how much of the total mesh volume belongs to elements with quality values
less than 0.3. Return the result as a percentage.
mv03_percent = volume(mesh,elemIDs)/volume(mesh)*100
mv03_percent = 0.0198
Evaluate the shape quality of the mesh elements by using the ratio of minimal to maximal
dimension for each element.
Q = meshQuality(mesh,'aspect-ratio');
2-236
Assess Quality of Mesh Elements
figure
pdemesh(mesh,'FaceAlpha',0.5)
hold on
pdemesh(mesh.Nodes,mesh.Elements(:,elemIDs),'FaceColor','blue','EdgeColor','blue')
2-237
2 Setting Up Your PDE
Note New features might not be compatible with the legacy workflow. For description of
the mesh data in the recommended workflow, see “Mesh Data” on page 2-241.
• p (points, the mesh nodes) is a 2-by-Np matrix of nodes, where Np is the number of
nodes in the mesh. Each column p(:,k) consists of the x-coordinate of point k in
p(1,k) and the y-coordinate of point k in p(2,k).
• e (edges) is a 7-by-Ne matrix of edges, where Ne is the number of edges in the mesh.
The mesh edges in e and the edges of the geometry have a one-to-one
correspondence. The e matrix represents the discrete edges of the geometry in the
same manner as the t matrix represents the discrete faces. Each column in the e
matrix represents one edge.
2-238
Mesh Data as [p,e,t] Triples
• p (points, the mesh nodes) is a 3-by-Np matrix of nodes, where Np is the number of
nodes in the mesh. Each column p(:,k) consists of the x-coordinate of point k in
p(1,k), the y-coordinate of point k in p(2,k), and the z-coordinate of point k in
p(3,k).
• e is an object that associates the mesh faces with the geometry boundaries. Partial
Differential Equation Toolbox functions use this association when converting the
boundary conditions, which you set on geometry boundaries, to the mesh boundary
faces.
• t (tetrahedra) is either an 11-by-Nt matrix of tetrahedra or a 5-by-Nt matrix of
tetrahedra, depending on whether you call generateMesh with the GeometricOrder
name-value pair set to 'quadratic' or 'linear', respectively. Nt is the number of
tetrahedra in the mesh. Each column of t contains the indices of the points in p that
form the tetrahedron. The exception is the last element in the column, which is the
subdomain number. Tetrahedron points are ordered as shown.
2-239
2 Setting Up Your PDE
2-240
Mesh Data
Mesh Data
Partial Differential Equation Toolbox uses meshes with triangular elements for 2-D
geometries and meshes with tetrahedral elements for 3-D geometries. In both cases, it
uses quadratic elements by default, and provides the option to switch to linear elements.
A mesh always consists of elements of the same type. The toolbox does not support mixed
meshes.
The triangles in 2-D meshes are specified by three nodes for linear elements or six nodes
for quadratic elements. A triangle representing a linear element has nodes at the corners.
A triangle representing a quadratic element has nodes at its corners and edge centers.
The tetrahedra in 3-D meshes are specified by four nodes for linear elements or 10 nodes
for quadratic elements. A tetrahedron representing a linear element has nodes at the
corners. A tetrahedron representing a quadratic element has nodes at its corners and
edge centers.
2-241
2 Setting Up Your PDE
The model container object stores the parameters of the PDE model. The toolbox offers
several types of model container objects, each for a particular application area. For
example, for linear elasticity problems, the model container is a StructuralModel
object, and for heat transfer problems, the model container is a ThermalModel object.
For general PDE problems, the toolbox uses the PDEModel object.
The Mesh property of the model container object stores mesh data. The Mesh property
contains a FEMesh object. FEMesh include information on the nodes and elements of the
mesh, mesh growth rate, and target minimum and maximum element size. The properties
also indicate whether the mesh is linear or quadratic. You can specify these mesh
parameters when creating a mesh.
To generate a mesh for your PDE model, use the generateMesh function.
By default, generateMesh uses the quadratic geometric order, which typically produces
more accurate results than the linear geometric order. To switch to the linear geometric
order, call the mesh generator and set the GeometricOrder name-value pair to
'linear'.
2-242
3
Solving PDEs
3-2
von Mises Effective Stress and Displacements
Consider a steel plate that is clamped along a right-angle inset at the lower-left corner,
and pulled along a rounded cut at the upper-right corner. All other sides are free. The
steel plate has the following properties:
The curved boundary is subjected to an outward normal load of 500 N/m. To specify a
surface traction, divide the load by the thickness (0.001 m). Thus, the surface traction is
0.5 MN/m2. The force unit in this example is MN.
To solve this problem in the PDE Modeler app, follow these steps:
1 Draw a polygon with corners (0 1), (2/3,1), (1,2/3), (1,0), (1/3,0), (1/3,1/3), (0,1/3) and
a circle with the center (2/3, 2/3) and radius 1/3.
3-3
3 Solving PDEs
7 Specify the boundary conditions. To do this, select Boundary > Specify Boundary
Conditions.
3-4
von Mises Effective Stress and Displacements
3-5
3 Solving PDEs
By selecting other options from the Color drop-down menu, you can visualize different
strain and stress properties, such as the x- and y-direction strains and stresses, the shear
stress, and the principal stresses and strains. You also can plot combinations of scalar and
vector properties by using color, height, vector field arrows, and displacements in a 3-D
plot to represent different properties.
3-6
Clamped, Square Isotropic Plate with Uniform Pressure Load
The partial differential equation for a thin, isotropic plate with a pressure loading is
and is the modulus of elasticity, is Poisson's ratio, and is the plate thickness. The
transverse deflection of the plate is and is the pressure load.
The boundary conditions for the clamped boundaries are and where is
the derivative of in a direction normal to the boundary.
The Partial Differential Equation Toolbox™ cannot directly solve the fourth order plate
equation shown above but this can be converted to the following two second order partial
differential equations.
where is a new dependent variable. However, it is not obvious how to specify boundary
conditions for this second order system. We cannot directly specify boundary conditions
for both and . Instead, we directly prescribe to be zero and use the following
technique to define in such a way to insure that also equals zero on the boundary.
3-7
3 Solving PDEs
Stiff "springs" that apply a transverse shear force to the plate edge are distributed along
the boundary. The shear force along the boundary due to these springs can be written
where is the normal to the boundary and is the stiffness of the
springs. The value of must be large enough that is approximately zero at all points
on the boundary but not so large that numerical errors result because the stiffness matrix
is ill-conditioned. This expression is a generalized Neumann boundary condition
supported by Partial Differential Equation Toolbox™
In the Partial Differential Equation Toolbox™ definition for an elliptic system, the and
dependent variables are u(1) and u(2). The two second order partial differential equations
can be rewritten as
which is the form supported by the toolbox. The input corresponding to this formulation is
shown in the sections below.
numberOfPDE = 2;
model = createpde(numberOfPDE);
Problem Parameters
Geometry Creation
For a single square, the geometry and mesh are easily defined as shown below.
3-8
Clamped, Square Isotropic Plate with Uniform Pressure Load
geometryFromEdges(model,g);
Plot the geometry and display the edge labels for use in the boundary condition definition.
figure;
pdegplot(model,'EdgeLabels','on');
ylim([-1,11])
axis equal
title 'Geometry With Edge Labels Displayed';
3-9
3 Solving PDEs
Coefficient Definition
The documentation on PDE coefficients shows the required formats for the a and c
matrices. The most convenient form for c in this example is from the table where
is the number of differential equations. In this example . The tensor, in the
form of an matrix of submatrices is shown below.
The six-row by one-column c matrix is defined below. The entries in the full a matrix
and the f vector follow directly from the definition of the two-equation system
shown above.
c = [1 0 1 D 0 D]';
a = [0 0 1 0]';
f = [0 pres]';
specifyCoefficients(model,'m',0,'d',0,'c',c,'a',a,'f',f);
Boundary Conditions
bOuter = applyBoundaryCondition(model,'neumann','Edge',(1:4),...
'g',[0 0],'q',[0 0; k 0]);
Mesh generation
The solution is calculated using the solvepde function and the transverse deflection is
plotted using the pdeplot function. For comparison, the transverse deflection at the
plate center is also calculated using an analytical solution to this problem.
3-10
Clamped, Square Isotropic Plate with Uniform Pressure Load
res = solvepde(model);
u = res.NodalSolution;
numNodes = size(model.Mesh.Nodes,2);
figure
pdeplot(model,'XYData',u(1:numNodes),'Contour','on');
title 'Transverse Deflection'
numNodes = size(model.Mesh.Nodes,2);
fprintf('Transverse deflection at plate center(PDE Toolbox) = %12.4e\n',...
min(u(1:numNodes,1)));
3-11
3 Solving PDEs
wMax = -.0138*pres*len^4/(E*thick^3);
fprintf('Transverse deflection at plate center(analytical) = %12.4e\n', wMax);
3-12
Deflection of Piezoelectric Actuator
where is the stress tensor and is the body force vector. The electrostatic behavior of
the solid is described by Gauss' Law
where is the electric displacement and is the distributed, free charge. These two
PDE systems can be combined into the following single system
In 2D, has the components and and has the components and
.
The constitutive equations for the material define the stress tensor and electric
displacement vector in terms of the strain tensor and electric field. For a 2D, orthotropic,
piezoelectric material under plane stress conditions these are commonly written as
3-13
3 Solving PDEs
where are the elastic coefficients, are the electrical permittivities, and are the
piezoelectric stress coefficients. The piezoelectric stress coefficients are written to
conform to conventional notation in piezoelectric materials where the z-direction (3-
direction) is aligned with the "poled" direction of the material. For the 2D analysis, we
want the poled direction to be aligned with the y-axis.
Finally, the strain vector can be written in terms of the x-displacement, , and y-
displacement, as
See reference 2, for example, for a more complete description of the piezoelectric
equations.
The strain-displacement equations and electric field equations above can be substituted
into the constitutive equations to yield a system of equations for the stresses and
3-14
Deflection of Piezoelectric Actuator
The PDE Toolbox requires a system of elliptic equations to be expressed in the form
or in tensor form
3-15
3 Solving PDEs
The documentation for the function assempde shows that it is convenient to view the
tensor as an matrix of submatrices. The most convenient form for the
input argument for this symmetric, system has 21 rows in and is described in
detail in the PDE Toolbox documentation. It is repeated here for convenience.
For the purposes of mapping terms from constitutive equations to the form required by
PDE Toolbox it is useful to write the tensor and solution gradient in the following form
3-16
Deflection of Piezoelectric Actuator
From this equation the traditional constitutive coefficients can be mapped to the form
required for the PDE Toolbox matrix. Note the minus sign in the equations for electric
field. This minus must be incorporated into the matrix to match the PDE Toolbox
convention. This is shown explicitly below.
3-17
3 Solving PDEs
Now that we have defined the equations for a 2D piezoelectric material, we are ready to
apply these to a specific model. The model is a two-layer cantilever beam that has been
extensively studied (e.g. refs 1 and 2). It is defined as a "bimorph" because although both
layers are made of the same Polyvinylidene Fluoride (PVDF) material, in the top layer the
polarization direction points down (minus y direction) and in the bottom layer, it points
up. A schematic of the cantilever beam is shown in the figure below.
This figure is not to scale; the actual thickness/length ratio is 100 so the beam is very
slender. When a voltage is applied between the lower and upper surfaces of the beam, it
deflects in the y-direction; one layer shortens and the other layer lengthens. Devices of
this type can be designed to provide the required motion or force for different
applications.
The first step in solving a PDE problem is to create a PDE Model. This is a container that
holds the number of equations, geometry, mesh, and boundary conditions for your PDE.
The equations of linear elasticity have three components, so the number of equations in
this model is three.
3-18
Deflection of Piezoelectric Actuator
N = 3;
model = createpde(N);
Geometry Creation
The simple two-layer geometry of the beam can be created by defining the sum of two
rectangles.
The two lines below contain the columns of the geometry description matrix (GDM) for
the two rectangular layers. The GDM is the first input argument to decsg and describes
the basic geometric entities in the model.
topLayer = [3 4 0 L L 0 0 0 H2 H2];
bottomLayer = [3 4 0 L L 0 -H2 -H2 0 0];
gdm = [topLayer; bottomLayer]';
g = decsg(gdm, 'R1+R2', ['R1'; 'R2']');
geometryFromEdges(model,g);
figure;
pdegplot(model, 'EdgeLabels', 'on', 'FaceLabels', 'on');
xlabel('X-coordinate, meters')
ylabel('Y-coordinate, meters')
axis([-.1*L, 1.1*L, -4*H2, 4*H2])
axis square
3-19
3 Solving PDEs
The material in both layers of the beam is Polyvinylidene Fluoride (PVDF), a thermoplastic
polymer with piezoelectric behavior.
relPermittivity = 12;
3-20
Deflection of Piezoelectric Actuator
The piezoelectric strain coefficients for PVDF are given above but the constitutive
relations in the finite element formulation require the piezoelectric stress coefficients.
These are calculated on the next line (for details see, for example, reference 2).
pzeE = c2d*pzeD;
D_const_stress = [relPermittivity 0; 0 relPermittivity]*permittivityFreeSpace;
f = [0 0 0]';
specifyCoefficients(model, 'm', 0,'d', 0,'c', ctop, 'a', 0, 'f', f,'Face',2);
specifyCoefficients(model, 'm', 0,'d', 0,'c', cbot, 'a', 0, 'f', f,'Face',1);
For this example, the top geometry edge (edge 1) has the voltage prescribed as 100 volts.
The bottom geometry edge (edge 2) has the voltage prescribed as 0 volts (i.e. grounded).
The left geometry edge (edges 6 and 7) have the u and v displacements equal zero (i.e.
clamped). The stress and charge are zero on the right geometry edge (i.e. q = 0).
V = 100;
3-21
3 Solving PDEs
Set the x and y displacements (solution components 1 and 2) on the left end (geometry
edges 6 and 7) to zero.
clampLeft = applyBoundaryCondition(model,'mixed','Edge',6:7,...
'u',[0 0],...
'EquationIndex',1:2);
Mesh Generation
We need a relatively fine mesh to accurately model the bending of the beam.
hmax = 5e-04;
msh = generateMesh(model,'Hmax',hmax,...
'GeometricOrder','quadratic',...
'MesherVersion','R2013a');
Extract the NodalSolution property from the result, this has the x-deflection in column
1, the y-deflection in column 2, and the electrical potential in column 3. Find the
minimum y-deflection, and plot the solution components.
rs = result.NodalSolution;
feTipDeflection = min(rs(:,2));
fprintf('Finite element tip deflection is: %12.4e\n', feTipDeflection);
3-22
Deflection of Piezoelectric Actuator
ylabel('Y-Coordinate, meters')
axis square
end
3-23
3 Solving PDEs
3-24
Deflection of Piezoelectric Actuator
Analytical Solution
A simple, approximate, analytical solution was obtained for this problem in reference 1.
tipDeflection = -3*d31*V*L^2/(8*H2^2);
fprintf('Analytical tip deflection is: %12.4e\n', tipDeflection);
Summary
The color contour plots of x-deflection and y-deflection show the standard behavior of the
classical cantilever beam solution. The linear distribution of voltage through the thickness
of the beam is as expected. There is good agreement between the PDE Toolbox finite
element solution and the analytical solution from reference 1.
3-25
3 Solving PDEs
Although this example shows a very specific coupled elasticity-electrostatic model, the
general approach here can be used for many other systems of coupled PDEs. The key to
applying PDE Toolbox to these types of coupled systems is the systematic, multi-step
coefficient mapping procedure described above.
References
3-26
Dynamics of Damped Cantilever Beam
The beam is modeled with a plane stress elasticity formulation. The damping model is
basic viscous damping distributed uniformly through the volume of the beam. Several
transient analyses are performed where the beam is deformed into an initial shape and
then released at time, . Analyses with and without damping are considered. Two
initial displacement shapes are considered. In the first, the beam is deformed into a shape
corresponding to the lowest vibration mode. In the second, the beam is deformed by
applying an external load at the tip of the beam. No additional loading is applied in this
example so, in the damped cases, the displacement of the beam decays as a function of
time due to the damping.
The transient analyses are performed using the PDE Toolbox hyperbolic function. One
form of this function allows a transient analysis to be performed with the stiffness, mass,
and damping matrices and load vectors as input. Typically these matrices and vectors are
calculated using other PDE Toolbox functions. That approach will be demonstrated in this
example.
In this example, we will define (three percent of critical damping) and equal
zero so that can be calculated as
This example specifies values of parameters using the imperial system of units. You can
replace them with values specified in the metric system. If you do so, ensure that you
specify all values throughout the example using the same system.
3-27
3 Solving PDEs
From beam theory, there is a simple expression for the lowest vibration frequency of the
cantilever beam.
eigValAnalytical = 1.8751^4*E*I/(rho*A*width^4);
freqAnalytical = sqrt(eigValAnalytical)/(2*pi);
Plot the geometry and display the edge labels for use in the boundary condition definition.
figure;
pdegplot(g,'EdgeLabels','on');
3-28
Dynamics of Damped Cantilever Beam
axis equal
title 'Geometry With Edge Labels Displayed'
geometryFromEdges(model,g);
Equation Coefficients
c = [2*G+mu;0;G;0;G;mu;0;G;0;2*G+mu];
f = [0;0];
a = 0;
3-29
3 Solving PDEs
m = rho;
specifyCoefficients(model,'m',m,'d',0,'c',c,'a',a,'f',f);
Boundary Conditions
Specify the following boundary condition to clamp (displacements equal zero) the left
beam-edge.
applyBoundaryCondition(model,'dirichlet','Edge',4,'u',[0 0]);
Mesh Generation
Plot the deformed shape of the beam with the displacements scaled by an arbitrary factor.
scaleFactor = 20;
figure;
[p,e,t] = meshToPet(msh);
pdeplot(p+scaleFactor*eigenVec',e,t,'XYData',real(eigenVec(:,2)));
title('Lowest Frequency Vibration Mode');
axis equal
xlabel('Inches');
ylabel('Inches');
3-30
Dynamics of Damped Cantilever Beam
drawnow
In the first two transient analyses, we define an initial displacement. in the shape of the
lowest vibration mode. By doing this, we convert the PDE to a single ODE with time as
the independent variable. The solution to this ODE is the same as that of the classical
spring-mass-damper system with a frequency equal the frequency of this vibration mode.
3-31
3 Solving PDEs
Thus we are able to compare the numerical solution with the analytical solution to this
well-known problem.
For convenience, we will scale the eigenvector shape so that y-displacement at the tip is .
1 inches. This makes the transient history plots simpler.
uEigenTip = eigenVec(2,2);
u0TipDisp = .1;
u0 = u0TipDisp/uEigenTip*eigenVec;
tlist = 0:longestPeriod/100:3*longestPeriod;
R = createPDEResults(model, u0(:));
ice = icEvaluator(R);
The displacement at the tip is a sinusoidal function of time with amplitude equal to the
initial y-displacement. This agrees with the solution to the simple spring-mass system.
3-32
Dynamics of Damped Cantilever Beam
Now solve the system with damping equal to 3% of critical for this lowest vibration
frequency.
fem = assembleFEMatrices(model);
zeta = .03;
omega = 2*pi*freqNumerical;
alpha = 2*zeta*omega;
dampmat = alpha*fem.M;
specifyCoefficients(model,'m',m,'d',dampmat,'c',c,'a',a,'f',f);
tres = solvepde(model,tlist);
This figure shows the y-displacement at the tip as a function of time. Superimposed on
this plot is a second curve which shows the envelope of the maximum amplitude as a
3-33
3 Solving PDEs
function of time, calculated from the solution to the single degree-of-freedom ODE. As
expected, the PDE solution agrees well with the analytical solution.
It would be very unusual for a structure to be loaded such that the displacement is equal
to a multiple of one of its vibration modes. In this more realistic example, we solve the
3-34
Dynamics of Damped Cantilever Beam
transient equations with the initial displacement shape calculated from the static solution
of the cantilever beam with a vertical load at the tip.
Perform a static analysis with vertical tip load equal one. Follow the model building steps
as before.
P = 1.0;
pdeTipLoad = createpde(2);
pg = geometryFromEdges(pdeTipLoad,g);
specifyCoefficients(pdeTipLoad,'m',0,'d',0,'c',c,'a',a,'f',f);
tipLoad = applyBoundaryCondition(pdeTipLoad,'neumann','Edge',2,'g',[0 P/height]);
clampedEdge = applyBoundaryCondition(pdeTipLoad,'dirichlet','Edge',4,'u',[0,0]);
msh=generateMesh(pdeTipLoad,'Hmax',hmax,'MesherVersion','R2013a');
statres = solvepde(pdeTipLoad);
To make comparison with the eigenvector case clearer, we will also scale this static
solution so that the maximum y-displacement at the tip equals .1 inches.
u = statres.NodalSolution;
uEigenTip = u(2,2);
u0TipDisp = 0.1;
u0 = u0TipDisp/uEigenTip*u;
Calculate the undamped solution with the initial displacement from the static analysis.
R = createPDEResults(model, u0(:));
ice = icEvaluator(R);
setInitialConditions(model, @ice.computeIC, 0);
tres = solvepde(model,tlist);
The displacement is no longer a pure sinusoidal wave. The static solution that we are
using as the initial conditions is similar to the lowest eigenvector but higher-frequency
modes are also contributing to the transient solution.
3-35
3 Solving PDEs
Calculate the damped solution with the initial displacement from the static analysis. The
damping matrix is the same as that used in the eigenvector case, above.
specifyCoefficients(model, 'm', m, 'd', dampmat, 'c', c, 'a', a, 'f', f);
tres = solvepde(model,tlist);
Plot the tip displacement from this solution as a function of time. Again we superimpose a
curve of the damped amplitude as a function of time obtained from an analytical solution
to the single degree-of-freedom ODE. Because the initial condition differs from the lowest
eigenvector, this analytical solution only approximates the amplitude of the PDE solution.
titl = 'Initial Displacements from Static Solution, Damped Solution';
cantileverBeamTransientPlot(tres,titl);
hold on;
3-36
Dynamics of Damped Cantilever Beam
plot(tlist,u0TipDisp*exp(-zeta*omega*tlist),'Color','r');
legend('PDE','ODE Amplitude Decay','Location','southeast');
Utility function for creating the plots of tip y-displacement as a function of time.
type cantileverBeamTransientPlot.m
3-37
3 Solving PDEs
tlist = tdres.SolutionTimes;
uu = tdres.NodalSolution;
utip = uu(2,2,:);
figure; plot(tlist, utip(:)); grid on;
title(titl); xlabel('Time, seconds');
ylabel('Y-displacement at beam tip, inches');
drawnow;
end
The evaluation function returns the value of the IC at any point within the mesh. A results
object represents the values and the interpolation function that it provided is used to
compute the ICs.
type icEvaluator.m
classdef icEvaluator
% icEvaluator Evaluates Initial Conditions data at requested locations
% ICE = icEvaluator(R) Creates an initial conditions evaluator from a
% results object. The evaluator provides a function that can be called at
% specific locations within the geometry. This class customized to represent
% a stationary solution.
%
% icEvaluator methods:
% computeIC - Computes ICs at locations within the geometric domain
%
methods
function obj = icEvaluator(R)
obj.Results = R;
end
function ic = computeIC(obj,locations)
is2d = size(obj.Results.Mesh.Nodes, 1) == 2;
3-38
Dynamics of Damped Cantilever Beam
if is2d
querypts = [locations.x; locations.y];
else
querypts = [locations.x; locations.y; locations.z];
end
numeqns = size(obj.Results.NodalSolution,2);
if numeqns == 1
ic = interpolateSolution(obj.Results, querypts);
else
ic = zeros(numeqns, numel(locations.x));
for i = 1:numeqns
ic(i,:) = interpolateSolution(obj.Results, querypts, i);
end
end
end
end
end
3-39
3 Solving PDEs
The pressure load is suddenly applied at time equal zero and the magnitude is high
enough to produce deflections on the same order as the beam thickness.
This example specifies values of parameters using the imperial system of units. You can
replace them with values specified in the metric system. If you do so, ensure that you
specify all values throughout the example using the same system.
Equations
This section describes the equations of geometrically nonlinear elasticity. One approach
to handling the large deflections is to consider the elasticity equations in the deformed
position. However, PDE Toolbox formulates the equations based on the original geometry.
This motivates using a Lagrangian formulation of nonlinear elasticity where stresses,
strains, and coordinates refer to the original geometry.
Although large deflections are accounted for in this formulation, it is assumed that the
strains remain small so that linear elastic constitutive relations apply. Also, the material is
assumed to be isotropic. For the 2D plane stress case, the constitutive relations may be
written in matrix form:
3-40
Dynamic Analysis of Clamped Beam
Readers who are interested in more details about the Lagrangian formulation for
nonlinear elasticity can consult, for example, reference 1.
The equations presented above completely define the geometrically nonlinear plane stress
problem. The work required to convert them to a form acceptable to PDE Toolbox is
considerably simplified by using the MATLAB Symbolic Math Toolbox. Symbolic Math
Toolbox can perform the necessary algebraic manipulations and output a MATLAB
function defining the c-coefficient that can be passed to PDE Toolbox functions. This
function, cCoefficientLagrangePlaneStress, is shown in the appendix below.
3-41
3 Solving PDEs
Since the beam geometry and loading are symmetric about the beam center(x =
blength/2), the model can be simplified by considering only the right-half of the beam.
l2 = blength/2;
h2 = height/2;
Create the edges of the rectangle representing the beam with these two statements.
The geometryFromEdges function creates a geometry object from the edges and stores
it within the model.
pg = geometryFromEdges(model,g);
Plot the geometry and display the edge labels. The edge labels are needed for edge
identification when applying boundary conditions.
figure
pdegplot(g,'EdgeLabels','on');
title('Geometry With Edge Labels Displayed');
3-42
Dynamic Analysis of Clamped Beam
3-43
3 Solving PDEs
Derive the equation coefficients using the material properties. For the linear case, the c-
coefficient matrix is constant
3-44
Dynamic Analysis of Clamped Beam
symBC = applyBoundaryCondition(model,'mixed','Edge',4,'u',0,'EquationIndex',1);
sigma = 2e2;
presBC = applyBoundaryCondition(model,'neumann','Edge',3,'g',[0 sigma]);
setInitialConditions(model,0,0);
Create a mesh with approximately eight elements through the thickness of the beam.
generateMesh(model,'Hmax',height/8,'MesherVersion','R2013a');
Linear Solution
Set up the analysis timespan. Here, tfinal is the final time in the analysis.
tfinal = 3e-3;
tlist = linspace(0,tfinal,100);
result = solvepde(model,tlist);
Interpolate the solution at the geometry center for the y-component (component 2) at all
times.
xc = 1.25;
yc = 0;
u4Linear = interpolateSolution(result,xc,yc,2,1:length(tlist));
3-45
3 Solving PDEs
Nonlinear Solution
result = solvepde(model,tlist);
As before, interpolate the solution at the geometry center for the y-component
(component 2) at all times.
u4NonLinear = interpolateSolution(result,xc,yc,2,1:length(tlist));
Plot Solutions
The figure below shows the y-deflection at the center of the beam as a function of time.
The nonlinear analysis computes displacements that are substantially less than the linear
analysis. This "stress stiffening" effect is also reflected in the higher oscillation frequency
from the nonlinear analysis.
figure
plot(tlist,u4Linear(:),tlist,u4NonLinear(:));
legend('Linear','Nonlinear');
title 'Deflection at Beam Center'
xlabel 'Time, seconds'
ylabel 'Deflection, inches'
grid on
3-46
Dynamic Analysis of Clamped Beam
References
type cCoefficientLagrangePlaneStress
3-47
3 Solving PDEs
% This function was generated by the Symbolic Math Toolbox version 6.0.
% 31-Jan-2014 09:50:09
ux = reshape(state.ux,2,[]);
uy = reshape(state.uy,2,[]);
dudx=ux(1,:);
dvdx=ux(2,:);
dudy=uy(1,:);
dvdy=uy(2,:);
% if(~isempty(u))
% [ux,uy] = pdegrad(p,t,u);
% dudx=ux(1,:); dudy=uy(1,:); dvdx=ux(2,:); dvdy=uy(2,:);
% else
% dudx = zeros(1, size(t,2)); dudy=dudx; dvdx=dudx; dvdy=dudx;
% end
t4 = 1/(nu^2-1);
t6 = 1/(1+nu);
t7 = E*dudy.*t4*.25;
t8 = dudx+1.0;
t9 = E*dudy.*t4.*t8*.25;
t10 = dvdy+1.0;
t11 = t7+t9-E*dvdx.*t6.*t10*.25;
t12 = dvdy.*2.0;
t13 = dudx.^2;
3-48
Dynamic Analysis of Clamped Beam
t14 = dudy.^2;
t15 = dvdy.^2;
t16 = dvdx.^2;
t17 = E*dvdx.*t4.*(1.0./2.0);
t18 = E*dudx.*dvdx.*t4*.25;
t19 = t17+t18-E*dudy.*t6*.25-E*dudy.*dvdy.*t6.*(1.0./8.0);
t20 = E*dudy.*dvdx.*nu.*t4*.25;
t21 = t20-E*t6.*(1.0./2.0)-E*dudx.*t6*.25-E*dvdy.*t6*.25-E*dudx.*dvdy.*t6.*(1.0./8.0);
t22 = dudx.*2.0;
t23 = dvdy+2.0;
t24 = nu-1.0;
t25 = E*nu.*t4;
t26 = E*dudx.*nu.*t4.*(1.0./2.0);
t27 = E*dvdy.*nu.*t4.*(1.0./2.0);
t28 = E*dudx.*dvdy.*nu.*t4*.25;
t29 = t25+t26+t27+t28-E*dudy.*dvdx.*t6.*(1.0./8.0);
t30 = E*dudy.*t4.*t23.*(1.0./8.0);
t31 = E*dudy.*dvdy.*t4.*(1.0./8.0);
t32 = t7+t30+t31-E*dvdx.*t6.*(1.0./8.0)-E*dvdx.*t4.*t8.*t24.*(1.0./8.0);
t33 = dudy.*2.0;
t34 = dvdx.*2.0;
t35 = dudx.*dudy.*2.0;
t36 = dvdx.*dvdy;
t37 = t33+t34+t35+t36;
t38 = 1.0./t24;
t39 = E*dvdx.*t23.*t38.*(1.0./8.0);
t40 = t39-E*t6.*t37.*(1.0./8.0);
out1 = [E*t4.*(dudx.*6.0+t13.*2.0+t14+t16+4.0)*.25+E*nu.*t4.*(t12+t15)*.25;
t11;
t19;
t29;
t11;
E*t4.*(t12+t13+t14.*2.0+t15+t22+2.0)*.25+E*nu.*t4.*(t16-2.0)*.25;
t21;
t32;
t19;
t21;
E*t4.*(t12+t13+t15+t16.*2.0+t22+2.0)*.25+E*nu.*t4.*(t14-2.0)*.25;
t40;
t29;
t32;
t40;
E*t4.*(dvdy.*6.0+t14+t15.*2.0+t16+4.0)*.25+E*nu.*t4.*(t13+t22)*.25];
3-49
3 Solving PDEs
end
3-50
Deflection Analysis of Bracket
The first step in solving a linear elasticity problem is to create a structural analysis model.
This is a container that holds the geometry, structural material properties, body and
boundary loads, boundary constraints, and mesh.
model = createpde('structural','static-solid');
Import an STL file of a simple bracket model using the importGeometry function. This
function reconstructs the faces, edges and vertices of the model. It can merge some faces
and edges, so the numbers can differ from those of the parent CAD model.
importGeometry(model,'BracketWithHole.stl');
Plot the geometry and turn on face labels. You will need the face labels to define the
boundary conditions.
figure
pdegplot(model,'FaceLabels','on')
view(30,30);
title('Bracket with Face Labels')
3-51
3 Solving PDEs
figure
pdegplot(model,'FaceLabels','on')
view(-134,-32)
title('Bracket with Face Labels, Rear View')
3-52
Deflection Analysis of Bracket
structuralProperties(model,'Cell',1,'YoungsModulus',200e9, ...
'PoissonsRatio',0.3);
The problem has two boundary conditions: the back face (face 4) is immobile and the
front face has an applied load. All other boundary conditions, by default, are free
boundaries.
structuralBC(model,'Face',4,'Constraint','fixed');
3-53
3 Solving PDEs
Apply a distributed load in the negative -direction to the front face (face 8).
Create a Mesh
Create a mesh that uses 10-node tetrahedral elements with quadratic interpolation
functions. This element type is significantly more accurate than the linear interpolation
(four-node) elements, particularly in elasticity analyses that involve bending.
3-54
Deflection Analysis of Bracket
result = solve(model);
minUz = min(result.Displacement.uz);
fprintf('Maximal deflection in the z-direction is %g meters.', minUz)
3-55
3 Solving PDEs
To see the solution, plot the components of the solution vector. The maximal deflections
are in the -direction. Because the part and the loading are symmetric, the -
displacement and -displacement are symmetric, and the -displacement is
antisymmetric with respect to the center line.
Here, the plotting routine uses the 'jet' colormap, which has blue as the color
representing the lowest value and red representing the highest value. The bracket
loading causes face 8 to dip down, so the maximum -displacement appears blue.
figure
pdeplot3D(model,'ColorMapData',result.Displacement.ux)
title('x-displacement')
colormap('jet')
3-56
Deflection Analysis of Bracket
figure
pdeplot3D(model,'ColorMapData',result.Displacement.uy)
title('y-displacement')
colormap('jet')
3-57
3 Solving PDEs
figure
pdeplot3D(model,'ColorMapData',result.Displacement.uz)
title('z-displacement')
colormap('jet')
3-58
Deflection Analysis of Bracket
Plot values of the von Mises Stress at nodal locations. Use the same jet colormap.
figure
pdeplot3D(model,'ColorMapData',result.VonMisesStress)
title('von Mises stress')
colormap('jet')
3-59
3 Solving PDEs
3-60
Vibration of Square Plate
The dimensions and material properties of the plate are taken from a standard finite
element benchmark problem published by NAFEMS, FV52 (See Reference).
First, create a structural model container for your 3-D modal analysis problem. This is a
container that holds the geometry, properties of the material, body loads, boundary loads,
boundary constraints, and mesh.
model = createpde('structural','modal-solid');
Import an STL file of a simple plate model using the importGeometry function. This
function reconstructs the faces, edges, and vertices of the model. It can merge some faces
and edges, so the numbers can differ from those of the parent CAD model.
importGeometry(model,'Plate10x10x1.stl');
Plot the geometry and turn on face labels. You need the face labels when defining the
boundary conditions.
figure
hc = pdegplot(model,'FaceLabels','on');
hc(1).FaceAlpha = 0.5;
title('Plate with Face Labels')
3-61
3 Solving PDEs
Define the elastic modulus of steel, Poisson's ratio, and the material density.
structuralProperties(model,'YoungsModulus',200e9, ...
'PoissonsRatio',0.3, ...
'MassDensity',8000);
In this example, the only boundary condition is the zero -displacement on the four edge
faces. These edge faces have labels 1 through 4.
structuralBC(model,'Face',1:4,'ZDisplacement',0);
Create and plot a mesh. Specify the target minimum edge length so that there is one row
of elements per plate thickness.
3-62
Vibration of Square Plate
generateMesh(model,'Hmin',1.3);
figure
pdeplot3D(model);
title('Mesh with Quadratic Tetrahedral Elements');
For comparison with the published values, load the reference frequencies in Hz.
refFreqHz = [0 0 0 45.897 109.44 109.44 167.89 193.59 206.19 206.19];
Solve the problem for the specified frequency range. Define the upper limit as slightly
larger than the highest reference frequency and the lower limit as slightly smaller than
the lowest reference frequency.
maxFreq = 1.1*refFreqHz(end)*2*pi;
result = solve(model,'FrequencyRange',[-0.1 maxFreq]);
3-63
3 Solving PDEs
freqHz = result.NaturalFrequencies/(2*pi);
Compare the reference and computed frequencies (in Hz) for the lowest 10 modes. The
lowest three mode shapes correspond to rigid-body motion of the plate. Their frequencies
are close to zero.
tfreqHz = table(refFreqHz.',freqHz(1:10));
tfreqHz.Properties.VariableNames = {'Reference','Computed'};
disp(tfreqHz);
Reference Computed
_________ __________
0 8.4781e-06
0 1.0533e-05
0 1.2248e-05
45.897 44.871
109.44 109.74
109.44 109.77
167.89 168.59
193.59 193.74
206.19 207.51
206.19 207.52
You see good agreement between the computed and published frequencies.
Plot the third component ( -component) of the solution for the seven lowest nonzero-
frequency modes.
h = figure;
h.Position = [100,100,900,600];
numToPrint = min(length(freqHz),length(refFreqHz));
for i = 4:numToPrint
subplot(4,2,i-3);
pdeplot3D(model,'ColorMapData',result.ModeShapes.uz(:,i));
axis equal
title(sprintf(['Mode=%d, z-displacement\n', ...
'Frequency(Hz): Ref=%g FEM=%g'], ...
i,refFreqHz(i),freqHz(i)));
end
3-64
Vibration of Square Plate
Reference
[1] National Agency for Finite Element Methods and Standards. The Standard NAFEMS
Benchmarks. United Kingdom: NAFEMS, October 1990.
3-65
3 Solving PDEs
A tuning fork is a U-shaped beam. When struck on one of its prongs or tines, it vibrates at
its fundamental (first) frequency and produces an audible sound.
The first flexible mode of a tuning fork is characterized by symmetric vibration of the
tines: they move towards and away from each other simultaneously, balancing the forces
at the base where they intersect. The fundamental mode of vibration does not produce
any bending effect on the handle attached at the intersection of tines. The lack of bending
at the base enables easy handling of tuning fork without influencing its dynamics.
Transverse vibration of the tines causes the handle to vibrate axially at the fundamental
frequency. This axial vibration can be used to amplify the audible sound by bringing the
end of the handle in contact with a larger surface area, like a metal table top. The next
higher mode with symmetric mode shape is about 6.25 times the fundamental frequency.
Therefore, a properly excited tuning fork tends to vibrate with a dominant frequency
corresponding to fundamental frequency, producing a pure audible tone. This example
simulates these aspects of the tuning fork dynamics by performing a modal analysis and a
transient dynamics simulation.
Find natural frequencies and mode shapes for the fundamental mode of a tuning fork and
the next several modes. Show the lack of bending effect on the fork handle at the
fundamental frequency.
First, create a structural model for modal analysis of a solid tuning fork.
model = createpde('structural','modal-solid');
importGeometry(model,'TuningFork.stl');
figure
pdegplot(model)
3-66
Structural Dynamics of Tuning Fork
Specify the Young's modulus, Poisson's ratio, and mass density to model linear elastic
material behavior. Specify all physical properties in consistent units.
E = 210E9;
nu = 0.3;
rho = 8000;
structuralProperties(model,'YoungsModulus',E, ...
'PoissonsRatio',nu, ...
'MassDensity',rho);
Generate a mesh.
generateMesh(model,'Hmax',0.001);
3-67
3 Solving PDEs
Solve the model for a chosen frequency range. Specify the lower frequency limit below
zero so that all modes with frequencies near zero appear in the solution.
RF = solve(model,'FrequencyRange',[-1,4000]*2*pi);
modeID = 1:numel(RF.NaturalFrequencies);
tmodalResults = table(modeID.',RF.NaturalFrequencies/2/pi);
tmodalResults.Properties.VariableNames = {'Mode','Frequency'};
disp(tmodalResults);
Mode Frequency
____ _________
1 0.0033244
2 0.0052855
3 0.0055476
4 0.008092
5 0.008617
6 0.0096338
7 460.42
8 706.34
9 1911.5
10 2105.5
11 2906.5
12 3814.7
Because there are no boundary constraints in this example, modal results include the
rigid body modes. The first six near-zero frequencies indicate the six rigid body modes of
a 3-D solid body. The first flexible mode is the seventh mode with a frequency around 460
Hz.
The best way to visualize mode shapes is to animate the harmonic motion at their
respective frequencies. The animateSixTuningForkModes function animates the six
flexible modes, which are modes 7 through 12 in the modal results RF.
frames = animateSixTuningForkModes(RF);
3-68
Structural Dynamics of Tuning Fork
movie(figure('units','normalized','outerposition',[0 0 1 1]),frames,
5,30)
In the first mode, two oscillating tines of the tuning fork balance out transverse forces at
the handle. The next mode with this effect is the fifth flexible mode with the frequency
2906.5 Hz. This frequency is about 6.25 times greater than the fundamental frequency
460 Hz.
3-69
3 Solving PDEs
Simulate the dynamics of a tuning fork being gently and quickly struck on one of its tines.
Analyze vibration of tines over time and axial vibration of the handle.
tmodel = createpde('structural','transient-solid');
Import the same tuning fork geometry you used for the modal analysis.
importGeometry(tmodel,'TuningFork.stl');
Generate a mesh.
mesh = generateMesh(tmodel,'Hmax',0.005);
structuralProperties(tmodel,'YoungsModulus',E, ...
'PoissonsRatio',nu, ...
'MassDensity',rho);
Identify faces for applying boundary constraints and loads by plotting the geometry with
the face labels.
figure('units','normalized','outerposition',[0 0 1 1])
pdegplot(tmodel,'FaceLabels','on')
view(-50,15)
title 'Geometry with Face Labels'
3-70
Structural Dynamics of Tuning Fork
Impose sufficient boundary constraints to prevent rigid body motion under applied
loading. Typically, you hold a tuning fork by hand or mount it on a table. A simplified
approximation to this boundary condition is fixing a region near the intersection of tines
and the handle (faces 21 and 22).
structuralBC(tmodel,'Face',[21,22],'Constraint','fixed');
Approximate an impulse loading on a face a tine by applying a pressure load for a very
small fraction of the time period of the fundamental mode. By using this very short
3-71
3 Solving PDEs
pressure pulse, you ensure that only the fundamental mode of a tuning fork is excited. To
evaluate the time period T of the fundamental mode, use the results of modal analysis.
T = 2*pi/RF.NaturalFrequencies(7);
structuralBoundaryLoad(tmodel,'Face',11,'Pressure',5E6,'EndTime',T/300);
structuralIC(tmodel,'Displacement',[0;0;0],'Velocity',[0;0;0]);
Solve the transient model for 50 periods of the fundamental mode. Sample the dynamics
60 times per period of the fundamental mode.
ncycle = 50;
sampingFrequency = 60/T;
tlist = linspace(0,ncycle*T,ncycle*T*sampingFrequency);
R = solve(tmodel,tlist)
R =
TransientStructuralResults with properties:
Plot the time-series of the vibration of the tine tip, which is face 12. Find nodes on the tip
face and plot the y-component of the displacement over time, using one of these nodes.
excitedTineTipNodes = findNodes(mesh,'region','Face',12);
tipDisp = R.Displacement.uy(excitedTineTipNodes(1),:);
figure
plot(R.SolutionTimes,tipDisp)
title('Transverse Displacement at Tine Tip')
xlim([0,0.1])
xlabel('Time')
ylabel('Y-Displacement')
3-72
Structural Dynamics of Tuning Fork
Perform fast Fourier transform (FFT) on the tip displacement time-series to see that the
vibration frequency of the tuning fork is close to its fundamental frequency. A small
deviation from the fundamental frequency computed in an unconstrained modal analysis
appears because of constraints imposed in the transient analysis.
[fTip,PTip] = tuningForkFFT(tipDisp,sampingFrequency);
figure
plot(fTip,PTip)
title({'Single-sided Amplitude Spectrum', 'of Tip Vibration'})
xlabel('f (Hz)')
ylabel('|P1(f)|')
xlim([0,4000])
3-73
3 Solving PDEs
Transverse vibration of tines causes the handle to vibrate axially with the same frequency.
To observe this vibration, plot the axial displacement time-series of the end face of the
handle.
baseNodes = tmodel.Mesh.findNodes('region','Face',6);
baseDisp = R.Displacement.ux(baseNodes(1),:);
figure
plot(R.SolutionTimes,baseDisp)
title('Axial Displacement at the End of Handle')
xlim([0,0.1])
ylabel('X-Displacement')
xlabel('Time')
3-74
Structural Dynamics of Tuning Fork
Perform an FFT of the time-series of the axial vibration of the handle. This vibration
frequency is also close to its fundamental frequency.
[fBase,PBase] = tuningForkFFT(baseDisp,sampingFrequency);
figure
plot(fBase,PBase)
title({'Single-sided Amplitude Spectrum', 'of Base Vibration'})
xlabel('f (Hz)')
ylabel('|P1(f)|')
xlim([0,4000])
3-75
3 Solving PDEs
3-76
Stress Concentration in Plate with Circular Hole
A thin rectangular plate under a uniaxial tension has a uniform stress distribution.
Introducing a circular hole in the plate disturbs the uniform stress distribution near the
hole, resulting in a significantly higher than average stress. Such a thin plate, subject to
in-plane loading, can be analyzed as a 2-D plane-stress elasticity problem. In theory, if the
plate is infinite, then the stress near the hole is three times higher than the average
stress. For a rectangular plate of finite width, the stress concentration factor is a function
of the ratio of hole diameter to the plate width. This example approximates the stress
concentration factor using a plate of a finite width.
model = createpde('structural','static-planestress');
The plate must be sufficiently long, so that the applied loads and boundary conditions are
far from the circular hole. This condition ensures that a state of uniform tension prevails
in the far field and, therefore, approximates an infinitely long plate. In this example the
length of the plate is four times greater than its width. Specify the following geometric
parameters of the problem.
radius = 20.0;
width = 50.0;
totalLength = 4*width;
Define the geometry description matrix (GDM) for the rectangle and circle.
To specify proper constraints to the model, first split the horizontal edges to the plate. To
do this, perform a Boolean addition of the original rectangle and a rectangle smaller in
length. The resulting geometry contains a mid-section with the hole, sandwiched between
two smaller rectangles.
midSectionLength = (3/4)*totalLength;
3-77
3 Solving PDEs
Define the geometry description matrix (GDM) for the smaller rectangle
Define the combined GDM, name-space matrix, and set formula to construct decomposed
geometry using decsg.
gdm = [R1,R2,C1];
ns = char('R1','R2','C1');
g = decsg(gdm,'(R1 + R2) - C1',ns');
geometryFromEdges(model,g);
figure
pdegplot(model,'EdgeLabel','on');
axis equal
title 'Geometry with Edge Labels';
3-78
Stress Concentration in Plate with Circular Hole
Specify the Young's modulus and Poisson's ratio to model linear elastic material behavior.
Remember to specify physical properties in consistent units.
structuralProperties(model,'YoungsModulus',200E3,'PoissonsRatio',0.25);
Restrain all rigid-body motions of the plate by specifying sufficient constraints. For static
analysis, the constraints must also resist the motion induced by applied load.
Set the x-component of displacement on the edge 1 to zero to resist the applied load. Set
the y-component of displacement on the edge 3 to zero to restraint the rigid body motion.
You can use any horizontal edge that is far away from the circular region. Note that
3-79
3 Solving PDEs
completely fixing the left edge provides sufficient constraints, but introduces unintended
restrictions on the deformation, thus causing spurious stress at the boundary.
structuralBC(model,'Edge',1,'XDisplacement',0);
structuralBC(model,'Edge',3,'YDisplacement',0);
Apply the surface traction with a non-zero x-component on the right edge of the plate.
structuralBoundaryLoad(model,'Edge',6,'SurfaceTraction',[100;0]);
To capture the gradation in solution accurately, use a fine mesh. Generate the mesh, using
Hmax to control the mesh size.
generateMesh(model,'Hmax', radius/6);
figure
pdemesh(model)
3-80
Stress Concentration in Plate with Circular Hole
R = solve(model);
Plot the x-component of the normal stress distribution. The stress is equal to applied
tension far away from the circular boundary. The maximum value of stress occurs near
the circular boundary.
figure
pdeplot(model,'XYData',R.Stress.sxx,'ColorMap','jet')
axis equal
title 'Normal Stress Along x-Direction';
3-81
3 Solving PDEs
Interpolate Stress
To see the details of the stress variation near the circular boundary, first define a set of
points on the boundary.
thetaHole = linspace(0,2*pi,200);
xr = radius*cos(thetaHole);
yr = radius*sin(thetaHole);
CircleCoordinates = [xr;yr];
stressHole = interpolateStress(R,CircleCoordinates);
3-82
Stress Concentration in Plate with Circular Hole
Plot the normal direction stress versus angular position of the interpolation points.
figure
plot(thetaHole,stressHole.sxx)
xlabel('\theta')
ylabel('\sigma_{xx}')
title 'Normal Stress Around Circular Boundary';
The plate with a hole model has two axes of symmetry. Therefore, you can model a
quarter of the geometry. The following model solves a quadrant of the full model with
appropriate boundary conditions.
3-83
3 Solving PDEs
symModel = createpde('structural','static-planestress');
Create the geometry that represents one quadrant of the original model. You do not need
to create additional edges to constrain the model properly.
R1 = [3,4,0,totalLength/2,totalLength/2,0,0,0,width,width]';
C1 = [1,0,0,radius,0,0,0,0,0,0]';
gm = [R1,C1];
sf = 'R1-C1';
ns = char('R1','C1');
g = decsg(gm,sf,ns');
geometryFromEdges(symModel,g);
figure
pdegplot(symModel,'EdgeLabel','on');
axis equal
title 'Symmetric Quadrant with Edge Labels';
3-84
Stress Concentration in Plate with Circular Hole
structuralProperties(symModel,'YoungsModulus',200E3, ...
'PoissonsRatio' ,0.25);
structuralBC(symModel,'Edge',[3,4],'Constraint','symmetric');
structuralBoundaryLoad(symModel,'Edge',1,'SurfaceTraction',[100,0]);
3-85
3 Solving PDEs
generateMesh(symModel,'Hmax',radius/6);
Rsym = solve(symModel);
Plot the x-component of the normal stress distribution. The results are identical to the
first quadrant of the full model.
figure
pdeplot(symModel,'xydata',Rsym.Stress.sxx,'ColorMap','jet');
axis equal
title 'Normal Stress Along x-Direction for Symmetric Model';
3-86
Thermal Deflection of Bimetallic Beam
This example finds the deflection of a bimetallic beam using a structural finite-element
model. The example compares this deflection to the analytic solution based on beam
theory approximation.
structuralmodel = createpde('structural','static-solid');
L = 0.1; % m
W = 5E-3; % m
H = 1E-3; % m
gm = multicuboid(L,W,[H,H],'Zoffset',[0,H]);
3-87
3 Solving PDEs
structuralmodel.Geometry = gm;
figure
pdegplot(structuralmodel)
Identify the cell labels of the cells for which you want to specify material properties.
First, display the cell label for the bottom cell. To see the cell label clearly, zoom onto the
left end of the beam and rotate the geometry as follows.
figure
pdegplot(structuralmodel,'CellLabels','on')
3-88
Thermal Deflection of Bimetallic Beam
Now, display the cell label for the top cell. To see the cell label clearly, zoom onto the right
end of the beam and rotate the geometry as follows.
figure
pdegplot(structuralmodel,'CellLabels','on')
axis([L/3 L/2 -W/2 W/2 0 2*H])
view([0 0])
zticks([])
3-89
3 Solving PDEs
Specify the Young's modulus, Poisson's ratio, and linear coefficient of thermal expansion
to model linear elastic material behavior. To maintain unit consistency, specify all physical
properties in SI units.
Ec = 137E9; % N/m^2
nuc = 0.28;
CTEc = 20.00E-6; % m/m-C
structuralProperties(structuralmodel,'Cell',1, ...
'YoungsModulus',Ec, ...
'PoissonsRatio',nuc, ...
'CTE',CTEc);
3-90
Thermal Deflection of Bimetallic Beam
Ei = 130E9; % N/m^2
nui = 0.354;
CTEi = 1.2E-6; % m/m-C
structuralProperties(structuralmodel,'Cell',2, ...
'YoungsModulus',Ei, ...
'PoissonsRatio',nui, ...
'CTE',CTEi);
For this example, assume that the left end of the beam is fixed. To impose this boundary
condition, display the face labels on the left end of the beam.
figure
pdegplot(structuralmodel,'faceLabels','on','FaceAlpha',0.25)
axis([-L/2 -L/3 -W/2 W/2 0 2*H])
view([60 10])
xticks([])
yticks([])
zticks([])
3-91
3 Solving PDEs
3-92
Thermal Deflection of Bimetallic Beam
Plot the deflected shape of the bimetallic beam with the magnitude of displacement as the
color map data.
figure
pdeplot3D(structuralmodel,'ColorMapData',R.Displacement.Magnitude, ...
'Deformation',R.Displacement, ...
'DeformationScaleFactor',2)
title('Deflection of Invar-Copper Beam')
Compute the deflection analytically, based on beam theory. The deflection of the strip is
3-93
3 Solving PDEs
and are the coefficients of thermal expansion of copper and invar, and are the
Young's modulus of copper and invar, and is the length of the strip.
K1 = 14 + (Ec/Ei)+ (Ei/Ec);
deflectionAnalytical = 3*(CTEc - CTEi)*100*2*H*L^2/(H^2*K1);
Compare the analytical results and the results obtained in this example. The results are
comparable because of the large aspect ratio.
PDEToobox_Deflection = max(R.Displacement.uz);
percentError = 100*(PDEToobox_Deflection - ...
deflectionAnalytical)/PDEToobox_Deflection;
3-94
Electrostatic Potential in an Air-Filled Frame
–∇ · (ε∇V) = ρ.
The PDE Modeler app uses the relative permittivity εr = ε/ε0, where ε0 is the absolute
dielectric permittivity of a vacuum (8.854 · 10-12 farad/meter). The relative permittivity for
the air is 1.00059. Note that the coefficient of permittivity does not affect the result in
this example as long as the coefficient is constant.
Assuming that there is no charge in the domain, you can simplify the Poisson equation to
the Laplace equation,
ΔV = 0.
Here, the boundary conditions are the Dirichlet boundary conditions V = 1000 at the
inner boundary and V = 0 at the outer boundary.
To solve this problem in the PDE Modeler app, follow these steps:
1 Draw the following two squares.
pderect([-0.1 0.1 -0.1 0.1])
pderect([-0.25 0.25 -0.25 0.25])
2 Set both x- and y-axis limits to [-0.3 0.3]. To do this, select Options > Axes
Limits and set the corresponding ranges. Then select Options > Axes Equal.
3 Model the frame by entering SQ2-SQ1 in the Set formula field.
4 Set the application mode to Electrostatics.
5 Specify the boundary conditions. To do this, switch to the boundary mode by
selecting Boundary > Boundary Mode. Use Shift+click to select several
boundaries. Then select Boundary > Specify Boundary Conditions.
3-95
3 Solving PDEs
• For the inner boundaries, use the Dirichlet boundary condition with h = 1 and r
= 1000.
• For the outer boundaries, use the Dirichlet boundary condition with h = 1 and r
= 0.
6 Specify the coefficients by selecting PDE > PDE Specification or clicking the PDE
button on the toolbar. Specify epsilon = 1 and rho = 0.
7 Initialize the mesh by selecting Mesh > Initialize Mesh.
8 Solve the PDE by selecting Solve > Solve PDE or clicking the = button on the
toolbar.
9 Plot the equipotential lines using a contour plot. To do this, select Plot >
Parameters and choose the contour plot in the resulting dialog box.
10 Improve the accuracy of the solution by refining the mesh close to the reentrant
corners where the gradients are steep. To do this, select Solve > Parameters. Select
Adaptive mode, use the Worst triangles selection method, and set the maximum
number of triangles to 500. Select Mesh > Refine Mesh.
11 Solve the PDE using the refined mesh. To display equipotential lines at every 100th
volt, select Plot > Parameters and enter 0:100:1000 in the Contour plot levels
field.
3-96
Electrostatic Potential in an Air-Filled Frame
3-97
3 Solving PDEs
s = stress
f = body force
e = strain
u = displacement
-—·s = f
1
e= (
—u +— uT )
2
s ij = s ji
The Voigt notation for the constitutive equation of the linear isotropic model is
3-98
Linear Elasticity Equations
Ès11 ˘ È1 - n n n 0 0 0 ˘ È e11 ˘
Ís ˙ Í ˙Í ˙
Í 22 ˙ Í n 1 -n n 0 0 0 ˙ Íe 22 ˙
Ís 33 ˙ E Í n n 1 -n 0 0 0 ˙ Íe 33 ˙
Í ˙= Í ˙Í ˙
Ís 23 ˙ (1 + n ) (1 - 2n ) Í 0 0 0 1 - 2n 0 0 ˙ Íe 23 ˙
Ís ˙ Í 0 0 0 0 1 - 2n 0 ˙ Í e13 ˙
Í 13 ˙ Í ˙Í ˙
ÍÎs12 ˙˚ ÍÎ 0 0 0 0 0 1 - 2n ˙˚ ÍÎ e12 ˙˚
The expanded form uses all the entries in σ and ε takes symmetry into account.
Ès11 ˘ È1 - n 0 0 0 n 0 0 0 n ˘ È e11 ˘
Í ˙ Í ∑ Í ˙
Ís12 ˙ Í 1 - 2n 0 0 0 0 0 0 0 ˙˙ Í e12 ˙
Ís13 ˙ Í ∑ ∑ 1 - 2n 0 0 0 0 0 0 ˙ Í e13 ˙
Í ˙ Í ˙Í ˙
Ís 21 ˙ Í ∑ ∑ ∑ 1 - 2n 0 0 0 0 0 ˙ Í e21 ˙
Ís ˙ = E Í ∑ ∑ ∑ ∑ 1 -n 0 0 0 n ˙ Í e22 ˙
Í 22 ˙ (1 + n ) (1 - 2n ) Í ˙Í ˙
Ís 23 ˙ Í ∑ ∑ ∑ ∑ ∑ 1 - 2n 0 0 0 ˙ Í e23 ˙
Ís ˙ Í ∑ ∑ ∑ ∑ ∑ ∑ 1 - 2n 0 0 ˙ Í e31 ˙
Í 31 ˙ Í ˙Í ˙
Ís 32 ˙ Í ∑ ∑ ∑ ∑ ∑ ∑ ∑ 1 - 2n 0 ˙ Í e32 ˙
Í ˙ Í ˙Í ˙
Îs 33 ˚ Î ∑ ∑ ∑ ∑ ∑ ∑ ∑ ∑ 1 - n ˚ Î e33 ˚
(3-1)
-—·( c ƒ —u ) = f
But the equations in the summary do not have ∇u alone, it appears together with its
transpose:
1
e= (—u +— uT )
2
3-99
3 Solving PDEs
È∂ ux / ∂x˘
Í∂ u / ∂ y˙˙
Í x
Í ∂ux / ∂z ˙
Í ˙
Í∂ uy / ∂x˙
Í / ∂y˙
— u = Í∂ uy ˙
Í∂ u / ∂z ˙
Í y ˙
Í ∂uz / ∂x ˙
Í ˙
Í ∂uz / ∂y˙
ÍÎ ∂uz / ∂ z ˙˚
È1 0 0 0 0 0 0 0 0˘
Í ˙
Í0 1 1
0 0 0 0 0 0˙
Í 2 2 ˙
Í 1 1 ˙
Í0 0 0 0 0 0 0˙
Í 2 2 ˙
Í 1 1 ˙
Í0 0 0 0 0 0 0˙
Í 2 2 ˙
e = Í0 0 0 0 1 0 0 0 0 ˙ —u ∫ A —u
Í ˙
Í0 1 1
0 0 0 0 0 0˙
Í 2 2 ˙
Í 1 1 ˙
Í0 0 0 0 0 0 0˙
Í 2 2 ˙
Í 1 1 ˙
Í0 0 0 0 0 0 0˙
Í 2 2 ˙
ÍÎ0 0 0 0 0 0 0 0 1 ˙˚
where A stands for the displayed matrix. So rewriting “Equation 3-1”, and recalling that •
means an entry is symmetric, you can write the stiffness tensor as
3-100
Linear Elasticity Equations
È1 - n 0 0 0 n 0 0 0 n ˘
Í ˙
Í ∑ 1 - 2n 0 0 0 0 0 0 0 ˙
Í ∑ ∑ 1 - 2n 0 0 0 0 0 0 ˙
Í ˙
Í ∑ ∑ ∑ 1 - 2n 0 0 0 0 0 ˙
E Í ∑
s = ∑ ∑ ∑ 1 -n 0 0 0 n ˙ A— u
( 1 + n ) ( 1 - 2n ) Í ˙
Í ∑ ∑ ∑ ∑ ∑ 1 - 2n 0 0 0 ˙
Í ∑ ∑ ∑ ∑ ∑ ∑ 1 - 2n 0 0 ˙
Í ˙
Í ∑ ∑ ∑ ∑ ∑ ∑ ∑ 1 - 2n 0 ˙
Í ˙
Î ∑ ∑ ∑ ∑ ∑ ∑ ∑ ∑ 1 -n ˚
È1 - n 0 0 0 n 0 0 0 n ˘
Í ˙
Í 0 1 / 2 -n 0 1 / 2 -n 0 0 0 0 0 ˙
Í 0 0 1 / 2 -n 0 0 0 1 / 2 -n 0 0 ˙
Í ˙
Í 0 1 / 2 -n 0 1 / 2 -n 0 0 0 0 0 ˙
E Í n
= 0 0 0 1 -n 0 0 0 n ˙ —u
( 1 + n ) ( 1 - 2n ) Í ˙
Í 0 0 0 0 0 1 / 2 -n 0 1 / 2 -n 0 ˙
Í 0 0 1 / 2 -n 0 0 0 1 / 2 -n 0 0 ˙
Í ˙
Í 0 0 0 0 0 1 / 2 -n 0 1 / 2 -n 0 ˙
Í ˙
Î n 0 0 0 n 0 0 0 1 -n ˚
E
m=
2(1 + n )
En
l=
(1 + n )(1 - 2n )
E(1 - n )
= 2m + l
(1 + n )(1 - 2n )
3-101
3 Solving PDEs
È2 m + l 0 0 0 l 0 0 0 l ˘
Í 0 m 0 m 0 0 0 0 0 ˙˙
Í
Í 0 0 m 0 0 0 m 0 0 ˙
Í ˙
Í 0 m 0 m 0 0 0 0 0 ˙
s =Í l 0 0 0 2m + l 0 0 0 l ˙ —u ∫ c—u
Í ˙
Í 0 0 0 0 0 m 0 m 0 ˙
Í 0 0 m 0 0 0 m 0 0 ˙
Í ˙
Í 0 0 0 0 0 m 0 m 0 ˙
Í ˙
Î l 0 0 0 l 0 0 0 2m + l ˚
If you are solving a 3-D linear elasticity problem by using PDEModel instead of
StructuralModel, use the elasticityC3D(E,nu) function (included in your software)
to obtain the c coefficient. This function uses the linearized, small-displacement
assumption for an isotropic material. For examples that use this function, see Vibration of
a Square Plate.
Plane Stress
Plane stress is a condition that prevails in a flat plate in the x-y plane, loaded only in its
own plane and without z-direction restraint. For plane stress, σ13 = σ23 = σ31 = σ32 = σ33
= 0. Assuming isotropic conditions, the Hooke's law for plane stress gives the following
strain-stress relation:
È e 11 ˘ È1 -n 0 ˘ Ès 11 ˘
Í e ˙ = 1 Í -n 1 0 ˙ Ís ˙
Í 22 ˙ E Í ˙ Í 22 ˙
ÍÎ2e12 ˙˚ ÍÎ 0 0 2 + 2n ˙˚ ÍÎs 12 ˙˚
Ê s 11 ˆ Ê1 n 0 ˆ Ê e11 ˆ
Á ˜ E Á ˜Á ˜
Á s 22 ˜ = 2 Án 1 0 ˜ Á e 22 ˜
Ás ˜ 1 -n Á 1 -n ˜ ÁË 2e 12 ˜¯
Ë 12 ¯
Á0 0 ˜
Ë 2 ¯
3-102
Linear Elasticity Equations
È1 0 0 0˘
Í 1 1 ˙
Í0 0˙
Í 2 2 ˙
e=Í ˙ —u ∫ A— u
1 1
Í0 0˙
Í 2 2 ˙
ÍÎ0 0 0 1 ˙˚
È E En ˘
Í 0 0 ˙
2
1 -n 2 ˙ È 2m ( m + l ) 2lm ˘
Í1 -n Í 0 0 ˙
Ès11 ˘ Í E E ˙ Í 2m + l 2m + l ˙
Í ˙ Í 0 2(1 +n ) 2(1 + n )
0 ˙
Í ˙
Ís12 ˙ = Í ˙ —u = Í
0 m m 0
˙ —u
Ís 21 ˙ Í E E ˙ Í 0 m m 0 ˙
Í ˙ Í 0 0 ˙
Îs 22 ˚ Í 2(1 +n ) 2(1 + n ) Í 2m ( m + l ) ˙
˙ Í 2lm 0 0 ˙
Í En E ˙ ÍÎ 2m + l 2 m + l ˙˚
Í 0 0 ˙
ÍÎ 1 - n 2 1 - n 2 ˙˚
Plane Strain
Plane strain is a deformation state where there are no displacements in the z-direction,
and the displacements in the x- and y-directions are functions of x and y but not z. The
stress-strain relation is only slightly different from the plane stress case, and the same set
of material parameters is used.
For plane strain, ε13 = ε23 = ε31 = ε32 = ε33 = 0. Assuming isotropic conditions, the stress-
strain relation can be written as follows:
Ê s 11 ˆ Ê1 - n n 0 ˆ Ê e11 ˆ
Á ˜ E Á ˜Á ˜
Á s 22 ˜ = (1 + n ) (1 - 2n ) Á n 1 -n 0 ˜ Á e 22 ˜
Ás ˜ Á 1 - 2n ˜ ÁË 2e 12 ˜¯
Ë 12 ¯
Á 0 0 ˜
Ë 2 ¯
3-103
3 Solving PDEs
È1 0 0 0˘
Í 1 1 ˙
Í0 0˙
Í 2 2 ˙
e=Í ˙ —u ∫ A— u
1 1
Í0 0˙
Í 2 2 ˙
ÍÎ0 0 0 1 ˙˚
È E (1 -n ) En ˘
Í 0 0 ˙
Í (1 + n ) (1 - 2n ) (1 + n ) (1 - 2n ) ˙
Ès11 ˘ Í E E ˙ È2 m + l 0 0 l ˘
Í ˙ Í 0
2(1 +n ) 2 (1 + n )
0 ˙ Í ˙
Ís12 ˙ = Í ˙ Í 0 m m 0 ˙
Ís 21 ˙ Í ˙ —u = Í 0
—u
E E m m 0 ˙
Í ˙ Í 0 0 ˙ Í ˙
Îs 22 ˚ Í 2(1 +n ) 2 (1 + n ) ˙ Î l 0 0 2m + l ˚
Í ˙
Í En E (1 - n ) ˙
Í 1 + n 1 - 2n 0 0
Î ( ) ( ) (1 + n ) (1 - 2n ) ˙˚
3-104
Magnetic Field in a Two-Pole Electric Motor
• Two ferromagnetic pieces: the stator and the rotor (transformer steel)
• The air gap between the stator and the rotor
• The armature copper coil carrying the DC current
Magnetic permeability of the air and copper is close to the magnetic permeability of a
vacuum, μ0 = 4π*10-7 H/m. In this example, use the magnetic permeability μ = μ0 for both
the air gap and copper coil. For the stator and the rotor, μ is
3-105
3 Solving PDEs
Ê mmax ˆ
m = m0 Á + mmin ˜
Á 2 ˜
Ë 1 + c —A ¯
where µmax = 5000, µmin = 200, and c = 0.05. The current density J is 0 everywhere except
in the coil, where it is 10 A/m2.
The geometry of the problem makes the magnetic vector potential A symmetric with
respect to y and antisymmetric with respect to x. Therefore, you can limit the domain to x
≥ 0, y ≥ 0 with the Neumann boundary condition
Ê1 ˆ
n ◊ Á —A ˜ = 0
Ë m ¯
on the x-axis and the Dirichlet boundary condition A = 0 on the y-axis. Because the field
outside the motor is negligible, you can use the Dirichlet boundary condition A = 0 on the
exterior boundary.
To solve this problem in the PDE Modeler app, follow these steps:
1 Set the x-axis limits to [-1.5 1.5] and the y-axis limits to [-1 1]. To do this, select
Options > Axes Limits and set the corresponding ranges.
2 Set the application mode to Magnetostatics.
3 Create the geometry. The geometry of this electric motor is complex. The model is a
union of five circles and two rectangles. The reduction to the first quadrant is
achieved by intersection with a square. To draw the geometry, enter the following
commands in the MATLAB Command Window:
pdecirc(0,0,1,'C1')
pdecirc(0,0,0.8,'C2')
pdecirc(0,0,0.6,'C3')
pdecirc(0,0,0.5,'C4')
pdecirc(0,0,0.4,'C5')
pderect([-0.2 0.2 0.2 0.9],'R1')
pderect([-0.1 0.1 0.2 0.9],'R2')
pderect([0 1 0 1],'SQ1')
3-106
Magnetic Field in a Two-Pole Electric Motor
3-107
3 Solving PDEs
6 Specify the boundary conditions. To do this, select the boundaries along the x-axis.
Select Boundary > Specify Boundary Conditions. In the resulting dialog box,
specify a Neumann boundary condition with g = 0 and q = 0.
All other boundaries have a Dirichlet boundary condition with h = 1 and r = 0, which
is the default boundary condition in the PDE Modeler app.
7 Specify the coefficients by selecting PDE > PDE Specification or clicking the PDE
button on the toolbar. Double-click each subdomain and specify the following
coefficients:
3-108
Magnetic Field in a Two-Pole Electric Motor
The plot shows that the magnetic flux is parallel to the equipotential lines of the
magnetostatic potential.
3-109
3 Solving PDEs
3-110
Helmholtz's Equation on Unit Disk with Square Hole
The Helmholtz equation, an elliptic equation that is the time-independent form of the
wave equation, is
Solving this equation allows us to compute the waves reflected by a square object
illuminated by incident waves that are coming from the left.
Problem Definition
• g: A geometry specification function. For more information, see the code for
scatterg.m and the documentation section Create Geometry Using a Geometry
Function.
• k, c, a, f: The coefficients and inhomogeneous term.
g = @scatterg;
k = 60;
c = 1;
a = -k^2;
f = 0;
numberOfPDE = 1;
model = createpde(numberOfPDE);
geometryFromEdges(model,g);
specifyCoefficients(model,'m',0,'d',0,'c',c,'a',a,'f',f);
3-111
3 Solving PDEs
Boundary Conditions
Plot the geometry and display the edge labels for use in the boundary condition definition.
figure;
pdegplot(model,'EdgeLabels','on');
axis equal
title 'Geometry With Edge Labels Displayed';
ylim([0,1])
3-112
Helmholtz's Equation on Unit Disk with Square Hole
Create Mesh
generateMesh(model,'Hmax',0.02);
figure
pdemesh(model);
axis equal
The real part of the vector u stores an approximation to a real-valued solution of the
Helmholtz equation.
result = solvepde(model);
u = result.NodalSolution;
3-113
3 Solving PDEs
figure
% pdeplot(model,'XYData',real(u),'ZData',real(u),'Mesh','off');
pdeplot(model,'XYData',real(u),'Mesh','off');
colormap(jet)
Using the solution to the Helmholtz equation, construct an animation showing the
corresponding solution to the time-dependent wave equation.
figure
m = 10;
3-114
Helmholtz's Equation on Unit Disk with Square Hole
h = newplot;
hf = h.Parent;
axis tight
ax = gca;
ax.DataAspectRatio = [1 1 1];
axis off
maxu = max(abs(u));
for j = 1:m
uu = real(exp(-j*2*pi/m*sqrt(-1))*u);
pdeplot(model,'XYData',uu,'ColorBar','off','Mesh','off');
colormap(jet)
caxis([-maxu maxu]);
axis tight
ax = gca;
ax.DataAspectRatio = [1 1 1];
axis off
M(j) = getframe(hf);
end
3-115
3 Solving PDEs
3-116
AC Power Electromagnetics
AC Power Electromagnetics
AC power electromagnetics problems are found when studying motors, transformers and
conductors carrying alternating currents.
∂H
— ¥ E = -m
∂t
∂E
— ¥H = e +J
∂t
For a more detailed discussion on Maxwell's equations, see Popovic, Branko D.,
Introductory Engineering Electromagnetics, Addison-Wesley, Reading, MA, 1971.
In the absence of current, we can eliminate H from the first set and E from the second set
and see that both fields satisfy wave equations with wave speed em :
∂2 E
DE - em =0
∂ t2
∂2 H
D H - em =0
∂ t2
J =sE
∂E ∂ 2E
DE - ms - em =0
∂t ∂t 2
The case of time harmonic fields is treated by using the complex form, replacing E by
3-117
3 Solving PDEs
E c e jwt
The plane case of this Partial Differential Equation Toolbox mode has
( )
E c = ( 0, 0, Ec ) , J = 0, 0, Je jw t , and the magnetic field
-1
H = ( H x , H y ,0 ) = — ¥ Ec
j ms
-— ·Á — Ec ˜ + ( jws - w 2e ) Ec = 0
Ê1 ˆ
Ë m ¯
This is the equation used by Partial Differential Equation Toolbox software in the AC
power electromagnetics application mode. It is a complex Helmholtz's equation,
describing the propagation of plane electromagnetic waves in imperfect dielectrics and
good conductors (σ » ωε). A complex permittivity εc can be defined as εc = ε-jσ/ω. The
conditions at material interfaces with abrupt changes of ε and µ are the natural ones for
the variational formulation and need no special attention.
The PDE parameters that have to be entered into the PDE Specification dialog box are the
angular frequency ω, the magnetic permeability µ, the conductivity σ, and the coefficient
of dielectricity ε.
The boundary conditions associated with this mode are a Dirichlet boundary condition,
specifying the value of the electric field Ec on the boundary, and a Neumann condition,
specifying the normal derivative of Ec. This is equivalent to specifying the tangential
component of the magnetic field H:
j Ê1 ˆ
Ht = n · Á — Ec ˜
w Ëm ¯
Interesting properties that can be computed from the solution—the electric field E—are
the current density J = σE and the magnetic flux density
j
B= —¥E
w
3-118
AC Power Electromagnetics
The electric field E, the current density J, the magnetic field H and the magnetic flux
density B are available for plots. Additionally, the resistive heating rate
Q = Ec2 / s
is also available. The magnetic field and the magnetic flux density can be plotted as vector
fields using arrows.
Example
The example shows the skin effect when AC current is carried by a wire with circular
cross section. The conductivity of copper is 57 · 106, and the permeability is 1, i.e.,
µ = 4π10–7. At the line frequency (50 Hz) the ω2ε-term is negligible.
Due to the induction, the current density in the interior of the conductor is smaller than
at the outer surface where it is set to JS = 1, a Dirichlet condition for the electric field,
Ec = 1/σ. For this case an analytical solution is available,
J0 ( kr )
J = JS
J 0 ( kR)
where
k= jwms
R is the radius of the wire, r is the distance from the center line, and J0(x) is the first
Bessel function of zeroth order.
Open the PDE Specification dialog box and enter the PDE parameters. The angular
frequency ω = 2π · 50.
3-119
3 Solving PDEs
Initialize the mesh and solve the equation. Due to the skin effect, the current density at
the surface of the conductor is much higher than in the conductor's interior. This is
clearly visualized by plotting the current density J as a 3-D plot. To improve the accuracy
of the solution close to the surface, you need to refine the mesh. Open the Solve
Parameters dialog box and select the Adaptive mode check box. Also, set the maximum
numbers of triangles to Inf, the maximum numbers of refinements to 1, and use the
triangle selection method that picks the worst triangles. Recompute the solution several
times. Each time the adaptive solver refines the area with the largest errors. The number
of triangles is printed in the command line.
3-120
AC Power Electromagnetics
The solution of the AC power electromagnetics equation is complex. The plots show the
real part of the solution (a warning message is issued), but the solution vector, which can
be exported to the main workspace, is the full complex solution. Also, you can plot various
properties of the complex solution by using the user entry. imag(u) and abs(u) are two
examples of valid user entries.
3-121
3 Solving PDEs
The skin effect is an AC phenomenon. Decreasing the frequency of the alternating current
results in a decrease of the skin effect. Approaching DC conditions, the current density is
close to uniform (experiment using different angular frequencies).
3-122
Conductive Media DC
Conductive Media DC
For electrolysis and computation of resistances of grounding plates, we have a conductive
medium with conductivity σ and a steady current. The current density J is related to the
electric field E through J = σE. Combining the continuity equation ∇ · J = Q, where Q is a
current source, with the definition of the electric potential V yields the elliptic Poisson's
equation
–∇ · (σ∇V) = Q.
The only two PDE parameters are the conductivity σ and the current source Q.
The Dirichlet boundary condition assigns values of the electric potential V to the
boundaries, usually metallic conductors. The Neumann boundary condition requires the
value of the normal component of the current density (n · (σ∇V)) to be known. It is also
possible to specify a generalized Neumann condition defined by n · (σ∇V) + qV = g,
where q can be interpreted as a film conductance for thin plates.
The electric potential V, the electric field E, and the current density J are all available for
plotting. Interesting quantities to visualize are the current lines (the vector field of J) and
the equipotential lines of V. The equipotential lines are orthogonal to the current lines
when σ is isotropic.
Example
Two circular metallic conductors are placed on a plane, thin conductor like a blotting
paper wetted by brine. The equipotentials can be traced by a voltmeter with a simple
probe, and the current lines can be traced by strongly colored ions, such as
permanganate ions.
The physical model for this problem consists of the Laplace equation
–∇ · (σ∇V) = 0
3-123
3 Solving PDEs
∂V
=0
∂n
pdeModeler
3-124
Conductive Media DC
6
Click and add two circles with radius 0.3 that represent the circular conductors.
Place them symmetrically with centers in (-0.6,0) and (0.6,0).
7 To express the 2-D domain of the problem, enter
R1-(C1+C2)
11 Hold down Shift and click to select the left circular conductor boundaries. Double-
click the last boundary to open the Boundary Condition dialog box.
12 Set the parameters as follows and then click OK:
3-125
3 Solving PDEs
13 Hold down Shift and click to select the right circular conductor boundaries. Double-
click the last boundary to open the Boundary Condition dialog box.
14 Set the parameters as follows and then click OK:
15 Open the PDE Specification dialog box by clicking PDE > PDE Specification.
3-126
Conductive Media DC
The resulting potential is zero along the y-axis, which is a vertical line of anti-
symmetry for this problem.
3-127
3 Solving PDEs
21
Visualize the current density J by clicking Plot > Parameters, selecting Contour
and Arrows check box, and clicking Plot.
The current flows, as expected, from the conductor with a positive potential to the
conductor with a negative potential.
3-128
Conductive Media DC
3-129
3 Solving PDEs
The 2-D geometry for this problem is a square with an embedded diamond (a square with
45 degrees rotation). PDE governing this problem is a parabolic heat equation:
∂T
rC - —◊ ( k—T ) = Q + h ( Text - T )
∂t
where ρ is the density, C is the heat capacity, k is the coefficient of heat conduction, Q is
the heat source, h is convective heat transfer coefficient, and Text is the external
temperature.
To solve this problem in the PDE Modeler app, follow these steps:
1 Model the geometry: draw the square region with corners in (0,0), (3,0), (3,3), and
(0,3) and the diamond-shaped region with corners in (1.5,0.5), (2.5,1.5), (1.5,2.5), and
(0.5,1.5).
pderect([0 3 0 3])
pdepoly([1.5 2.5 1.5 0.5],[0.5 1.5 2.5 1.5])
2 Set the x-axis limit to [-1.5 4.5] and y-axis limit to [-0.5 3.5]. To do this, select
Options > Axes Limits and set the corresponding ranges.
3 Set the application mode to Heat Transfer.
4 The temperature is kept at 0 on all the outer boundaries, so you do not have to
change the default Dirichlet boundary condition T = 0.
5 Specify the coefficients. To do this, select PDE > PDE Mode. Then click each region
and select PDE > PDE Specification or click the PDE button on the toolbar. Since
you are solving the parabolic heat equation, select the Parabolic type of PDE for
both regions. For the square region, specify the following coefficients:
• Density, pho = 2
• Heat capacity, C = 0.1
• Coefficient of heat conduction, k = 10
3-130
Heat Transfer Between Two Squares Made of Different Materials: PDE Modeler App
• Heat source, Q = 0
• Convective heat transfer coefficient, h = 0
• External temperature, Text = 0
• Density, pho = 1
• Heat capacity, C = 0.1
• Coefficient of heat conduction, k = 2
• Heat source, Q = 4
• Convective heat transfer coefficient, h = 0
• External temperature, Text = 0
6 Initialize the mesh by selecting Mesh > Initialize Mesh. For a more accurate
solution, refine the mesh by selecting Mesh > Refine Mesh.
7 Set the initial value and the solution time. To do this, select Solve > Parameters.
The dynamics for this problem is very fast — the temperature reaches steady state in
about 0.1 time units. To capture the interesting part of the dynamics, set time to
logspace(-2,-1,10). This gives 10 logarithmically spaced numbers between 0.01
and 0.1. Set the initial value of the temperature u(t0) to 0.
8 Solve the equation by selecting Solve > Solve PDE or clicking the = button on the
toolbar.
9 Plot the solution. By default, the app plots the temperature distribution at the last
time. The best way to visualize the dynamic behavior of the temperature is to animate
the solution. To do this, select Plot > Parameters and select the Animation and
Height (3-D plot) options to animate a 3-D plot. Also, you can select the Plot in x-y
grid option to use a rectangular grid instead of the default triangular grid. Using a
rectangular grid instead of a triangular grid speeds up the animation process
significantly.
You can also plot isothermal lines using a contour plot and the heat flux vector field
using arrows.
3-131
3 Solving PDEs
c Change the colormap to hot by using the corresponding drop-down menu in the
same dialog box.
d To obtain the first plot, select the Color and Contour options.
e For the second plot, select the Color and Arrows and set their values to
temperature and heat flux, respectively.
Isothermal Lines
3-132
Heat Transfer Between Two Squares Made of Different Materials: PDE Modeler App
3-133
3 Solving PDEs
The plate is square and the temperature is fixed along the bottom edge. No heat is
transferred from the other three edges (i.e. they are insulated). Heat is transferred from
both the top and bottom faces of the plate by convection and radiation. Because radiation
is included, the problem is nonlinear. One of the purposes of this example is to show how
to handle nonlinearities in PDE problems.
Both a steady state and a transient analysis are performed. In a steady state analysis we
are interested in the final temperature at different points in the plate after it has reached
an equilibrium state. In a transient analysis we are interested in the temperature in the
plate as a function of time. One question that can be answered by this transient analysis
is how long does it take for the plate to reach an equilibrium temperature.
The plate has planar dimensions one meter by one meter and is 1 cm thick. Because the
plate is relatively thin compared with the planar dimensions, the temperature can be
assumed constant in the thickness direction; the resulting problem is 2D.
Convection and radiation heat transfer are assumed to take place between the two faces
of the plate and a specified ambient temperature.
The amount of heat transferred from each plate face per unit area due to convection is
defined as
The amount of heat transferred from each plate face per unit area due to radiation is
defined as
where is the emissivity of the face and is the Stefan-Boltzmann constant. Because the
heat transferred due to radiation is proportional to the fourth power of the surface
temperature, the problem is nonlinear.
3-134
Nonlinear Heat Transfer in Thin Plate
where is the material density, is the specific heat, is the plate thickness, and the
factors of two account for the heat transfer from both plate faces.
Problem Parameters
numberOfPDE = 1;
model = createpde(numberOfPDE);
Geometry
For a square, the geometry and mesh are easily defined as shown below.
width = 1;
height = 1;
Define the square by giving the 4 x-locations followed by the 4 y-locations of the corners.
3-135
3 Solving PDEs
Convert the DECSG geometry into a geometry object on doing so it is appended to the
PDEModel
geometryFromEdges(model,g);
Plot the geometry and display the edge labels for use in the boundary condition definition.
figure;
pdegplot(model,'EdgeLabels','on');
axis([-.1 1.1 -.1 1.1]);
title 'Geometry With Edge Labels Displayed';
3-136
Nonlinear Heat Transfer in Thin Plate
The expressions for the coefficients required by PDE Toolbox can easily be identified by
comparing the equation above with the scalar parabolic equation in the PDE Toolbox
documentation.
c = thick*k;
Because of the radiation boundary condition, the "a" coefficient is a function of the
temperature, u. It is defined as a MATLAB expression so it can be evaluated for different
values of u during the analysis.
Boundary Conditions
The boundary conditions are defined below. Three of the plate edges are insulated.
Because a Neumann boundary condition equal zero is the default in the finite element
formulation, the boundary conditions on these edges do not need to be set explicitly. A
Dirichlet condition is set on all nodes on the bottom edge, edge 1,
applyBoundaryCondition(model,'dirichlet','Edge',1,'u',1000);
Initial guess
setInitialConditions(model,0);
Mesh
Create the triangular mesh on the square with approximately ten elements in each
direction.
3-137
3 Solving PDEs
Because the a and f coefficients are functions of temperature (due to the radiation
boundary conditions), solvepde automatically picks the nonlinear solver to obtain the
solution.
R = solvepde(model);
u = R.NodalSolution;
figure;
pdeplot(model,'XYData',u,'Contour','on','ColorMap','jet');
3-138
Nonlinear Heat Transfer in Thin Plate
3-139
3 Solving PDEs
Transient Solution
Set the initial temperature on the bottom edge E1 to the value of the constant BC, 1000
K.
3-140
Nonlinear Heat Transfer in Thin Plate
setInitialConditions(model,1000,'edge',1);
model.SolverOptions.RelativeTolerance = 1.0e-3;
model.SolverOptions.AbsoluteTolerance = 1.0e-4;
R = solvepde(model,tlist);
u = R.NodalSolution;
figure;
plot(tlist,u(3, :));
grid on
title 'Temperature Along the Top Edge of the Plate as a Function of Time'
xlabel 'Time, seconds'
ylabel 'Temperature, degrees-Kelvin'
figure;
pdeplot(model,'XYData',u(:,end),'Contour','on','ColorMap','jet');
title(sprintf('Temperature In The Plate, Transient Solution( %d seconds)\n', ...
tlist(1,end)));
xlabel 'X-coordinate, meters'
ylabel 'Y-coordinate, meters'
axis equal;
3-141
3 Solving PDEs
3-142
Nonlinear Heat Transfer in Thin Plate
Summary
As can be seen, the plots of temperature in the plate from the steady state and transient
solution at the ending time are very close. That is, after around 5000 seconds, the
transient solution has reached the steady state values. The temperatures from the two
solutions at the top edge of the plate agree to within one percent.
3-143
3 Solving PDEs
This example uses the PDE Modeler app. For a programmatic workflow, see “Poisson's
Equation on Unit Disk” on page 3-150. Because the app and the programmatic workflow
use different meshers, they yield slightly different results.
The problem formulation is –Δu = 1 in Ω, u = 0 on ∂Ω, where Ω is the unit disk. The exact
solution is
1 - x2 - y2
u ( x, y ) =
4
To solve this problem in the PDE Modeler app, follow these steps:
button. Then right-click the origin and drag to draw a circle. Right-clicking
constrains the shape you draw so that it is a circle rather than an ellipse. If the circle
is not a perfect unit circle, double-click it. In the resulting dialog box, specify the
exact center location and radius of the circle.
5 Check that the application mode is set to Generic Scalar.
6 Specify the boundary conditions. To do this, switch to boundary mode by clicking the
3-144
Poisson's Equation on Unit Disk: PDE Modeler App
9
Initialize the mesh by selecting Mesh > Initialize Mesh or clicking the button.
10 Solve the PDE by selecting Solve > Solve PDE or clicking the = button on the
toolbar. The toolbox assembles the PDE problem, solves it, and plots the solution.
3-145
3 Solving PDEs
3-146
Poisson's Equation on Unit Disk: PDE Modeler App
12
Refine the mesh by selecting Mesh > Refine Mesh or clicking the button.
3-147
3 Solving PDEs
13 Compare the numerical solution to the exact solution for the refined mesh. Plot the
absolute error.
3-148
Poisson's Equation on Unit Disk: PDE Modeler App
14 Export the mesh data and the solution to the MATLAB workspace by selecting Mesh
> Export Mesh and Solve > Export Solution, respectively.
3-149
3 Solving PDEs
The example uses the solvepde function. For the PDE Modeler app solution, see
“Poisson's Equation on Unit Disk: PDE Modeler App” on page 3-144. Because the app and
the programmatic workflow use different meshers, they yield slightly different results.
The Poisson equation on a unit disk with zero Dirichlet boundary condition can be written
as in , on , where is the unit disk. The exact solution is
For most PDEs, the exact solution is not known. However, the Poisson's equation on a unit
disk has a known, exact solution that you can use to see how the error decreases as you
refine the mesh.
Problem Definition
model = createpde();
geometryFromEdges(model,@circleg);
Plot the geometry and display the edge labels for use in the boundary condition definition.
figure
pdegplot(model,'EdgeLabels','on');
axis equal
3-150
Poisson's Equation on Unit Disk
3-151
3 Solving PDEs
pdemesh(model);
axis equal
results = solvepde(model);
u = results.NodalSolution;
pdeplot(model,'XYData',u)
title('Numerical Solution');
xlabel('x')
ylabel('y')
3-152
Poisson's Equation on Unit Disk
Compare this result with the exact analytical solution and plot the error.
p = model.Mesh.Nodes;
exact = (1 - p(1,:).^2 - p(2,:).^2)/4;
pdeplot(model,'XYData',u - exact')
title('Error');
xlabel('x')
ylabel('y')
3-153
3 Solving PDEs
Solve the equation while refining the mesh in each iteration and comparing the result
with the exact solution. Each refinement halves the Hmax value. Refine the mesh until the
infinity norm of the error vector is less than .
hmax = 0.1;
error = [];
err = 1;
while err > 5e-7 % run until error <= 5e-7
generateMesh(model,'Hmax',hmax); % refine mesh
results = solvepde(model);
u = results.NodalSolution;
3-154
Poisson's Equation on Unit Disk
p = model.Mesh.Nodes;
exact = (1 - p(1,:).^2 - p(2,:).^2)/4;
err = norm(u - exact',inf); % compare with exact solution
error = [error err]; % keep history of err
hmax = hmax/2;
end
Plot the infinity norm of the error vector for each iteration. The value of the error
decreases in each iteration.
plot(error,'rx','MarkerSize',12);
ax = gca;
ax.XTick = 1:numel(error);
title('Error History');
xlabel('Iteration');
ylabel('Norm of Error');
3-155
3 Solving PDEs
figure
pdemesh(model);
axis equal
3-156
Poisson's Equation on Unit Disk
figure
pdeplot(model,'XYData',u)
title('Numerical Solution');
xlabel('x')
ylabel('y')
3-157
3 Solving PDEs
Compare the result with the exact analytical solution and plot the error.
p = model.Mesh.Nodes;
exact = (1 - p(1,:).^2 - p(2,:).^2)/4;
pdeplot(model,'XYData',u - exact')
title('Error');
xlabel('x')
ylabel('y')
3-158
Poisson's Equation on Unit Disk
3-159
3 Solving PDEs
Scattering Problem
This example shows how to solve a simple scattering problem, where you compute the
waves reflected from an object illuminated by incident waves. For this problem, assume
an infinite horizontal membrane subjected to small vertical displacements U. The
membrane is fixed at the object boundary.
We assume that the medium is homogeneous so that the wave speed is constant, c.
Note Do not confuse this c with the parameter c appearing in Partial Differential
Equation Toolbox functions.
When the illumination is harmonic in time, we can compute the field by solving a single
steady problem. With
U(x,y,t) = u(x,y)e–iωt,
∂ 2U
- c2 DU = 0
2
∂t
turns into
–ω2u – c2Δu = 0
3-160
Scattering Problem
–Δu – k2u = 0,
where k, the wave number, is related to the angular frequency ω, the frequency f, and the
wavelength λ by
w 2p f 2p
k= = =
c c l
We have yet to specify the boundary conditions. Let the incident wave be a plane wave
traveling in the direction a = (cos(a), sin(a)):
r
V ( x, y, t) = e (
i ka◊ x-w t)
rr
= v( x, y) e-iw t
where
v( x, y) = eika◊x
r r
U = V + R.
Reflected wave can be decomposed into spatial and time component as:
R ( x, y, t ) = r ( x, y ) e-iw t
R = –V(x,y,t)
For acoustic waves, where V is the pressure disturbance, the proper condition would be
∂u
=0
∂n
The reflected wave R travels outward from the object. The condition at the outer
computational boundary should be chosen to allow waves to pass without reflection. Such
conditions are usually called nonreflecting, and we use the classical Sommerfeld radiation
3-161
3 Solving PDEs
∂R r
+ cx · —R = 0
∂t
which allows waves moving in the positive ξ-direction only (ξ is the radial distance from
the object). With the time-harmonic solution, this turns into the generalized Neumann
boundary condition
r
x · — r = ikr
For simplicity, let us make the outward normal of the computational domain approximate
the outward ξ-direction.
For the outer boundary (the circle perimeter), the boundary condition is a generalized
Neumann condition with q = –ik. The wave number k = 60, which corresponds to a
wavelength of about 0.1 units, so enter -60i as a constant q and 0 as a constant g.
For the square object's boundary, you have a Dirichlet boundary condition:
r = -v ( x, y ) = - eika ◊ x
r r
In this problem, the reflected wave is traveling in the -x direction, and so the boundary
condition is simply
r = –e–ikx.
Enter this boundary condition in the Boundary Condition dialog box as a Dirichlet
condition: h = 1, r = -exp(-i*60*x). The real part of this is a sinusoid.
For sufficient accuracy, about 10 finite elements per wavelength are needed. The outer
boundary should be located a few object diameters from the object itself. An initial mesh
3-162
Scattering Problem
generation and two successive mesh refinements give approximately the desired
resolution.
The problem can now be solved, and the solution is complex. For a complex solution, the
real part is plotted and a warning message is issued. Plot the reflected waves setting the
colormap to jet.
3-163
3 Solving PDEs
( i( ka◊ x-w t)
)
rr
Re e
3-164
Scattering Problem
(( )
Re r( x, y) + eika◊ x e-iwt )
rr
The reflected waves and the “shadow” behind the object are clearly visible in this plot.
To make an animation of the reflected wave, first export the solution and the mesh data to
the MATLAB workspace. To export the mesh, select Export Mesh from the Mesh menu.
To export the solution, select Export Solution from the Solve menu.
Then make a script file or type the following commands at the MATLAB prompt:
3-165
3 Solving PDEs
Ê ˆ
Á 1 ˜
-— ◊ Á —u ˜ = 0
Á 1 + —u 2 ˜
Ë ¯
where the coefficients c, a, and f do not depend only on x and y, but also on the solution u.
This example shows how to solve this minimal surface problem using both the PDE
Modeler app and command-line functions.
1
c= , a = 0, and f = 0
2
1 + —u
1./sqrt(1+ux.^2+uy.^2)
Before solving the PDE, select Parameters from the Solve menu and check the Use
nonlinear solver option. Also, set the tolerance parameter to 0.001.
3-166
Minimal Surface Problem
Click the = button to solve the PDE. Use the Plot Selection dialog box to plot the solution
in 3-D (check u and continuous selections in the Height column) to visualize the saddle
shape of the solution.
A Nonlinear PDE
A nonlinear problem is one whose coefficients not only depend on spatial coordinates, but
also on the solution itself. An example of this is the minimal surface equation
on the boundary. To express this equation in toolbox form, note that the elliptic equation
in toolbox syntax is
is a function of the solution , so the problem is nonlinear. In toolbox syntax, you see
that the and coefficients are 0.
Geometry
Create a PDE Model with a single dependent variable, and include the geometry of the
unit disk. The circleg function represents this geometry. Plot the geometry and display
the edge labels.
3-167
3 Solving PDEs
numberOfPDE = 1;
model = createpde(numberOfPDE);
geometryFromEdges(model,@circleg);
pdegplot(model,'EdgeLabels','on');
axis equal
title 'Geometry with Edge Labels';
a = 0;
f = 0;
cCoef = @(region,state) 1./sqrt(1+state.ux.^2 + state.uy.^2);
specifyCoefficients(model,'m',0,'d',0,'c',cCoef,'a',a,'f',f);
3-168
Minimal Surface Problem
Boundary Conditions
bcMatrix = @(region,~)region.x.^2;
applyBoundaryCondition(model,'dirichlet',...
'Edge',1:model.Geometry.NumEdges,...
'u',bcMatrix);
Generate Mesh
generateMesh(model,'Hmax',0.1);
figure;
pdemesh(model);
axis equal
3-169
3 Solving PDEs
Solve PDE
Because the problem is nonlinear, solvepde invokes nonlinear solver. Observe the solver
progress by setting the SolverOptions.ReportStatistics property of model to
'on'.
model.SolverOptions.ReportStatistics = 'on';
result = solvepde(model);
u = result.NodalSolution;
3-170
Minimal Surface Problem
Plot Solution
figure;
pdeplot(model,'XYData',u,'ZData',u);
xlabel 'x'
ylabel 'y'
zlabel 'u(x,y)'
title 'Minimal surface'
3-171
3 Solving PDEs
on the unit disk with zero Dirichlet boundary conditions. The exact solution expressed in
polar coordinates is
By using adaptive mesh refinement, Partial Equation Toolbox™ can accurately find the
solution everywhere away from the origin.
c = 1;
a = 0;
f = @circlef;
numberOfPDE = 1;
model = createpde(numberOfPDE);
Create a geometry and include it in the model. For more information, see the |circleg| and
|pdegeom| pages.
g = @circleg;
geometryFromEdges(model,g);
3-172
Poisson's Equation with Point Source and Adaptive Mesh Refinement
figure;
pdegplot(model,'EdgeLabels','on');
axis equal
title 'Geometry With Edge Labels Displayed';
Specify the zero solution at all four outer edges of the circle.
applyBoundaryCondition(model,'dirichlet','Edge',(1:4),'u',0);
adaptmesh solves elliptic PDEs using the adaptive mesh generation. The 'tripick'
parameter lets you specify a function that returns which triangles will be refined in the
3-173
3 Solving PDEs
next iteration. circlepick returns triangles with computed error estimates greater a
given tolerance. The tolerance is provided to circlepick using the 'par' parameter.
[u,p,e,t] = adaptmesh(g,model,c,a,f,'tripick','circlepick','maxt',2000,'par',1e-3);
figure;
pdemesh(p,e,t);
axis equal
3-174
Poisson's Equation with Point Source and Adaptive Mesh Refinement
x = p(1,:)';
y = p(2,:)';
r = sqrt(x.^2+y.^2);
uu = -log(r)/2/pi;
figure;
pdeplot(p,e,t,'XYData',u-uu,'ZData',u-uu,'Mesh','off');
3-175
3 Solving PDEs
figure;
pdeplot(p,e,t,'XYData',u,'ZData',u,'Mesh','off');
3-176
Poisson's Equation with Point Source and Adaptive Mesh Refinement
3-177
3 Solving PDEs
Consider a block containing a rectangular crack or cavity. The left side of the block is
heated to 100 degrees centigrade. At the right side of the block, heat flows from the block
to the surrounding air at a constant rate, for example -10 W/m2. All the other boundaries
are insulated. The temperature in the block at the starting time t0 = 0 is 0 degrees. The
goal is to model the heat distribution during the first five seconds.
The PDE governing this problem is a parabolic heat equation. Partial Differential Equation
Toolbox solves the generic parabolic PDE of the form
∂u
d - — ◊ ( c— u ) + au = f
∂t
∂u
d - Du = 0
∂t
To solve this problem in the PDE Modeler app, follow these steps:
pdeModeler
2 Model the geometry: draw a rectangle with corners (-0.5,-0.8), (0.5,-0.8), (0.5,0.8),
and (-0.5,0.8) and a rectangle with corners (-0.05,-0.4), (0.05,-0.4), (0.05,0.4), and
(-0.05,0.4). Draw the first rectangle by using the pderect function.
3-178
Heat Transfer in Block with Cavity: PDE Modeler App
4 Set the x-axis limit to [-0.6 0.6] and y-axis limit to [-1 1]. To do this, select
Options > Axes Limits and set the corresponding ranges.
5 Select Options > Snap to align any new shape to the grid lines. Then draw the
rectangle with corners (-0.05,-0.4), (0.05,-0.4), (0.05,0.4), and (-0.05,0.4)
6 Model the geometry by entering R1-R2 in the Set formula field.
7 Check that the application mode is set to Generic Scalar.
8 Specify the boundary conditions. To do this, switch to the boundary mode by
selecting Boundary > Boundary Mode. Then select Boundary > Specify
Boundary Conditions and specify the Neumann boundary condition.
• For convenience, first specify the insulating Neumann boundary condition ∂u/∂n =
0 for all boundaries. To do this, select all boundaries by using Edit > Select All
and specify g = 0, q = 0.
• Specify the Dirichlet boundary condition u = 100 for the left side of the block. To
do this, specify h = 1, r = 100.
• Specify the Neumann boundary condition ∂u/∂n = –10 for the right side of the
block. To do this, specify g = -10, q = 0.
3-179
3 Solving PDEs
9 Specify the coefficients by selecting PDE > PDE Specification or clicking the PDE
button on the toolbar. Heat equation is a parabolic equation, so select the Parabolic
type of PDE. Specify c = 1, a = 0, f = 0, and d = 1.
10 Initialize the mesh by selecting Mesh > Initialize Mesh. Refine the mesh by
selecting Mesh > Refine Mesh.
11 Set the initial value to 0, the solution time to 5 seconds, and compute the solution
every 0.5 seconds. To do this, select Solve > Parameters. In the Solve Parameters
dialog box, set time to 0:0.5:5, and u(t0) to 0.
12 Solve the PDE by selecting Solve > Solve PDE or clicking the = button on the
toolbar. The app solves the heat equation at 11 different times from 0 to 5 seconds
and displays the heat distribution at the end of the time span.
13 Plot isothermal lines using a contour plot and the heat flux vector field using arrows
and change the colormap to hot. To do this:
3-180
Heat Transfer in Block with Cavity: PDE Modeler App
14 Use an animated plot to visualize the dynamic behavior of the temperature. For this,
select Plot > Parameters and then select the Animation option.
15 The temperature in the block rises very quickly. To improve the animation and focus
on the first second, change the list of times to the MATLAB expression
logspace(-2,0.5,20). To do this, select Solve > Parameters. In the Solve
Parameters dialog box, set time to logspace(-2,0.5,20).
3-181
3 Solving PDEs
16 You can explore the solution by varying the parameters of the model and plotting the
results. For example, change the heat capacity coefficient d and the heat flow at the
right boundary to see how these parameters affect the heat distribution.
3-182
Heat Transfer in Block with Cavity
Consider a block containing a rectangular crack or cavity. The left side of the block is
heated to 100 degrees centigrade. At the right side of the block, heat flows from the block
to the surrounding air at a constant rate, for example . All the other boundaries
are insulated. The temperature in the block at the starting time is 0 degrees. The
goal is to model the heat distribution during the first five seconds.
thermalmodel = createpde('thermal','transient');
geometryFromEdges(thermalmodel,@crackg);
pdegplot(thermalmodel,'EdgeLabels','on');
ylim([-1,1])
axis equal
3-183
3 Solving PDEs
thermalProperties(thermalmodel,'ThermalConductivity',1,...
'MassDensity',1,...
'SpecificHeat',1);
Set the boundary conditions to have the solution u equal to 100 on the left edge (edge 6),
and g equal to -10 on the right edge (edge 1). The boundary condition on edge 1
corresponds to constant heat flow to the exterior. The toolbox uses the default insulating
boundary condition for all other boundaries.
thermalBC(thermalmodel,'Edge',6,'Temperature',20);
thermalBC(thermalmodel,'Edge',1,'HeatFlux',-10);
3-184
Heat Transfer in Block with Cavity
thermalIC(thermalmodel,0);
tlist = 0:0.5:5;
generateMesh(thermalmodel);
thermalresults = solve(thermalmodel,tlist);
T = thermalresults.Temperature;
Compute the heat flux density. Plot the solution at t = 5.0 seconds with isothermal lines
using a contour plot, and plot the heat flux vector field using arrows.
[qx,qy] = evaluateHeatFlux(thermalresults);
pdeplot(thermalmodel,'XYData',T(:,end),'Contour','on',...
'FlowData',[qx(:,end),qy(:,end)],'ColorMap','hot')
3-185
3 Solving PDEs
3-186
Heat Transfer Problem with Temperature-Dependent Properties
The partial differential equation for transient conduction heat transfer is:
where is the temperature, is the material density, is the specific heat, and is the
thermal conductivity. is the heat generated inside the body which is zero in this
example.
thermalmodelS = createpde('thermal','steadystate');
Create a 2-D geometry by drawing one rectangle the size of the block and a second
rectangle the size of the slot.
Subtract the second rectangle from the first to create the block with a slot.
g = decsg(gdm,'R1-R2',['R1'; 'R2']');
Convert the decsg format into a geometry object. Include the geometry in the model.
geometryFromEdges(thermalmodelS,g);
Plot the geometry with edge labels displayed. The edge labels will be used below in the
function for defining boundary conditions.
3-187
3 Solving PDEs
figure
pdegplot(thermalmodelS,'EdgeLabels','on');
axis([-.9 .9 -.9 .9]);
title 'Block Geometry With Edge Labels Displayed'
Set the temperature on the left edge to 100 degrees. On the right edge, there is a
prescribed heat flux out of the block. The top and bottom edges and the edges inside the
cavity are all insulated, that is, no heat is transferred across these edges.
thermalBC(thermalmodelS,'Edge',1,'HeatFlux',-10);
thermalBC(thermalmodelS,'Edge',6,'Temperature',100);
3-188
Heat Transfer Problem with Temperature-Dependent Properties
Specify the thermal conductivity of the material. First, consider the constant thermal
conductivity, for example, equal one. Later, consider a case where the thermal
conductivity is a function of temperature.
thermalProperties(thermalmodelS,'ThermalConductivity',1);
generateMesh(thermalmodelS,'Hmax',0.2);
figure
pdeplot(thermalmodelS);
axis equal
title 'Block With Finite Element Mesh Displayed'
3-189
3 Solving PDEs
3-190
Heat Transfer Problem with Temperature-Dependent Properties
Specify thermal conductivity, mass density, and specific heat of the material.
thermalProperties(thermalmodelT,'ThermalConductivity',1,...
'MassDensity',1,...
'SpecificHeat',1);
Define boundary conditions. In the transient cases, the temperature on the left edge is
zero at time=0 and ramps to 100 degrees over .5 seconds. On the right edge, there is a
prescribed heat flux out of the block. The top and bottom edges as well as the edges
inside the cavity are all insulated, that is no heat is transferred across these edges.
thermalBC(thermalmodelT,'Edge',1,'HeatFlux',-10);
thermalBC(thermalmodelT,'Edge',6,'Temperature',@transientBCHeatedBlock);
msh = generateMesh(thermalmodelT,'Hmax',0.2);
figure
pdeplot(thermalmodelT);
axis equal
title 'Block With Finite Element Mesh Displayed'
3-191
3 Solving PDEs
Calculate the transient solution. Perform a transient analysis from zero to five seconds.
The toolbox saves the solution every .1 seconds so that plots of the results as functions of
time can be created.
tlist = 0:.1:5;
thermalIC(thermalmodelT,0);
R = solve(thermalmodelT,tlist);
T = R.Temperature;
Two plots are useful in understanding the results from this transient analysis. The first is
a plot of the temperature at the final time. The second is a plot of the temperature at a
specific point in the block, in this case near the center of the right edge, as a function of
time. To identify a node near the center of the right edge, it is convenient to define this
short utility function.
3-192
Heat Transfer Problem with Temperature-Dependent Properties
Call this function to get a node near the center of the right edge.
The two plots are shown side-by-side in the figure below. The temperature distribution at
this time is very similar to that obtained from the steady-state solution above. At the right
edge, for times less than about one-half second, the temperature is less than zero. This is
because heat is leaving the block faster than it is arriving from the left edge. At times
greater than about three seconds, the temperature has essentially reached steady-state.
h = figure;
h.Position = [1 1 2 1].*h.Position;
subplot(1,2,1);
axis equal
pdeplot(thermalmodelT,'XYData',T(:,end),'Contour','on','ColorMap','hot');
axis equal
title 'Temperature, Final Time, Transient Solution'
subplot(1,2,2);
axis equal
plot(tlist, T(nid,:));
grid on
title 'Temperature at Right Edge as a Function of Time';
xlabel 'Time, seconds'
ylabel 'Temperature, degrees-Celsius'
3-193
3 Solving PDEs
It is not uncommon for material properties to be functions of the dependent variables. For
example, assume that the thermal conductivity is a simple linear function of temperature:
k = @(~,state) 0.3+0.003*state.u;
In this case, the variable u is the temperature. For this example, assume that the density
and specific heat are not functions of temperature.
thermalProperties(thermalmodelS,'ThermalConductivity',k);
Calculate the steady-state solution. Compared with the constant-conductivity case, the
temperature on the right-hand edge is lower. This is due to the lower conductivity in
regions with lower temperature.
R = solve(thermalmodelS);
T = R.Temperature;
figure
pdeplot(thermalmodelS,'XYData',T,'Contour','on','ColorMap','hot');
axis equal
title 'Temperature, Steady State Solution'
3-194
Heat Transfer Problem with Temperature-Dependent Properties
thermalProperties(thermalmodelT,'ThermalConductivity',k,...
'MassDensity',1,...
'SpecificHeat',1);
Use the same timespan tlist = 0:.1:5 as for the linear case.
thermalIC(thermalmodelT,0);
R = solve(thermalmodelT,tlist);
T = R.Temperature;
3-195
3 Solving PDEs
Plot the temperature at the final time step and the temperature at the right edge as a
function of time. The plot of temperature at the final time step is only slightly different
from the comparable plot from the linear analysis: temperature at the right edge is
slightly lower than the linear case. The plot of temperature as a function of time is
considerably different from the linear case. Because of the lower conductivity at lower
temperatures, the heat takes longer to reach the right edge of the block. In the linear
case, the temperature is essentially constant at around three seconds but for this
nonlinear case, the temperature curve is just beginning to flatten at five seconds.
h = figure;
h.Position = [1 1 2 1].*h.Position;
subplot(1,2,1);
axis equal
pdeplot(thermalmodelT,'XYData',T(:,end),'Contour','on','ColorMap','hot');
axis equal
title 'Temperature, Final Time, Transient Solution'
subplot(1,2,2);
axis equal
plot(tlist(1:size(T,2)), T(nid,:));
grid on
title 'Temperature at Right Edge as a Function of Time (Nonlinear)';
xlabel 'Time, seconds'
ylabel 'Temperature, degrees-Celsius'
3-196
Heat Conduction in Multidomain Geometry with Nonuniform Heat Flux
Problem Description
The physical properties and geometry of this problem are described in Singh, Jain, and
Rizwan-uddin [1], which also has an analytical solution for this problem. The inner face of
the sphere has a temperature of zero at all times. The outer hemisphere with positive
value has a nonuniform heat flux defined by
and are azimuthal and elevation angles of points in the sphere. Initially, the
temperature at all points in the sphere is zero.
thermalmodel = createpde('thermal','transient');
Define Geometry
Create a multilayered sphere using the multisphere function. Assign the resulting
geometry to the thermal model. The sphere has three layers of material with a hollow
inner core.
gm = multisphere([1,2,4,6],'Void',[true,false,false,false]);
thermalmodel.Geometry = gm;
Plot the geometry and show the cell labels and face labels. Use a FaceAlpha of 0.25 so
that labels of the interior layers are visible.
3-197
3 Solving PDEs
figure('Position',[10,10,800,400]);
subplot(1,2,1)
pdegplot(thermalmodel,'FaceAlpha',0.25,'CellLabel','on')
title('Geometry with Cell Labels')
subplot(1,2,2)
pdegplot(thermalmodel,'FaceAlpha',0.25,'FaceLabel','on')
title('Geometry with Face Labels')
Generate Mesh
Generate a mesh for the geometry. Choose a mesh size that is coarse enough to speed the
solution, but fine enough to represent the geometry reasonably accurately.
generateMesh(thermalmodel,'Hmax',1);
Specify thermal conductivity, mass density, and specific heat for each layer of the sphere.
The material properties are dimensionless values, not given by realistic material
properties.
thermalProperties(thermalmodel,'Cell',1,'ThermalConductivity',1, ...
'MassDensity',1, ...
3-198
Heat Conduction in Multidomain Geometry with Nonuniform Heat Flux
'SpecificHeat',1);
thermalProperties(thermalmodel,'Cell',2,'ThermalConductivity',2, ...
'MassDensity',1, ...
'SpecificHeat',0.5);
thermalProperties(thermalmodel,'Cell',3,'ThermalConductivity',4, ...
'MassDensity',1, ...
'SpecificHeat',4/9);
Boundary Conditions
thermalBC(thermalmodel,'Face',1,'Temperature',0);
The outer surface of the sphere has an external heat flux. Use the functional form of
thermal boundary conditions to define the heat flux.
[phi,theta,r] = meshgrid(linspace(0,2*pi),linspace(-pi/2,pi/2),6);
[x,y,z] = sph2cart(phi,theta,r);
region.x = x;
region.y = y;
region.z = z;
flux = externalHeatFlux(region,[]);
figure
surf(x,y,z,flux,'LineStyle','none')
axis equal
view(130,10)
colorbar
xlabel 'x'
ylabel 'y'
zlabel 'z'
title('External Flux')
3-199
3 Solving PDEs
thermalBC(thermalmodel,'Face',4,'HeatFlux',@externalHeatFlux,'Vectorized','on');
Initial Conditions
thermalIC(thermalmodel,0);
Solve Problem
3-200
Heat Conduction in Multidomain Geometry with Nonuniform Heat Flux
tlist = [0,2,5:5:50];
R = solve(thermalmodel,tlist);
To plot contours at several times, with the contour levels being the same for all plots,
determine the range of temperatures in the solution. The minimum temperature is zero
because it is the boundary condition on the inner face of the sphere.
Tmin = 0;
Tmax = max(R.Temperature(:,end));
h = figure;
for i = 1:numel(tlist)
pdeplot3D(thermalmodel,'ColorMapData',R.Temperature(:,i))
caxis([Tmin,Tmax])
view(130,10)
title(['Temperature at Time ' num2str(tlist(i))]);
M(i) = getframe;
end
3-201
3 Solving PDEs
To see a movie of the contours when running this example on your computer, execute the
following line:
movie(M,2)
[YG,ZG] = meshgrid(linspace(-6,6,100),linspace(-6,6,100));
XG = zeros(size(YG));
Interpolate the temperature at the grid points. Perform interpolation for several time
steps to observe the evolution of the temperature contours.
3-202
Heat Conduction in Multidomain Geometry with Nonuniform Heat Flux
tIndex = [2,3,5,7,9,11];
varNames = {'Time_index','Time_step'};
table(tIndex.',tlist(tIndex).','VariableNames',varNames)
TG = interpolateTemperature(R,XG,YG,ZG,tIndex);
ans =
6x2 table
Time_index Time_step
__________ _________
2 2
3 5
5 15
7 25
9 35
11 45
t = linspace(0,2*pi);
ylayer1 = cos(t); zlayer1 = sin(t);
ylayer2 = 2*cos(t); zlayer2 = 2*sin(t);
ylayer3 = 4*cos(t); zlayer3 = 4*sin(t);
ylayer4 = 6*cos(t); zlayer4 = 6*sin(t);
Plot the contours in the range Tmin to Tmax for the time steps corresponding to the time
indices tIndex.
figure('Position',[10,10,1000,550]);
for i = 1:numel(tIndex)
subplot(2,3,i)
contour(YG,ZG,reshape(TG(:,i),size(YG)),'ShowText','on')
colorbar
title(['Temperature at Time ' num2str(tlist(tIndex(i)))]);
hold on
caxis([Tmin,Tmax])
axis equal
% Plot boundaries of spherical layers for reference.
plot(ylayer1,zlayer1,'k','LineWidth',1.5)
plot(ylayer2,zlayer2,'k','LineWidth',1.5)
plot(ylayer3,zlayer3,'k','LineWidth',1.5)
3-203
3 Solving PDEs
plot(ylayer4,zlayer4,'k','LineWidth',1.5)
end
Reference
[1] Singh, Suneet, P. K. Jain, and Rizwan-uddin. "Analytical Solution for Three-
Dimensional, Unsteady Heat Conduction in a Multilayer Sphere." ASME. J. Heat Transfer.
138(10), 2016, pp. 101301-101301-11.
3-204
Inhomogeneous Heat Equation on Square Domain
This is solved on a square domain with a discontinuous initial condition and zero
temperatures on the boundaries.
thermalmodel = createpde('thermal','transient');
R1 = [3;4;-1;1;1;-1;-1;-1;1;1];
C1 = [1;0;0;0.4];
C1 = [C1;zeros(length(R1) - length(C1),1)];
gd = [R1,C1];
sf = 'R1+C1';
ns = char('R1','C1')';
g = decsg(gd,sf,ns);
geometryFromEdges(thermalmodel,g);
thermalProperties(thermalmodel,'ThermalConductivity',1,...
'MassDensity',1,...
'SpecificHeat',1);
internalHeatSource(thermalmodel,1);
3-205
3 Solving PDEs
Plot the geometry and display the edge labels for use in the boundary condition definition.
figure
pdegplot(thermalmodel,'EdgeLabels','on','FaceLabels','on')
axis([-1.1 1.1 -1.1 1.1]);
axis equal
title 'Geometry With Edge and Subdomain Labels'
thermalBC(thermalmodel,'Edge',1:4,'Temperature',0);
3-206
Inhomogeneous Heat Equation on Square Domain
The discontinuous initial value is 1 inside the circle and zero outside. Specify zero initial
temperature everywhere.
thermalIC(thermalmodel,0);
% Specify non-zero initial temperature inside the circle (Face 2).
thermalIC(thermalmodel,1,'Face',2);
3-207
3 Solving PDEs
nframes = 20;
tlist = linspace(0,0.1,nframes);
thermalmodel.SolverOptions.ReportStatistics ='on';
result = solve(thermalmodel,tlist);
T = result.Temperature;
99 successful steps
0 failed attempts
200 function evaluations
1 partial derivatives
20 LU decompositions
199 solutions of linear systems
figure
Tmax = max(max(T));
Tmin = min(min(T));
for j = 1:nframes,
pdeplot(thermalmodel,'XYData',T(:,j),'ZData',T(:,j));
caxis([Tmin Tmax]);
axis([-1 1 -1 1 0 1]);
Mv(j) = getframe;
end
3-208
Inhomogeneous Heat Equation on Square Domain
3-209
3 Solving PDEs
The model geometry, material properties, and boundary conditions must all be symmetric
about a single axis for this simplification from 3-D to 2-D to be appropriate. Because of
this symmetry, a cylindrical coordinate system is the most convenient form for defining
the partial differential equation. However, Partial Differential Equation Toolbox™ expects
the equations in a Cartesian system. One of the main goals of this example is to show how
to express the PDE defined in a cylindrical system in a Cartesian form that Partial
Differential Equation Toolbox™ can handle.
This particular example shows heat transfer in a rod with a circular cross section. There
is a heat source at the left end of the rod and a fixed temperature at the right end. The
outer surface of the rod exchanges heat with the environment due to convection. In
addition, heat is generated within the rod due to radioactive decay.
We would like to calculate the temperature in the rod as a function of time. The parabolic
equation describing heat transfer is
where are the density, specific heat, and thermal conductivity of the material,
respectively, is the temperature, and is the heat generated in the rod.
where , and are the three coordinate variables of the cylindrical system. Because
the problem is axisymmetric, and after multiplying by the equation can be
rewritten
3-210
Heat Distribution in Circular Cylindrical Rod
The equation can be converted to the form supported by PDE Toolbox if is defined as
and is defined as . Rewriting the above equation gives
In transient problems of this type it is often useful to first compute the steady state
solution-- the solution to the time-independent, elliptic equation. If the final time in the
transient analysis is sufficiently large, the transient solution at the final time should be
close to this steady state solution. This provides a valuable check on the accuracy of the
transient analysis.
thermalModelS = createpde('thermal');
The 2-D model is a rectangular strip whose y-dimension extends from the axis of
symmetry to the outer surface and x-dimension extends over the actual length of the rod
(from -1.5 m to 1.5 m). The geometry and mesh for this rectangular section are easily
defined by specifying the x and y locations of the four corners as shown below.
geometryFromEdges(thermalModelS,g);
3-211
3 Solving PDEs
thermalProperties(thermalModelS,'ThermalConductivity',kFunc);
internalHeatSource(thermalModelS,qFunc);
When defining boundary conditions below, it is necessary to know the edge numbers for
the boundary edges of the geometry. A convenient way to obtain these edge numbers is to
plot the geometry using pdegplot with option edgeLabels set to 'on'.
figure
pdegplot(thermalModelS,'EdgeLabels','on');
axis equal
xlim([-2 2]);
title 'Rod Section Geometry With Edge Labels Displayed';
3-212
Heat Distribution in Circular Cylindrical Rod
Define the boundary conditions. Edge 1, which is the edge at equal zero, is along the
axis of symmetry so there is no heat transferred in the direction normal to this edge. This
boundary is modeled by the default as an insulated boundary. Edge 2 is kept at a constant
temperature T = 100 C. Boundary conditions for the edges 3 and 4 are functions of y.
thermalBC(thermalModelS,'Edge',2,'Temperature',100);
3-213
3 Solving PDEs
3-214
Heat Distribution in Circular Cylindrical Rod
figure;
pdeplot(thermalModelS,'XYData',T,'Contour','on');
axis equal
title 'Steady State Temperature';
Transient Solution
Create a thermal model for transient analysis, include the geometry, and mesh.
thermalModelT = createpde('thermal','transient');
3-215
3 Solving PDEs
generateMesh(thermalModelT,'Hmax',0.1);
For a transient analysis, specify the thermal conductivity, mass density, specific heat of
the material.
thermalProperties(thermalModelT,'ThermalConductivity',kFunc,...
'MassDensity',rho,...
'SpecificHeat',cFunc);
thermalBC(thermalModelT,'Edge',2,'Temperature',100);
thermalBC(thermalModelT,'Edge',3,...
'ConvectionCoefficient',outerCC,...
'AmbientTemperature',100);
thermalBC(thermalModelT,'Edge',4,'HeatFlux',leftHF);
Compute the transient solution for solution times from to seconds. Initial
temperature in the rod is zero.
tfinal = 20000;
tlist = 0:100:tfinal;
thermalIC(thermalModelT,0);
thermalModelT.SolverOptions.ReportStatistics = 'on';
result = solve(thermalModelT,tlist);
T = result.Temperature;
3-216
Heat Distribution in Circular Cylindrical Rod
The steady state solution and the transient solution at 20000 seconds are in close
agreement. This can be seen by comparing the two figures.
The third figure below shows the temperature at the left end of the rod as a function of
time. The outer surface of the rod is exposed to the environment with a constant
temperature of 100 degrees-C. Consequently, when the surface temperature of the rod is
less than 100, the rod is being heated by the environment and when greater than 100,
cooled. When the rod temperature is less than 100 degrees, the outer surface is slightly
warmer than the inner axis but when the temperature is around 100 degrees, the outer
surface becomes cooler than the interior of the rod.
Find nodes on the left end of the rod and on the center axis and outer surface using their
coordinate values.
3-217
3 Solving PDEs
p = thermalModelT.Mesh.Nodes;
nodesLeftEnd = find(p(1,:) < -1.5+eps);
nodeCenter = nodesLeftEnd(p(2,nodesLeftEnd) < eps);
nodeOuter = nodesLeftEnd(p(2,nodesLeftEnd) > 0.2-eps);
figure;
plot(tlist,T(nodeCenter,:));
hold all
plot(tlist,T(nodeOuter,:),'--');
title 'Temperature at Left End as a Function of Time'
xlabel 'Time, seconds'
ylabel 'Temperature, degrees-C'
grid on;
legend('Center Axis','Outer Surface','Location','SouthEast');
3-218
Heat Distribution in Circular Cylindrical Rod
3-219
3 Solving PDEs
Consider a cylindrical radioactive rod. Heat is continuously added at the left end of the
rod, while the right end is kept at a constant temperature. At the outer boundary, heat is
exchanged with the surroundings by transfer. At the same time, heat is uniformly
produced in the whole rod due to radioactive processes. Assuming that the initial
temperature is zero leads to the following equation:
∂u
rC - — · ( k— u) = q
∂t
Here, ρ, C, and k are the density, thermal capacity, and thermal conductivity of the
material, u is the temperature, and q is the heat generated in the rod.
∂ u 1 ∂ Ê ∂ u ˆ 1 ∂ Ê ∂ u ˆ ∂ Ê ∂u ˆ
rC - Á kr ˜- Ák ˜- Ák ˜ = q
∂t r ∂r Ë ∂ r ¯ r 2 ∂q Ë ∂q ¯ ∂ z Ë ∂z ¯
Here r, θ, and z are the three coordinate variables of the cylindrical system. Because the
problem is axisymmetric, ∂ u ∂q = 0 .
This is a cylindrical problem, and Partial Differential Equation Toolbox requires equations
to be in Cartesian coordinates. To transform the equation to the Cartesian coordinates,
first multiply both sides of the equation by r:
∂u ∂ Ê ∂ u ˆ ∂ Ê ∂ u ˆ
r rC - Á kr ˜ - Á kr ˜ = qr
∂ t ∂r Ë ∂ r ¯ ∂z Ë ∂ z ¯
∂u
r yC - — · ( ky— u) = qy
∂t
3-220
Heat Distribution in Circular Cylindrical Rod: PDE Modeler App
To solve this problem in the PDE Modeler app, follow these steps:
1 Model the rod as a rectangle with corners in (-1.5,0), (1.5,0), (1.5,0.2), and (-1.5,0.2).
Here, the x-axis represents the z direction, and the y-axis represents the r direction.
pderect([-1.5,1.5,0,0.2])
2 Specify the boundary conditions. To do this, double-click the boundaries to open the
Boundary Condition dialog box. The PDE Modeler app requires boundary
conditions in a particular form. Thus, Neumann boundary conditions must be in the
•
For the left end, use the Neumann condition n · ( k— u ) = HF _ left = 5000 . Specify g
r
= 5000*y and q = 0.
• For the right end, use the Dirichlet condition u = T_right = 100. Specify h = 1
and r = 100.
• For the outer boundary, use the Neumann condition
3-221
3 Solving PDEs
3 Specify the coefficients by selecting PDE > PDE Specification or click the PDE
button on the toolbar. Heat equation is a parabolic equation, so select the Parabolic
type of PDE. Because both sides of the equation are multiplied by r = y, multiply the
coefficients by y and enter the following values: c = 40*y, a = 0, f = 20000*y,
and d = 7800*500*y.
4 Initialize the mesh by selecting Mesh > Initialize Mesh.
5 Set the initial value to 0, the solution time to 20000 seconds, and compute the
solution every 100 seconds. To do this, select Solve > Parameters. In the Solve
Parameters dialog box, set time to 0:100:20000, and u(t0) to 0.
6 Solve the equation by selecting Solve > Solve PDE or clicking the = button on the
toolbar.
7 Plot the solution, using the color and contour plot. To do this, select Plot >
Parameters and choose the color and contour plots in the resulting dialog box.
3-222
Heat Distribution in Circular Cylindrical Rod: PDE Modeler App
You can explore the solution by varying the parameters of the model and plotting the
results. For example, you can:
• Show the solution when u does not depend on time, that is, the steady state solution.
To do this, open the PDE Specification dialog box, and change the PDE type to
Elliptic. The resulting steady state solution is in close agreement with the transient
solution at 20000 seconds.
3-223
3 Solving PDEs
• Show the steady state solution without cooling on the outer boundary: the heat
transfer coefficient is zero. To do this, set the Neumann boundary condition at the
outer boundary (the top side of the rectangle) to g = 0 and q = 0. The resulting plot
shows that the temperature rises to more than 2500 on the left end of the rod.
3-224
Wave Equation on Square Domain
Problem Definition
To express this in toolbox form, note that the solvepde function solves problems of the
form
c = 1;
a = 0;
f = 0;
m = 1;
Geometry
Solve the problem on a square domain. The squareg function describes this geometry.
Create a model object and include the geometry. Plot the geometry and view the edge
labels.
numberOfPDE = 1;
model = createpde(numberOfPDE);
geometryFromEdges(model,@squareg);
pdegplot(model,'EdgeLabels','on');
ylim([-1.1 1.1]);
axis equal
title 'Geometry With Edge Labels Displayed';
xlabel x
ylabel y
3-225
3 Solving PDEs
Boundary Conditions
Set zero Dirichlet boundary conditions on the left (edge 4) and right (edge 2) and zero
Neumann boundary conditions on the top (edge 1) and bottom (edge 3).
applyBoundaryCondition(model,'dirichlet','Edge',[2,4],'u',0);
applyBoundaryCondition(model,'neumann','Edge',([1 3]),'g',0);
Generate Mesh
3-226
Wave Equation on Square Domain
generateMesh(model);
figure
pdemesh(model);
ylim([-1.1 1.1]);
axis equal
xlabel x
ylabel y
•
.
3-227
3 Solving PDEs
•
.
This choice avoids putting energy into the higher vibration modes and permits a
reasonable time step size.
u0 = @(location) atan(cos(pi/2*location.x));
ut0 = @(location) 3*sin(pi*location.x).*exp(sin(pi/2*location.y));
setInitialConditions(model,u0,ut0);
Plot the solution for all times. Keep a fixed vertical scale by first calculating the maximum
and minimum values of u over all times, and scale all plots to use those -axis limits.
figure
umax = max(max(u));
umin = min(min(u));
for i = 1:n
pdeplot(model,'XYData',u(:,i),'ZData',u(:,i),'ZStyle','continuous',...
'Mesh','off','XYGrid','on','ColorBar','off');
axis([-1 1 -1 1 umin umax]);
caxis([umin umax]);
xlabel x
3-228
Wave Equation on Square Domain
ylabel y
zlabel u
M(i) = getframe;
end
3-229
3 Solving PDEs
∂2 u
- Du = 0
∂ t2
To solve this problem in the PDE Modeler app, follow these steps:
button. Then click one of the corners using the right mouse button and drag to
draw a square. The right mouse button constrains the shape you draw to be a square
rather than a rectangle.
pderect([-1 1 -1 1])
5 Check that the application mode is set to Generic Scalar.
6 Specify the boundary conditions. To do this, switch to boundary mode by clicking the
button or selecting Boundary > Boundary Mode. Select the left and right
boundaries. Then select Boundary > Specify Boundary Conditions and specify the
Dirichlet boundary condition u = 0. This boundary condition is the default one (h =
1, r = 0), so you do not need to change it.
For the bottom and top boundaries, set the Neumann boundary condition ∂u/∂n = 0.
To do this, set g = 0, q = 0.
3-230
Wave Equation on a Square Domain: PDE Modeler App
The inverse tangent function and exponential function introduce more modes into the
solution.
3-231
3 Solving PDEs
11 Solve the PDE by selecting Solve > Solve PDE or clicking the = button on the
toolbar. The app solves the heat equation at times from 0 to 5 seconds and displays
the result at the end of the time span.
12 Visualize the solution as a 3-D static and animated plots. To do this:
3-232
Eigenvalues and Eigenmodes of the L-Shaped Membrane
Create a model and include this geometry. The geometry of the L-shaped membrane is
described in the file lshapeg.
model = createpde();
geometryFromEdges(model,@lshapeg);
Specify the coefficients for the problem: d = 1 and c = 1. All other coefficients are equal
to zero.
specifyCoefficients(model,'m',0,'d',1,'c',1,'a',0,'f',0);
Set the interval [0 100] as the region for the eigenvalues in the solution.
r = [0 100];
3-233
3 Solving PDEs
length(results.Eigenvalues)
ans = 19
3-234
Eigenvalues and Eigenmodes of the L-Shaped Membrane
Plot the first eigenmode and compare it to the MATLAB's membrane function. Multiply
the PDE solution by -1, so that the plots look similar instead of being inverted.
u = results.Eigenvectors;
pdeplot(model,'XYData',-u(:,1),'ZData',-u(:,1));
figure
membrane(1,20,9,9)
3-235
3 Solving PDEs
Eigenvectors can be multiplied by any scalar and remain eigenvectors. This explains the
difference in scale that you see.
membrane can produce the first 12 eigenfunctions for the L-shaped membrane. Compare
the 12th eigenmodes.
figure
pdeplot(model,'XYData',u(:,12),'ZData',u(:,12));
3-236
Eigenvalues and Eigenmodes of the L-Shaped Membrane
figure
membrane(12,20,9,9)
3-237
3 Solving PDEs
3-238
Eigenvalues and Eigenmodes of the L-Shaped Membrane: PDE Modeler App
–Δu = λu
on the geometry of the L-shaped membrane. The boundary condition is the Dirichlet
condition u = 0. This example uses the PDE Modeler app. For a programmatic workflow,
see “Eigenvalues and Eigenmodes of the L-Shaped Membrane” on page 3-233.
To solve this problem in the PDE Modeler app, follow these steps:
1 Draw a polygon with the corners (0,0), (–1,0), (–1,–1), (1,–1), (1,1), and (0,1) by using
the pdepoly function.
pdepoly([0,-1,-1,1,1,0],[0,0,-1,-1,1,1])
2 Check that the application mode is set to Generic Scalar.
3 Use the default Dirichlet boundary condition u = 0 for all boundaries. To verify it,
switch to boundary mode by selecting Boundary > Boundary Mode. Use Edit >
Select all to select all boundaries. Select Boundary > Specify Boundary
Conditions and verify that the boundary condition is the Dirichlet condition with h =
1, r = 0.
4 Specify the coefficients by selecting PDE > PDE Specification or clicking the PDE
button on the toolbar. This is an eigenvalue problem, so select the Eigenmodes type
of PDE. The general eigenvalue PDE is described by -— ◊ ( c—u ) + au = l du . Thus, for
this problem, use the default coefficients c = 1, a = 0, and d = 1.
5 Specify the maximum edge size for the mesh by selecting Mesh > Parameters. Set
the maximum edge size value to 0.05.
6 Initialize the mesh by selecting Mesh > Initialize Mesh.
7 Specify the eigenvalue range by selecting Solve > Parameters. In the resulting
dialog box, use the default eigenvalue range [0 100].
8 Solve the PDE by selecting Solve > Solve PDE or clicking the = button on the
toolbar. By default, the app plots the first eigenfunction.
3-239
3 Solving PDEs
9 Plot other eigenfunctions by selecting Plot > Parameters and then selecting the
corresponding eigenvalue from the drop-down list at the bottom of the dialog box.
For example, plot the fifth eigenfunction in the specified range.
3-240
Eigenvalues and Eigenmodes of the L-Shaped Membrane: PDE Modeler App
3-241
3 Solving PDEs
pdepoly([-1, 1, 1, 0, 0, -1],...
[-1, -1, 1, 1, 0, 0],'P1');
pdecirc(-a,a,a,'C1');
pderect([-a 0 a 0],'SQ1');
The extra circle and rectangle that are added using pdecirc and pderect to create the
rounded corner are affected by the added input argument a through a couple of extra
lines of MATLAB code. This is possible since Partial Differential Equation Toolbox
software is a part of the open MATLAB environment.
With lshapec you can create L-shaped rounded geometries with different degrees of
roundness. If you use lshapec without an input argument, a default radius of 0.5 is used.
Otherwise, use lshapec(a), where a is the radius of the circle.
Experimenting using different values for the radius a shows you that the eigenvalues and
the frequencies of the corresponding eigenmodes decrease as the radius increases, and
the shape of the L-shaped membrane becomes more rounded. In the following figure, the
first eigenmode of an L-shaped membrane with a rounded corner is plotted.
3-242
L-Shaped Membrane with a Rounded Corner
3-243
3 Solving PDEs
The eigenvalue PDE problem is . This example finds the eigenvalues smaller
than 10 and the corresponding eigenmodes.
Create a model. Import and plot the geometry. The geometry description file for this
problem is called squareg.m.
model = createpde();
geometryFromEdges(model,@squareg);
pdegplot(model,'EdgeLabels','on')
ylim([-1.5,1.5])
axis equal
3-244
Eigenvalues and Eigenmodes of a Square
applyBoundaryCondition(model,'dirichlet','Edge',4,'u',0);
Specify the zero Neumann boundary condition for the upper and lower boundary.
applyBoundaryCondition(model,'neumann','Edge',[1,3],'g',0,'q',0);
applyBoundaryCondition(model,'neumann','Edge',2,'g',0,'q',-3/4);
3-245
3 Solving PDEs
The eigenvalue PDE coefficients for this problem are c = 1, a = 0, and d = 1. You can
enter the eigenvalue range r as the vector [-Inf 10].
specifyCoefficients(model,'m',0,'d',1,'c',1,'a',0,'f',0);
r = [-Inf,10];
3-246
Eigenvalues and Eigenmodes of a Square
l = results.Eigenvalues
l = 5×1
-0.4146
2.0528
4.8019
7.2693
9.4550
u = results.Eigenvectors;
pdeplot(model,'XYData',u(:,1));
3-247
3 Solving PDEs
pdeplot(model,'XYData',u(:,length(l)));
3-248
Eigenvalues and Eigenmodes of a Square
The functions f and g are eigenfunctions in the x and y directions, respectively. In the x
direction, the first eigenmode is a slowly increasing exponential function. The higher
modes include sinusoids. In the y direction, the first eigenmode is a straight line
(constant), the second is half a cosine, the third is a full cosine, the fourth is one and a
half full cosines, etc. These eigenmodes in the y direction are associated with the
eigenvalues
3-249
3 Solving PDEs
Look at the difference between the first and the second eigenvalue compared to :
ans = 1.6751e-07
Likewise, the fifth eigenmode is made up of the first eigenmode in the x direction and the
third eigenmode in the y direction. As expected, l(5)-l(1) is approximately equal to
:
ans = 6.2135e-06
You can explore higher modes by increasing the search range to include eigenvalues
greater than 10.
3-250
Eigenvalues and Eigenmodes of a Square: PDE Modeler App
The eigenvalue PDE problem is - Du = l u . Find the eigenvalues smaller than 10 and the
corresponding eigenmodes.
To solve this problem in the PDE Modeler app, follow these steps:
1 Draw a square with the corners (-1,-1), (-1,1), (1,1), and (1,-1) by using the pderect
function.
pderect([-1 1 -1 1])
2 Check that the application mode is set to Generic Scalar.
3 Specify the boundary conditions. To do this, switch to the boundary mode by
selecting Boundary > Boundary Mode. Double-click the boundary to specify the
boundary condition.
• Specify the Dirichlet condition u = 0 for the left boundary. To do this, specify h =
1, r = 0.
• ∂u
=0
Specify the Neumann condition ∂ n for the upper and lower boundary. To do
this, specify g = 0, q = 0.
• ∂u 3
- u=0
Specify the generalized Neumann condition ∂ n 4 for the right boundary. To
do this, specify g = 0, q = -3/4.
4 Specify the coefficients by selecting PDE > PDE Specification or clicking the PDE
button on the toolbar. This is a eigenvalue problem, so select the Eigenmodes type
of PDE. The general eigenvalue PDE is described by -— ◊ ( c—u ) + au = l du . Thus, for
this problem, the coefficients are c = 1, a = 0, and d = 1.
5 Specify the maximum edge size for the mesh by selecting Mesh > Parameters. Set
the maximum edge size value to 0.05.
3-251
3 Solving PDEs
3-252
Eigenvalues and Eigenmodes of a Square: PDE Modeler App
9 Plot other eigenfunctions by selecting Plot > Parameters and then selecting the
corresponding eigenvalue from the drop-down list at the bottom of the dialog box.
For example, plot the last eigenfunction in the specified range.
10 Export the eigenfunctions and eigenvalues to the MATLAB workspace by using the
Solve > Export Solution.
3-253
3 Solving PDEs
The calculation of vibration modes requires the solution of the eigenvalue partial
differential equation (PDE). In this example the solution of the eigenvalue problem is
performed using both the PDE Toolbox's solvepdeeig solver and the core MATLAB's
eigs eigensolver.
The main objective of this example is to show how eigs can be used with PDE Toolbox.
Generally, the eigenvalues calculated by solvepdeeig and eigs are practically identical.
However, sometimes, it is simply more convenient to use eigs than solvepdeeig. One
example of this is when it is desired to calculate a specified number of eigenvalues in the
vicinity of a user-specified target value. solvepdeeig requires that a lower and upper
bound surrounding this target value be specified. eigs requires only that the target
eigenvalue and the desired number of eigenvalues be specified.
numberOfPDE = 1;
model = createpde(numberOfPDE);
Include Geometry
radius = 2;
g = decsg([1 0 0 radius]','C1',('C1')');
geometryFromEdges(model,g);
Plot the geometry and display the edge labels for use in the boundary condition definition.
figure;
pdegplot(model,'EdgeLabels','on');
axis equal
title 'Geometry With Edge Labels Displayed';
3-254
Vibration of Circular Membrane
Generate Mesh
generateMesh(model,'Hmax',0.2);
3-255
3 Solving PDEs
Use assembleFEMatrices to calculate the global finite element mass and stiffness
matrices with boundary conditions imposed using nullspace approach.
FEMatrices = assembleFEMatrices(model,'nullspace');
K = FEMatrices.Kc;
B = FEMatrices.B;
M = FEMatrices.M;
sigma = 1e2;
numberEigenvalues = 5;
[eigenvectorsEigs,eigenvaluesEigs] = eigs(K,M,numberEigenvalues,sigma);
Find the largest eigenvalue and its index in the eigenvalues vector.
[maxEigenvaluesEigs, maxIndex] = max(eigenvaluesEigs);
Transform the eigenvectors with constrained equations removed to the full eigenvector
including constrained equations.
eigenvectorsEigs = B*eigenvectorsEigs;
Set the range for solvepdeeig to be slightly larger than the range from eigs.
r = [min(eigenvaluesEigs)*.99 max(eigenvaluesEigs)*1.01];
result = solvepdeeig(model,r);
eigenvectorsPde = result.Eigenvectors;
eigenvaluesPde = result.Eigenvalues;
3-256
Vibration of Circular Membrane
As can be seen, both functions calculate the same eigenvalues. For any eigenvalue, the
eigenvector can be multiplied by an arbitrary scalar. eigs and solvepdeeig choose a
different arbitrary scalar for normalizing their eigenvectors as shown in the figure below.
h = figure;
h.Position = [1 1 2 1].*h.Position;
subplot(1,2,1);
axis equal
pdeplot(model,'XYData', eigenvectorsEigs(:,maxIndex),'Contour','on');
title(sprintf('eigs eigenvector, eigenvalue: %12.4e', eigenvaluesEigs(maxIndex)));
xlabel('x');
ylabel('y');
subplot(1,2,2);
axis equal
pdeplot(model,'XYData',eigenvectorsPde(:,end),'Contour','on');
title(sprintf('solvepdeeig eigenvector, eigenvalue: %12.4e',eigenvaluesPde(end)));
xlabel('x');
ylabel('y');
3-257
3 Solving PDEs
• 3-D geometry
• Geometrical shapes other than straight lines, circular arcs, and elliptical arcs
• Nonstandard boundary conditions
• Complicated PDE or boundary condition coefficients
• More than two dependent variables in the system case
• Nonlocal solution constraints
• Special solution data processing and presentation itemize
The PDE Modeler app can still be a valuable aid in some of the situations presented
previously, if part of the modeling is done using the PDE Modeler app and then made
available for command-line use through the extensive data export facilities of the PDE
Modeler app.
The rectangles are functions, and ellipses are data represented by matrices or files.
Arrows indicate data necessary for the functions.
3-258
Solve PDEs Programmatically
As there is a definite direction in this diagram, you can cut into it by presenting the
needed data sets, and then continue downward. In the following sections, we give
pointers to descriptions of the precise formats of the various data structures and files.
3-259
3 Solving PDEs
Geometry
Description
matrix
decsg
Decomposed
Geometry
Geometry
M - fi l e
matrix
initmesh
Boundary
Boundary Mesh Coefficient Coefficient
Condition refinemesh
M - fi l e data matrix M - fi l e
matrix
assempde
Solution
data
pdeplot
3-260
Solve PDEs Programmatically
Decomposed Geometry
Boundary Conditions
These are specified by either a Boundary Condition matrix, or a Boundary file. Boundary
conditions are given as functions on boundary segments. A Boundary Condition matrix
can be exported from the PDE Modeler app by selecting the Export Decomposed
Geometry, Boundary Cond's option from the Boundary menu. For a description of the
data structures of the Boundary Condition matrix and Boundary file, see the reference
pages for assemb and see “Boundary Conditions”.
Equation Coefficients
The PDE is specified by either a Coefficient matrix or a Coefficient file for each of the PDE
coefficients c, a, f, and d. The coefficients are functions on the subdomains. Coefficients
can be exported from the PDE Modeler app by selecting the Export PDE Coefficient
option from the PDE menu. For the details on the equation coefficient data structures,
see the reference page for assempde, and see “PDE Coefficients”.
Mesh
A triangular mesh is described by the mesh data which consists of a Point matrix, an Edge
matrix, and a Triangle matrix. In the mesh, minimal regions are triangulated into
3-261
3 Solving PDEs
subdomains, and border segments and boundary segments are broken up into edges.
Mesh data is created from a decomposed geometry by the function initmesh and can be
altered by the functions refinemesh and jigglemesh. The Export Mesh option from
the Mesh menu provides another way of creating mesh data. The adaptmesh function
creates mesh data as part of the solution process. The mesh may be plotted with the
pdemesh function. For details on the mesh data representation, see the reference page
for initmesh and see “Mesh Data” on page 2-241.
Solution
The solution of a PDE problem is represented by the solution vector. A solution gives the
value at each mesh point of each dependent variable, perhaps at several points in time, or
connected with different eigenvalues. Solution vectors are produced from the mesh, the
boundary conditions, and the equation coefficients by assempde, pdenonlin,
adaptmesh, parabolic, hyperbolic, and pdeeig. The Export Solution option from
the Solve menu exports solutions to the workspace. Since the meaning of a solution
vector is dependent on its corresponding mesh data, they are always used together when
a solution is presented. For details on solution vectors, see the reference page for
assempde.
Given a solution/mesh pair, a variety of tools is provided for the visualization and
processing of the data. pdeintrp and pdeprtni can be used to interpolate between
functions defined at triangle nodes and functions defined at triangle midpoints. tri2grid
interpolates a functions from a triangular mesh to a rectangular grid. Use
pdeInterpolant and evaluate for more general interpolation. pdegrad and
pdecgrad compute gradients of the solution. pdeplot has a large number of options for
plotting the solution. pdecont and pdesurf are convenient shorthands for pdeplot.
Working with the system matrices and vectors produced by assema and assemb can
sometimes be valuable. When solving the same equation for different loads or boundary
conditions, it pays to assemble the stiffness matrix only once. Point loads on a particular
node can be implemented by adding the load to the corresponding row in the right side
vector. A nonlocal constraint can be incorporated into the H and R matrices.
3-262
Solve PDEs Programmatically
The routines for adaptive mesh generation and solution are powerful but can lead to
dense meshes and thus long computation times. Setting the Ngen parameter to one limits
you to a single refinement step. This step can then be repeated to show the progress of
the refinement. The Maxt parameter helps you stop before the adaptive solver generates
too many triangles. An example of a handwritten triangle selection function is
circlepick, used in Poisson's Equation with Point Source and Adaptive Mesh
Refinement. Remember that you always need a decomposed geometry with adaptmesh.
Deformed meshes are easily plotted by adding offsets to the Point matrix p. Assuming two
variables stored in the solution vector u:
np = size(p,2);
pdemesh(p+scale*[u(1:np) u(np+1:np+np)]',e,t)
u1 = u(:,mode)*cos(sqrt(l(mode))*tlist); % hyperbolic
u1 = u(:,mode)*exp(-l(mode)*tlist); % parabolic
in parabolic problems. This makes nice animations, perhaps together with deformed mesh
plots.
3-263
3 Solving PDEs
–Δu = f in Ω
For the fast solution algorithms to work, the mesh on the rectangle must be a regular
mesh. In this context it means that the first side of the rectangle is divided into N1
segments of length h1, the second into N2 segments of length h2, and (N1 + 1) by (N2 + 1)
points are introduced on the regular grid thus defined. The triangles are all congruent
with sides h1, h2 and a right angle in between.
The Dirichlet boundary conditions are eliminated in the usual way, and the resulting
problem for the interior nodes is Kv = F. If the interior nodes are numbered from left to
right, and then from bottom to top, the K matrix is block tridiagonal. The N2 – 1 diagonal
blocks, here called T, are themselves tridiagonal (N1 – 1) by (N1 – 1) matrices, with 2(h1/h2
+ h2/h1) on the diagonal and –h2/h1 on the subdiagonals. The subdiagonal blocks, here
called I, are –h1/h2 times the unit N1 – 1 matrix.
The key to the solution of the problem Kv = F is that the problem Tw = f is possible to
solve using the discrete sine transform. Let S be the (N1 – 1) by (N1 – 1) matrix with Sij=
sin(πij/N1). Then S–1TS = Λ, where Λ is a diagonal matrix with diagonal entries 2(h1/h2 +
h2/h1) – 2h2/h1 cos(πi/N1). w = SΛ–1S–1 f, but multiplying with S is nothing more than
taking the discrete sine transform, and multiplying with S–1 is the same as taking the
inverse discrete sine transform. The discrete sine transform can be efficiently calculated
using the fast Fourier transform on a sequence of length 2N1.
Solving Tw = f using the discrete sine transform would not be an advantage in itself, since
the system is tridiagonal and should be solved as such. However, for the full system
Ky = F, a transformation of the blocks in K turns it into N1 – 1 decoupled tridiagonal
systems of size N2 – 1. Thus, a solution algorithm would look like
3-264
Solve Poisson's Equation on a Grid
3 Reverse the reordering, and perform N2 – 1 discrete sine transforms on the blocks of
length N1 – 1.
When using a fast solver such as this one, time and memory are also saved since the
matrix K in fact never has to be assembled. A drawback is that since the mesh has to be
regular, it is impossible to do adaptive mesh refinement.
The fast elliptic solver for Poisson's equation is implemented in poisolv. The discrete
sine transform and the inverse discrete sine transform are computed by dst and idst,
respectively.
3-265
3 Solving PDEs
Create the PDE model, 2-D geometry, and mesh. Specify boundary conditions and
coefficients. Solve the PDE problem.
model = createpde;
geometryFromEdges(model,@lshapeg);
applyBoundaryCondition(model,'dirichlet','edge',1:model.Geometry.NumEdges,'u',0);
c = 1;
a = 0;
f = 1;
specifyCoefficients(model,'m',0,'d',0,'c',c,'a',a,'f',f);
generateMesh(model);
results = solvepde(model);
u = results.NodalSolution;
pdeplot(model,'XYData',u,'ZData',u,'Mesh','on')
xlabel('x')
ylabel('y')
3-266
Plot 2-D Solutions and Their Gradients
To get a smoother solution surface, specify the maximum size of the mesh triangles by
using the Hmax argument. Then solve the PDE problem using this new mesh, and plot the
solution again.
generateMesh(model,'Hmax',0.05);
results = solvepde(model);
u = results.NodalSolution;
pdeplot(model,'XYData',u,'ZData',u,'Mesh','on')
xlabel('x')
ylabel('y')
3-267
3 Solving PDEs
Create the PDE model, 2-D geometry, and mesh. Specify boundary conditions and
coefficients. Solve the PDE problem.
3-268
Plot 2-D Solutions and Their Gradients
model = createpde;
geometryFromEdges(model,@lshapeg);
applyBoundaryCondition(model,'dirichlet','edge',1:model.Geometry.NumEdges,'u',0);
c = 1;
a = 0;
f = 1;
specifyCoefficients(model,'m',0,'d',0,'c',c,'a',a,'f',f);
generateMesh(model,'Hmax',0.05);
results = solvepde(model);
Interpolate the solution and its gradients to a dense grid from -1 to 1 in each direction.
v = linspace(-1,1,101);
[X,Y] = meshgrid(v);
querypoints = [X(:),Y(:)]';
uintrp = interpolateSolution(results,querypoints);
uintrp = reshape(uintrp,size(X));
mesh(X,Y,uintrp)
xlabel('x')
ylabel('y')
3-269
3 Solving PDEs
Interpolate gradients of the solution to the grid from -1 to 1 in each direction. Plot the
result using quiver.
[gradx,grady] = evaluateGradient(results,querypoints);
figure
quiver(X(:),Y(:),gradx,grady)
xlabel('x')
ylabel('y')
3-270
Plot 2-D Solutions and Their Gradients
Zoom in to see more details. For example, restrict the range to [-0.2,0.2] in each
direction.
3-271
3 Solving PDEs
figure
h1 = meshc(X,Y,uintrp);
set(h1,'FaceColor','g','EdgeColor','b')
xlabel('x')
ylabel('y')
alpha(0.5)
hold on
Z = -0.05*ones(size(X));
gradz = zeros(size(gradx));
h2 = quiver3(X(:),Y(:),Z(:),gradx,grady,gradz);
3-272
Plot 2-D Solutions and Their Gradients
set(h2,'Color','r')
axis([-0.2,0.2,-0.2,0.2])
figure
mesh(X,Y,uintrp)
xlabel('x')
ylabel('y')
alpha(0.25)
hold on
z = linspace(0,0.15,101);
Z = meshgrid(z);
3-273
3 Solving PDEs
surf(X,X,Z')
figure
xq = v;
yq = v;
uintrp = interpolateSolution(results,xq,yq);
plot3(xq,yq,uintrp)
grid on
3-274
Plot 2-D Solutions and Their Gradients
xlabel('x')
ylabel('y')
Interpolate gradients of the solution along the same line and add them to the solution
plot.
[gradx,grady] = evaluateGradient(results,xq,yq);
gradx = reshape(gradx,size(xq));
grady = reshape(grady,size(yq));
hold on
quiver(xq,yq,gradx,grady)
view([-20 -45 75])
3-275
3 Solving PDEs
3-276
Plot 3-D Solutions and Their Gradients
• Surface plot — Sometimes you want to examine the solution on the surface of the
geometry. For example, in a stress or strain calculation, the most interesting data can
appear on the geometry surface. For an example, see “Surface Plot” on page 3-277.
For a colored surface plot of a scalar solution, set the pdeplot3D colormapdata to
the solution u:
pdeplot3D(model,'ColorMapData',u)
• Plot on a 2-D slice — To examine the solution on the interior of the geometry, define a
2-D grid that intersects the geometry, and interpolate the solution onto the grid. For
examples, see “2-D Slices Through 3-D Geometry” on page 3-280 and “Contour Slices
Through 3-D Solution” on page 3-285. While these two examples show planar grid
slices, you can also slice on a curved grid.
• Streamline or quiver plots — Plot the gradient of the solution as streamlines or a
quiver. See “Plots of Gradients and Streamlines” on page 3-292.
• You can use any MATLAB plotting command to create 3-D plots. See “Techniques for
Visualizing Scalar Volume Data” (MATLAB) and “Visualizing Vector Volume Data”
(MATLAB).
Surface Plot
This example shows how to obtain a surface plot of a solution with 3-D geometry and N >
1.
Import a tetrahedral geometry to a model with N = 2 equations and view its faces.
model = createpde(2);
importGeometry(model,'Tetrahedron.stl');
pdegplot(model,'FaceLabels','on','FaceAlpha',0.5)
view(-40,24)
3-277
3 Solving PDEs
Create coefficients for the problem, where f = [1;10] and c is a symmetric matrix in
6N form.
f = [1;10];
a = 0;
c = [2;0;4;1;3;8;1;0;2;1;2;4];
specifyCoefficients(model,'m',0,'d',0,'c',c,'a',a,'f',f);
3-278
Plot 3-D Solutions and Their Gradients
results = solvepde(model);
u = results.NodalSolution;
pdeplot3D(model,'ColorMapData',u(:,1))
view(-175,4)
title('u(1)')
figure
pdeplot3D(model,'ColorMapData',u(:,2))
3-279
3 Solving PDEs
view(-175,4)
title('u(2)')
The problem is
3-280
Plot 3-D Solutions and Their Gradients
Define a function for the nonlinear f coefficient in the syntax as given in “f Coefficient for
specifyCoefficients” on page 2-107.
bcMatrix = 1+10*region.z.^2+region.y;
model = createpde;
g = importGeometry(model,'Plate10x10x1.stl');
pdegplot(g,'FaceLabels','on','FaceAlpha',0.5)
3-281
3 Solving PDEs
applyBoundaryCondition(model,'dirichlet','face',1:6,'u',0);
3-282
Plot 3-D Solutions and Their Gradients
Create a grid of (x,y,z) points, where x = 5, y ranges from 0 through 10, and z ranges
from 0 through 1. Interpolate the solution to these grid points and all times.
yy = 0:0.5:10;
zz = 0:0.25:1;
[YY,ZZ] = meshgrid(yy,zz);
XX = 5*ones(size(YY));
uintrp = interpolateSolution(results,XX,YY,ZZ,1:length(tlist));
The solution matrix uintrp has 11 columns, one for each time in tlist. Take the
interpolated solution for the second column, which corresponds to time 0.02.
usol = uintrp(:,2);
The elements of usol come from interpolating the solution to the XX, YY, and ZZ
matrices, which are each 5-by-21, corresponding to z-by-y variables. Reshape usol to
the same 5-by-21 size, and make a surface plot of the solution. Also make surface plots
corresponding to times 0.06, 0.10, and 0.20.
figure
usol = reshape(usol,size(XX));
subplot(2,2,1)
surf(usol)
title('t = 0.02')
zlim([0,1.5])
xlim([1,21])
ylim([1,5])
usol = uintrp(:,4);
usol = reshape(usol,size(XX));
subplot(2,2,2)
surf(usol)
title('t = 0.06')
zlim([0,1.5])
3-283
3 Solving PDEs
xlim([1,21])
ylim([1,5])
usol = uintrp(:,6);
usol = reshape(usol,size(XX));
subplot(2,2,3)
surf(usol)
title('t = 0.10')
zlim([0,1.5])
xlim([1,21])
ylim([1,5])
usol = uintrp(:,11);
usol = reshape(usol,size(XX));
subplot(2,2,4)
surf(usol)
title('t = 0.20')
zlim([0,1.5])
xlim([1,21])
ylim([1,5])
3-284
Plot 3-D Solutions and Their Gradients
The problem is to solve Poisson's equation with zero Dirichlet boundary conditions for a
complicated geometry. Poisson's equation is
3-285
3 Solving PDEs
c = 1;
a = 0;
f = 10;
The first step in solving any 3-D PDE problem is to create a PDE Model. This is a
container that holds the number of equations, geometry, mesh, and boundary conditions
for your PDE. Create the model, then import the 'ForearmLink.stl' file and view the
geometry.
N = 1;
model = createpde(N);
importGeometry(model,'ForearmLink.stl');
pdegplot(model,'FaceAlpha',0.5)
view(-42,24)
3-286
Plot 3-D Solutions and Their Gradients
specifyCoefficients(model,'m',0,'d',0,'c',c,'a',a,'f',f);
applyBoundaryCondition(model,'dirichlet','Face',1:model.Geometry.NumFaces,'u',0);
generateMesh(model);
result = solvepde(model);
3-287
3 Solving PDEs
Because the boundary conditions are on all faces, the solution is nonzero only in
the interior. To examine the interior, take a rectangular grid that covers the geometry
with a spacing of one unit in each coordinate direction.
[X,Y,Z] = meshgrid(0:135,0:35,0:61);
For plotting and analysis, create a PDEResults object from the solution. Interpolate the
result at every grid point.
V = interpolateSolution(result,X,Y,Z);
V = reshape(V,size(X));
figure
colormap jet
contourslice(X,Y,Z,V,[],[],0:5:60)
xlabel('x')
ylabel('y')
zlabel('z')
colorbar
view(-11,14)
axis equal
3-288
Plot 3-D Solutions and Their Gradients
figure
colormap jet
contourslice(X,Y,Z,V,[],1:6:31,[])
xlabel('x')
ylabel('y')
zlabel('z')
colorbar
view(-62,34)
axis equal
3-289
3 Solving PDEs
For large problems you can run out of memory when creating a fine 3-D grid.
Furthermore, it can be time-consuming to evaluate the solution on a full grid. To save
memory and time, evaluate only at the points you plot. You can also use this technique to
interpolate to tilted grids, or to other surfaces.
3-290
Plot 3-D Solutions and Their Gradients
V = interpolateSolution(result,X,Y,Z);
V = reshape(V,size(X));
figure
subplot(2,1,1)
contour(X,Y,V);
axis equal
title('Contour Plot on Tilted Plane')
xlabel('x')
ylabel('y')
colorbar
subplot(2,1,2)
surf(X,Y,V,'LineStyle','none');
axis equal
view(0,90)
title('Colored Plot on Tilted Plane')
xlabel('x')
ylabel('y')
colorbar
3-291
3 Solving PDEs
The problem is the calculation of the mean exit time of a Brownian particle from a region
that contains absorbing (escape) boundaries and reflecting boundaries. For more
information, see Narrow escape problem. The PDE is Poisson's equation with constant
coefficients. The geometry is a simple rectangular solid. The solution represents
the mean time it takes a particle starting at position to exit the region.
3-292
Plot 3-D Solutions and Their Gradients
model = createpde;
importGeometry(model,'Block.stl');
pdegplot(model,'FaceLabels','on','FaceAlpha',0.5)
view(-42,24)
Set faces 1, 2, and 5 to be the places where the particle can escape. On these faces, the
solution . Keep the default reflecting boundary conditions on faces 3, 4, and 6.
applyBoundaryCondition(model,'dirichlet','Face',[1,2,5],'u',0);
3-293
3 Solving PDEs
The PDE is
c = 1;
a = 0;
f = 2;
specifyCoefficients(model,'m',0,'d',0,'c',c','a',a,'f',f);
generateMesh(model);
results = solvepde(model);
[X,Y,Z] = meshgrid(0:135,0:35,0:61);
V = interpolateSolution(results,X,Y,Z);
V = reshape(V,size(X));
Create a contour slice plot for five fixed values of the y-coordinate.
figure
colormap jet
contourslice(X,Y,Z,V,[],0:4:16,[])
xlabel('x')
ylabel('y')
zlabel('z')
xlim([0,100])
3-294
Plot 3-D Solutions and Their Gradients
ylim([0,20])
zlim([0,50])
axis equal
view(-50,22)
colorbar
The particle has the largest mean exit time near the point .
Examine the solution in more detail by evaluating the gradient of the solution. Use a
rather coarse mesh so that you can see the details on the quiver and streamline plots.
3-295
3 Solving PDEs
[X,Y,Z] = meshgrid(1:9:99,1:3:20,1:6:50);
[gradx,grady,gradz] = evaluateGradient(results,X,Y,Z);
Plot the gradient vectors. First reshape the approximate gradients to the shape of the
mesh.
gradx = reshape(gradx,size(X));
grady = reshape(grady,size(Y));
gradz = reshape(gradz,size(Z));
figure
quiver3(X,Y,Z,gradx,grady,gradz)
axis equal
xlabel 'x'
ylabel 'y'
zlabel 'z'
title('Quiver Plot of Estimated Gradient of Solution')
3-296
Plot 3-D Solutions and Their Gradients
Plot the streamlines of the approximate gradient. Start the streamlines from a sparser set
of initial points.
hold on
[sx,sy,sz] = meshgrid([1,46],1:6:20,1:12:50);
streamline(X,Y,Z,gradx,grady,gradz,sx,sy,sz)
title('Quiver Plot with Streamlines')
hold off
3-297
3 Solving PDEs
The streamlines show that small values of y and z give larger mean exit times. They also
show that the x-coordinate has a significant effect on u when x is small, but when x is
greater than 40, the larger values have little effect on u. Similarly, when z is less than 20,
its values have little effect on u.
See Also
Related Examples
• “Solve Problems Using PDEModel Objects” on page 2-6
3-298
Dimensions of Solutions, Gradients, and Fluxes
Note solvepde does not compute components of flux of a PDE solution. To compute flux
of the solution at the mesh nodes, use evaluateCGradient.
The dimensions of the solution, its gradient, and flux of the solution depend on:
• For results returned by solvepde, this is the number of solution times (specified
as an input to solvepde).
• For results returned by solvepdeeig, this is the number of eigenvalues.
• For results returned by interpolateSolution, evaluateGradient, and
evaluateCGradient, this is the number of query times for time-dependent
problems or query modes for eigenvalue problems.
3-299
3 Solving PDEs
Node Indices
u2 u2 (t1 ) u2 (t2 ) L u2 (tNt )
M M M O M
uNp uNp (t1 ) uNp (t2 ) L uNp (tNt )
Time-Dependent or Eigenvalue
Stationary System System
s
ce
Node Iindices
11 1
di
2 N
uNp2(t2 ) uNp (t2 )N L uNp (t2 )
In
u12 (t1 ) u2 (t1 ) L u2 (t1 )
e
od
M
M M O M or
e
u1Np (t1 ) 2 N
m
Equation Number
3-300
Dimensions of Solutions, Gradients, and Fluxes
Suppose you also compute the solution, its gradient, or flux of the solution at other points
("query points") in the geometry by using interpolateSolution, evaluateGradient,
or evaluateCGradient, respectively. Here:
The tables show how to index into the solution returned by solvepde or solvepdeeig,
where:
The tables also show the dimensions of solutions, gradients, and flux of the solution at
nodal locations (returned by solvepde,solvepdeeig, and evaluateCGradient) and
the dimensions of interpolated solutions and gradients (returned by
interpolateSolution, evaluateGradient, and evaluateCGradient).
result.XGradients(iP)
result.YGradients(iP)
result.ZGradients(iP)
3-301
3 Solving PDEs
result.YGradients(iP,iN)
result.ZGradients(iP,iN)
result.XGradients(iP,iT)
result.YGradients(iP,iT)
result.ZGradients(iP,iT)
System, result.NodalSolution(iP,iN,i Np-by-N-by-Nt Nqp-by-Nq-by-Nqt
N>1 T)
result.XGradients(iP,iN,iT)
result.YGradients(iP,iN,iT)
result.ZGradients(iP,iN,iT)
3-302
See Also
See Also
EigenResults | StationaryResults | TimeDependentResults |
evaluateGradient | interpolateSolution | solvepde | solvepdeeig
3-303
4
You open the PDE Modeler app by entering pdeModeler at the command line. The main
components of the PDE Modeler app are the menus, the dialog boxes, and the toolbar.
Use Commands
• To open a blank PDE Modeler app window, type pdeModeler in the MATLAB
Command Window.
• To open the PDE Modeler app with a circle already drawn in it, type pdecirc in the
MATLAB Command Window.
• To open the PDE Modeler app with an ellipse already drawn in it, type pdeellip in
the MATLAB Command Window.
• To open the PDE Modeler app with a rectangle already drawn in it, type pderect in
the MATLAB Command Window.
• To open the PDE Modeler app with a polygon already drawn in it, type pdepoly in the
MATLAB Command Window.
You can use a sequence of drawing commands to create several basic shapes. For
example, the following commands create a circle, a rectangle, an ellipse, and a polygon:
pderect([-1.5,0,-1,0])
pdecirc(0,0,1)
pdepoly([-1,0,0,1,1,-1],[0,0,1,1,-1,-1])
pdeellip(0,0,1,0.3,pi)
4-2
2-D Geometry Creation in PDE Modeler App
Using the left mouse button, drag to create a rectangle. Using the right mouse
button (or Ctrl+click), drag to create a square.
Draw a rectangle/square starting at the center.
Using the left mouse button, drag to create a rectangle. Using the right mouse
button (or Ctrl+click), drag to create a square.
Draw an ellipse/circle starting at the perimeter.
Using the left mouse button, drag to create an ellipse. Using the right mouse
button (or Ctrl+click), drag to create a circle.
Draw an ellipse/circle starting at the center.
Using the left mouse button, drag to create an ellipse. Using the right mouse
button (or Ctrl+click), drag to create a circle.
Draw a polygon.
Using the left mouse button, drag to create polygon edges. You can close the
polygon by pressing the right mouse button. Clicking at the starting vertex also
closes the polygon.
Alternatively, you can create a basic shape by typing one of the following commands in
the MATLAB Command Window:
4-3
4 PDE Modeler App
These commands open the PDE Modeler app with the requested shape already drawn in
it. If the app is already open, these commands add the requested shape to the app
window without deleting any existing shapes.
You can use a sequence of drawing commands to create several basic shapes. For
example, these commands create a circle, a rectangle, an ellipse, and a polygon:
pderect([-1.5,0,-1,0])
pdecirc(0,0,1)
pdepoly([-1,0,0,1,1,-1],[0,0,1,1,-1,-1])
pdeellip(0,0,1,0.3,pi)
Rotate Shapes
To rotate a shape:
4-4
2-D Geometry Creation in PDE Modeler App
4 By default, the rotation center is the center-of-mass of the selected shapes. To use a
different rotation center, clear the Use center-of-mass option and enter a rotation
center (xc,yc) as a 1-by-2 vector, for example, [-0.4 0.3].
The app assigns a unique name to each shape. The names depend on the type of the
shape:
• For circles, the default names are C1, C2, C3, and so on.
• For ellipses, the default names are E1, E2, E3, and so on.
• For polygons, the default names are P1, P2, P3, and so on.
• For rectangles, the default names are R1, R2, R3, and so on.
• For squares, the default names are SQ1, SQ2, SQ3, and so on.
To change the name and parameters of a shape, first switch to the draw mode and then
double-click the shape. (Select Draw Mode from the Draw menu to switch to the draw
mode.) The resulting dialog box lets you change the name and parameters of the selected
shape. The name cannot contain spaces.
4-5
4 PDE Modeler App
Now you can combine basic shapes to create a complex geometry. To do this, use the Set
formula field located under the toolbar. Here you can specify a geometry by using the
names of basic shapes and the following operators:
For example, SQ1+C2 creates a geometry comprised of all points of the square SQ1
and all points of the circle C2.
• * is the set intersection operator.
For example, SQ1*C2 creates a geometry comprised of the points that belong to both
the square SQ1 and the circle C2.
• - is the set difference operator.
For example, SQ1-C2 creates a geometry comprised of the points of the square SQ1
that do not belong to the circle C2.
The operators + and * have the same precedence. The operator - has a higher
precedence. You can control the precedence by using parentheses. The resulting
geometrical model (called decomposed geometry) is the set of points for which the set
formula evaluates to true. By default, it is the union of all basic shapes.
4-6
2-D Geometry Creation in PDE Modeler App
To add axis grid, the snap-to-grid feature, and zoom, use the Options menu. To adjust the
grid spacing:
4-7
4 PDE Modeler App
• Specify the grid spacing for the x-axis and y-axis. For example, change the default
linear spacing -1.5:0.5:1.5 to -1:0.2:1.
You also can add extra ticks to customize the grid and aid in drawing. To separate
extra tick entries, use spaces, commas, semicolons, or brackets.
4-8
2-D Geometry Creation in PDE Modeler App
4-9
4 PDE Modeler App
4-10
2-D Geometry Creation in PDE Modeler App
4 Set the grid spacing for x-axis to -1.5:0.1:1.5 and for y-axis to -1:0.1:1. To do
this, select Options > Grid Spacing, clear the Auto checkboxes, and set the
corresponding ranges.
5 Draw a rectangle with the width 2, the height 1, and the top left corner at (–1,0.5). To
do this, first click the button. Then click the point (–1,0.5) and drag to draw a
rectangle.
To edit the parameters of the rectangle, double-click it. In the resulting dialog box,
specify the exact parameters.
6 Draw four circles with the radius 0.2 and the centers at (–0.8,–0.3), (–0.8,0.3), (0.8,–
0.3), and (0.8,0.3).To do this, first click the button. Then click the center of a
circle using the right mouse button and drag to draw a circle. The right mouse button
constrains the shape you draw to be a circle rather than an ellipse. If the circle is not
a perfect unit circle, then double-click it. In the resulting dialog box, specify the exact
center location and radius of the circle.
7 Add four squares with the side 0.2, one in each corner.
4-11
4 PDE Modeler App
8 Model the geometry with rounded corners by subtracting the small squares from the
rectangle, and then adding the circles. To do this, enter the following formula in the
Set formula field.
R1-(SQ1+SQ2+SQ3+SQ4)+C1+C2+C3+C4
9
Switch to the boundary mode by clicking the button or selecting Boundary >
Boundary Mode. The CSG model is now decomposed using the set formula, and you
get a rectangle with rounded corners.
4-12
2-D Geometry Creation in PDE Modeler App
10 Because of the intersection of the solid objects used in the initial CSG model, a
number of subdomain borders remain. They appear as gray lines. To remove these
borders, select Boundary > Remove All Subdomain Borders.
4-13
4 PDE Modeler App
4-14
Specify Boundary Conditions in the PDE Modeler App
Select Boundary Mode from the Boundary menu or click the button. Then
select a boundary or multiple boundaries for which you are specifying the conditions.
Note that no if you do not select any boundaries, then the specified conditions apply to all
boundaries.
Specify Boundary Conditions opens a dialog box where you can specify the boundary
condition for the selected boundary segments. There are three different condition types:
n · ( c— u) + qu = g.
r
4-15
4 PDE Modeler App
The following figure shows the dialog box for the generic system PDE (Options >
Application > Generic System).
For boundary condition entries you can use the following variables in a valid MATLAB
expression:
4-16
Specify Boundary Conditions in the PDE Modeler App
• The solution u.
• The time t.
Note If the boundary condition is a function of the solution u, you must use the nonlinear
solver. If the boundary condition is a function of the time t, you must choose a parabolic
or hyperbolic PDE.
4-17
4 PDE Modeler App
Select PDE Specification from the PDE menu or click the PDE button on the toolbar.
PDE Specification opens a dialog box where you enter the type of partial differential
equation and the applicable parameters. The dimension of the parameters depends on the
dimension of the PDE. The following description applies to scalar PDEs. If you select a
nongeneric application mode, application-specific PDEs and parameters replace the
standard PDE coefficients.
Each of the coefficients c, a, f, and d can be given as a valid MATLAB expression for
computing coefficient values at the triangle centers of mass. These variables are
available:
4-18
Specify Coefficients in the PDE Modeler App
For details, see “Coefficients for Scalar PDEs in PDE Modeler App” on page 2-79 and
“Systems in the PDE Modeler App” on page 2-101.
4-19
4 PDE Modeler App
4-20
Specify Mesh Parameters in the PDE Modeler App
• Maximum edge size: Largest triangle edge length (approximately). This parameter is
optional and must be a real positive number.
• Mesh growth rate: The rate at which the mesh size increases away from small parts
of the geometry. The value must be between 1 and 2. The default value is 1.3, i.e., the
mesh size increases by 30%.
• Mesher version: Choose the geometry triangulation algorithm. R2013a is faster, and
can mesh more geometries. preR2013a gives the same mesh as previous toolbox
versions.
• Jiggle mesh: Toggles automatic jiggling of the initial mesh on/off.
• Jiggle mode: Select a jiggle mode from a pop-up menu. Available modes are on,
optimize minimum, and optimize mean. on jiggles the mesh once. Using the jiggle
mode optimize minimum, the jiggling process is repeated until the minimum
triangle quality stops increasing or until the iteration limit is reached. The same
applies for the optimize mean option, but it tries to increase the mean triangle
quality.
• Number of jiggle iterations: Iteration limit for the optimize minimum and
optimize mean modes. Default: 20.
For the mesh refinement algorithm refinemesh, the Refinement method can be
regular or longest. The default refinement method is regular, which results in a
uniform mesh. The refinement method longest always refines the longest edge on each
triangle.
To initialize a triangular mesh, select Initialize Mesh from the Mesh menu or click the
button. To refine a mesh, select Refine Mesh from the Mesh menu or click the
button.
4-21
4 PDE Modeler App
the button.
4-22
Adjust Solve Parameters in the PDE Modeler App
Elliptic Equations
By default, no specific solve parameters are used, and the elliptic PDEs are solved using
the basic elliptic solver assempde. Optionally, the adaptive mesh generator and solver
adaptmesh can be used. For the adaptive mode, the following parameters are available:
4-23
4 PDE Modeler App
• Worst triangles. This method picks all triangles that are worse than a fraction of
the value of the worst triangle (default: 0.5).
• Relative tolerance. This method picks triangles using a relative tolerance
criterion (default: 1E-3).
• User-defined function. Enter the name of a user-defined triangle selection
method. See Poisson's Equation with Point Source and Adaptive Mesh Refinement
for an example of a user-defined triangle selection method.
• Function parameter. The function parameter allows fine-tuning of the triangle
selection methods. For the worst triangle method (pdeadworst), it is the fraction of
the worst value that is used to determine which triangles to refine. For the relative
tolerance method, it is a tolerance parameter that controls how well the solution fits
the PDE.
• Refinement method. Can be regular or longest. See “Specify Mesh Parameters in
the PDE Modeler App” on page 4-20.
If the problem is nonlinear, i.e., parameters in the PDE are directly dependent on the
solution u, a nonlinear solver must be used. The following parameters are used:
4-24
Adjust Solve Parameters in the PDE Modeler App
Note The adaptive mode and the nonlinear solver can be used together.
Parabolic Equations
• Time. A MATLAB vector of times at which a solution to the parabolic PDE should be
generated. The relevant time span is dependent on the dynamics of the problem.
4-25
4 PDE Modeler App
Hyperbolic Equations
• Time. A MATLAB vector of times at which a solution to the hyperbolic PDE should be
generated. The relevant time span is dependent on the dynamics of the problem.
4-26
Adjust Solve Parameters in the PDE Modeler App
• Absolute tolerance. Absolute tolerance parameter for the ODE solver that is used for
solving the time-dependent part of the hyperbolic PDE problem.
Eigenvalue Equations
For the eigenvalue PDE, the only solve parameter is the Eigenvalue search range, a
two-element vector, defining an interval on the real axis as a search range for the
eigenvalues. The left side can be -Inf.
Nonlinear Equations
Before solving a nonlinear elliptic PDE in the PDE Modeler app, select SolveParameters.
Then select Use nonlinear solver and click OK.
4-27
4 PDE Modeler App
4-28
Plot the Solution in the PDE Modeler App
To open the Plot Selection dialog box, select Parameters from the Plot menu or click
the button.
Parameters opens a dialog box containing options controlling the plotting and
visualization.
• Plot type (far left) contains a row of six different plot types, which can be used for
visualization:
4-29
4 PDE Modeler App
A color bar is added to the plots to map the colors in the plot to the magnitude of the
property that is represented using color or contour lines.
• Property contains four pop-up menus containing lists of properties that are available
for plotting using the corresponding plot type. From the first pop-up menu you control
the property that is visualized using color and/or contour lines. The second and third
pop-up menus contain vector valued properties for visualization using arrows and
deformed mesh, respectively. From the fourth pop-up menu, finally, you control which
scalar property to visualize using z-height in a 3-D plot. The lists of properties are
dependent on the current application mode. For the generic scalar mode, you can
select the following scalar properties:
4-30
Plot the Solution in the PDE Modeler App
available in the local workspace. You enter the expression into the edit box to the
right of the Property pop-up menu in the User entry column.
The vector property pop-up menus contain the following properties in the generic
scalar case:
For the generic system case, the properties available for visualization using color, contour
lines, or z-height are u, v, abs(u,v), and a user entry. For visualization using arrows or a
deformed mesh, you can choose (u,v) or a user entry. For applications in structural
mechanics, u and v are the x- and y-displacements, respectively.
The variables available in the local workspace for a user entered expression are the same
for all scalar and system modes (the solution is always referred to as u and, in the system
case, v).
• User entry contains four edit fields where you can enter your own expression, if you
select the user entry property from the corresponding pop-up menu to the left of the
edit fields. If the user entry property is not selected, the corresponding edit field is
disabled.
• Plot style contains three pop-up menus from which you can control the plot style for
the color, arrow, and height plot types respectively. The available plot styles for color
surface plots are
4-31
4 PDE Modeler App
• Flat shading. A surface plot using the selected colormap and flat shading, i.e.,
each triangular area is colored using a constant color.
A total of three properties of the solution—two scalar properties and one vector field—can
be visualized simultaneously. If the Height (3-D plot) option is turned off, the solution
plot is a 2-D plot and is plotted in the main axes of the PDE Modeler app. If the Height
(3-D plot) option is used, the solution plot is a 3-D plot in a separate figure window. If
possible, the 3-D plot uses an existing figure window. If you would like to plot in a new
figure window, simply type figure at the MATLAB command line.
• Plot in x-y grid. If you select this option, the solution is converted from the original
triangular grid to a rectangular x-y grid. This is especially useful for animations since
it speeds up the process of recording the movie frames significantly.
• Show mesh. In the surface plots, the mesh is plotted using black color if you select
this option. By default, the mesh is hidden.
• Contour plot levels. For contour plots, the number of level curves, e.g., 15 or 20 can
be entered. Alternatively, you can enter a MATLAB vector of levels. The curves of the
contour plot are then drawn at those levels. The default is 20 contour level curves.
4-32
Plot the Solution in the PDE Modeler App
• Colormap. Using the Colormap pop-up menu, you can select from a number of
different colormaps: cool, gray, bone, pink, copper, hot, jet, hsv, prism, and
parula.
• Plot solution automatically. This option is normally selected. If turned off, there will
not be a display of a plot of the solution immediately upon solving the PDE. The new
solution, however, can be plotted using this dialog box.
For the parabolic and hyperbolic PDEs, the bottom right portion of the Plot Selection
dialog box contains the Time for plot parameter.
Time for plot. A pop-up menu allows you to select which of the solutions to plot by
selecting the corresponding time. By default, the last solution is plotted.
Also, the Animation plot type is enabled. In its property field you find an Options button.
If you press it, an additional dialog box appears. It contains parameters that control the
animation:
• Animation rate (fps). For the animation, this parameter controls the speed of the
movie in frames per second (fps).
• Number of repeats. The number of times the movie is played.
• Replay movie. If you select this option, the current movie is replayed without
rerecording the movie frames. If there is no current movie, this option is disabled.
4-33
4 PDE Modeler App
For eigenvalue problems, the bottom right part of the dialog box contains a pop-up menu
with all eigenvalues. The plotted solution is the eigenvector associated with the selected
eigenvalue. By default, the smallest eigenvalue is selected.
You can rotate the 3-D plots by clicking the plot and, while keeping the mouse button
down, moving the mouse. For guidance, a surrounding box appears. When you release the
mouse, the plot is redrawn using the new viewpoint. Initially, the solution is plotted using
-37.5 degrees horizontal rotation and 30 degrees elevation.
If you click the Plot button, the solution is plotted immediately using the current plot
setup. If there is no current solution available, the PDE is first solved. The new solution is
then plotted. The dialog box remains on the screen.
If you click the Done button, the dialog box is closed. The current setup is saved but no
additional plotting takes place.
If you click the Cancel button, the dialog box is closed. The setup remains unchanged
since the last plot.
4-34
Plot the Solution in the PDE Modeler App
In plot mode, you can use the mouse to display the numerical value of the plotted
property at the position where you click. Press the left mouse button to display the
triangle number and the value of the plotted property on the information line.
The information remains on the information line until you release the mouse button.
4-35
5
adaptmesh
Adaptive 2-D mesh generation and PDE solution
Note This page describes the legacy workflow. New features might not be compatible
with the legacy workflow. In the recommended workflow, see generateMesh for mesh
generation and solvepde for PDE solution.
Syntax
[u,p,e,t] = adaptmesh(g,b,c,a,f)
[u,p,e,t] = adaptmesh(g,b,c,a,f,'PropertyName',PropertyValue)
Description
[u,p,e,t] = adaptmesh(g,b,c,a,f) and [u,p,e,t] =
adaptmesh(g,b,c,a,f,'PropertyName',PropertyValue) perform adaptive mesh
generation and PDE solution for elliptic problems with 2-D geometry. Optional arguments
are given as property name/property value pairs.
-— ◊ ( c—u ) + au = f
-— ◊ ( c ƒ — u ) + au = f
with the problem geometry and boundary conditions given by g and b. The mesh is
described by the p, e, and t matrices.
The solution u is represented as the solution vector u. If the PDE is scalar, meaning that is
has only one equation, then u is a column vector representing the solution u at each node
in the mesh. If the PDE is a system of N > 1 equations, then u is a column vector with
N*Np elements, where Np is the number of nodes in the mesh. The first Np elements of u
5-2
adaptmesh
represent the solution of equation 1, the next Np elements represent the solution of
equation 2, and so on.
The algorithm works by solving a sequence of PDE problems using refined triangular
meshes. The first triangular mesh generation is provided as an optional argument to
adaptmesh or obtained by a call to initmesh without options. Subsequent generations
of triangular meshes are obtained by solving the PDE problem, computing an error
estimate, selecting a set of triangles based on the error estimate, and then refining the
triangles. The solution to the PDE problem is then recomputed. The loop continues until
the triangle selection method selects no further triangles, until the maximum number of
triangles is attained, or until the maximum number of triangle generations is reached.
g describes the geometry of the PDE problem. g can be a decomposed geometry matrix,
the name of a geometry file, or a function handle to a geometry file. For details, see
“Three Ways to Create 2-D Geometry” on page 2-8.
b describes the boundary conditions of the PDE problem. For details, see “Boundary
Conditions by Writing Functions” on page 2-204.
The adapted triangular mesh of the PDE problem is given by the mesh data p, e, and t.
For details on the mesh data representation, see “Mesh Data as [p,e,t] Triples” on page 2-
238.
The coefficients c, a, and f of the PDE problem can be given in a wide variety of ways. In
the context of adaptmesh, the coefficients can depend on u if the nonlinear solver is
enabled using the property nonlin. The coefficients cannot depend on t, the time.
5-3
5 Functions — Alphabetical List
Par is passed to the Tripick function, which is described later. Normally it is used as
tolerance of how well the solution fits the equation.
No more than Ngen successive refinements are attempted. Refinement is also stopped
when the number of triangles in the mesh exceeds Maxt.
p1, e1, and t1 are the input mesh data. This triangular mesh is used as starting mesh for
the adaptive algorithm. For details on the mesh data representation, see initmesh. If no
initial mesh is provided, the result of a call to initmesh with no options is used as the
initial mesh.
5-4
adaptmesh
The refinement method is longest or regular. For details on the refinement method,
see refinemesh.
The MesherVersion property chooses the algorithm for mesh generation. The 'R2013a'
algorithm runs faster and can triangulate more geometries than the 'preR2013a'
algorithm. Both algorithms use Delaunay triangulation.
The adaptive algorithm can also solve nonlinear PDE problems. For nonlinear PDE
problems, the Nonlin parameter must be set to on. The nonlinear tolerance Toln,
nonlinear initial value u0, nonlinear Jacobian calculation Jac, and nonlinear residual
norm Norm are passed to the nonlinear solver pdenonlin.
Examples
Solve the Laplace equation over a circle sector, with Dirichlet boundary conditions u =
cos(2/3atan2( y , x )) along the arc and u = 0 along the straight lines, and compare the
resulting solution to the exact solution. Set options so that adaptmesh refines the
triangles using the worst error criterion until it obtains a mesh with at least 500 triangles.
[u,p,e,t]=adaptmesh('cirsg','cirsb',1,0,0,'maxt',500,...
'tripick','pdeadworst','ngen',inf);
x=p(1,:); y=p(2,:);
exact=((x.^2+y.^2).^(1/3).*cos(2/3*atan2(y,x)))';
max(abs(u-exact))
5-5
5 Functions — Alphabetical List
ans = 0.0028
size(t,2)
ans = 629
Test how many refinements you need with a uniform triangle net.
[p,e,t]=initmesh('cirsg');
[p,e,t]=refinemesh('cirsg',p,e,t);
u=assempde('cirsb',p,e,t,1,0,0);
5-6
adaptmesh
x=p(1,:); y=p(2,:);
exact=((x.^2+y.^2).^(1/3).*cos(2/3*atan2(y,x)))';
max(abs(u-exact))
ans = 0.0121
size(t,2)
ans = 788
[p,e,t]=refinemesh('cirsg',p,e,t);
u=assempde('cirsb',p,e,t,1,0,0);
x=p(1,:); y=p(2,:);
exact=((x.^2+y.^2).^(1/3).*cos(2/3*atan2(y,x)))';
max(abs(u-exact))
ans = 0.0078
size(t,2)
ans = 3152
pdemesh(p,e,t)
5-7
5 Functions — Alphabetical List
Uniform refinement with 3152 triangles produces an error of 0.0078. This error is over
three times as large as that produced by the adaptive method (0.0028) with many fewer
triangles (629). Typically, a problem with regular solution has an error. However,
this solution is singular since at the origin.
Diagnostics
Upon termination, one of the following messages is displayed:
5-8
adaptmesh
• Adaption completed (This means that the Tripick function returned zero
triangles to refine.)
• Maximum number of triangles obtained
• Maximum number of refinement passes obtained
Algorithms
Mesh Refinement for Improving Solution Accuracy
Partial Differential Equation Toolbox provides the refinemesh function for global,
uniform mesh refinement for 2-D geometries. It divides each triangle into four similar
triangles by creating new corners at the midsides, adjusting for curved boundaries. You
can assess the accuracy of the numerical solution by comparing results from a sequence
of successively refined meshes. If the solution is smooth enough, more accurate results
can be obtained by extrapolation.
The solutions of equations often have geometric features such as localized strong
gradients. An example of engineering importance in elasticity is the stress concentration
occurring at reentrant corners, such as the MATLAB L-shaped membrane. In such cases,
it is more economical to refine the mesh selectively, that is, only where it is needed. The
selection that is based on estimates of errors in the computed solutions is called adaptive
mesh refinement. See adaptmesh for an example of the computational savings where
global refinement needs more than 6000 elements to compete with an adaptively refined
mesh of 500 elements.
5-9
5 Functions — Alphabetical List
criteria, and so on to be optimal in the sense of giving the most accurate solution at fixed
cost or lowest computational effort for a given accuracy. Such results have been proved
only for model problems, but generally, the equidistribution heuristic has been found near
optimal. Element sizes must be chosen so that each element contributes the same to the
error. The theory of adaptive schemes makes use of a priori bounds for solutions in terms
of the source function f. For nonelliptic problems, such bounds might not exist, while the
refinement scheme is still well defined and works well.
The error indicator function used in the software is an elementwise estimate of the
contribution, based on the work of C. Johnson et al. [1], [2]. For Poisson's equation –Δu = f
on Ω, the following error estimate for the FEM-solution uh holds in the L2-norm ◊ :
— (u - uh ) £ a hf + b Dh (uh )
1/2
Ê È ∂v ˘ ˆ
2
Dh (v) = Á Â
Á t ŒE
ht2 Í
Î
˙
∂nt ˚ ˜
˜
Ë 1 ¯
The braced quantity is the jump in normal derivative of v across the edge τ, hτ is the
length of the edge τ, and the sum runs over Ei, the set of all interior edges of the
triangulation. The coefficients α and β are independent of the triangulation. This bound is
turned into an elementwise error indicator function E(K) for the element K by summing
the contributions from its edges.
The general form of the error indicator function for the elliptic equation
–∇ · (c∇u) + au = f (5-1)
is
1/2
Ê1 2ˆ
E ( K ) = a h ( f - au ) K
+ bÁ
2
 ht2 ( nt · c—uh ) ˜
Ë t Œ∂ K ¯
where nt is the unit normal of the edge τ and the braced term is the jump in flux across
the element edge. The L2 norm is computed over the element K. The pdejmps function
computes this error indicator.
5-10
adaptmesh
When an element is refined, new nodes appear on its midsides, and if the neighbor
triangle is not refined in a similar way, it is said to have hanging nodes. The final
triangulation must have no hanging nodes, and they are removed by splitting neighbor
triangles. To avoid further deterioration of triangle quality in successive generations, the
"longest edge bisection" scheme is used by Rosenberg-Stenger [3], in which the longest
side of a triangle is always split, whenever any of the sides have hanging nodes. This
guarantees that no angle is ever smaller than half the smallest angle of the original
triangulation.
Two selection criteria can be used. One, pdeadworst, refines all elements with value of
the error indicator larger than half the worst of any element. The other, pdeadgsc,
refines all elements with an indicator value exceeding a user-defined dimensionless
tolerance. The comparison with the tolerance is properly scaled with respect to domain,
solution size, and so on.
References
[1] Johnson, C. Numerical Solution of Partial Differential Equations by the Finite Element
Method. Lund, Sweden: Studentlitteratur, 1987.
[2] Johnson, C., and K. Eriksson. Adaptive Finite Element Methods for Parabolic Problems
I: A Linear Model Problem. SIAM J. Numer. Anal, 28, (1991), pp. 43–77.
5-11
5 Functions — Alphabetical List
[3] Rosenberg, I.G., and F. Stenger, A lower bound on the angles of triangles constructed
by bisecting the longest side. Mathematics of Computation. Vol 29, Number 10,
1975, pp 390–395.
See Also
initmesh | refinemesh
5-12
AnalyticGeometry Properties
AnalyticGeometry Properties
2-D geometry description
Description
AnalyticGeometry describes 2-D geometry in the form of an object. A PDEModel object
has a Geometry property. For 2-D geometry, the Geometry property is an
AnalyticGeometry object.
Specify a 2-D geometry for your model using the geometryFromEdges function.
Properties
Properties
5-13
5 Functions — Alphabetical List
See Also
PDEModel | geometryFromEdges
Topics
“Solve Problems Using PDEModel Objects” on page 2-6
Introduced in R2015a
5-14
applyBoundaryCondition
applyBoundaryCondition
Package: pde
Syntax
applyBoundaryCondition(model,'dirichlet',RegionType,RegionID,
Name,Value)
applyBoundaryCondition(model,'neumann',RegionType,RegionID,
Name,Value)
applyBoundaryCondition(model,'mixed',RegionType,RegionID,Name,Value)
bc = applyBoundaryCondition( ___ )
Description
applyBoundaryCondition(model,'dirichlet',RegionType,RegionID,
Name,Value) adds a Dirichlet boundary condition to model. The boundary condition
applies to boundary regions of type RegionType with ID numbers in RegionID, and with
arguments r, h, u, EquationIndex specified in the Name,Value pairs. For Dirichlet
boundary conditions, specify either both arguments r and h, or the argument u. When
specifying u, you can also use EquationIndex.
applyBoundaryCondition(model,'neumann',RegionType,RegionID,
Name,Value) adds a Neumann boundary condition to model. The boundary condition
applies to boundary regions of type RegionType with ID numbers in RegionID, and with
values g and q specified in the Name,Value pairs.
applyBoundaryCondition(model,'mixed',RegionType,RegionID,Name,Value)
adds an individual boundary condition for each equation in a system of PDEs. The
boundary condition applies to boundary regions of type RegionType with ID numbers in
RegionID, and with values specified in the Name,Value pairs. For mixed boundary
conditions, you can use Name,Value pairs from both Dirichlet and Neumann boundary
conditions as needed.
5-15
5 Functions — Alphabetical List
Examples
model = createpde(1);
R1 = [3,4,-1,1,1,-1,-.4,-.4,.4,.4]';
g = decsg(R1);
geometryFromEdges(model,g);
pdegplot(model,'EdgeLabels','on')
xlim([-1.2,1.2])
axis equal
5-16
applyBoundaryCondition
applyBoundaryCondition(model,'dirichlet','Edge',1,'u',0);
applyBoundaryCondition(model,'dirichlet','Edge',2:4,'r',1,'h',1);
5-17
5 Functions — Alphabetical List
model = createpde(2);
R1 = [3,4,-1,1,1,-1,-.4,-.4,.4,.4]';
g = decsg(R1);
geometryFromEdges(model,g);
5-18
applyBoundaryCondition
Apply both types of boundary conditions to a scalar problem. First, create a PDE model
and import a simple block geometry.
model = createpde;
importGeometry(model,'Block.stl');
Set zero Dirichlet conditions on the narrow faces, which are labeled 1 through 4.
5-19
5 Functions — Alphabetical List
applyBoundaryCondition(model,'dirichlet','Face',1:4,'u',0);
Solve an elliptic PDE with these boundary conditions, and plot the result.
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',0,'f',0);
generateMesh(model);
results = solvepde(model);
u = results.NodalSolution;
pdeplot3D(model,'ColorMapData',u)
5-20
applyBoundaryCondition
model = createpde(3);
importGeometry(model,'Block.stl');
pdegplot(model,'FaceLabels','on','FaceAlpha',0.5)
5-21
5 Functions — Alphabetical List
applyBoundaryCondition(model,'dirichlet','Face',1:2,'u',[0,0,0]);
applyBoundaryCondition(model,'neumann','Face',4:5,'g',[1;1;1]);
applyBoundaryCondition(model,'neumann','Face',6,'g',[-1;-1;-1]);
For face 3, apply generalized Neumann boundary condition for the first equation and
Dirichlet boundary conditions for the second and third equations.
Solve an elliptic PDE with these boundary conditions, and plot the result.
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',0,'f',[0;0;0]);
generateMesh(model);
results = solvepde(model);
u = results.NodalSolution;
pdeplot3D(model,'ColorMapData',u(:,1))
5-22
applyBoundaryCondition
Input Arguments
model — PDE model
PDEModel object
5-23
5 Functions — Alphabetical List
Geometric region type, specified as 'Face' for 3-D geometry or 'Edge' for 2-D
geometry.
Example: applyBoundaryCondition(model,'dirichlet','Face',3,'u',0)
Data Types: char | string
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot with the 'FaceLabels' (3-D) or 'EdgeLabels' (2-D) value set to 'on'.
Example: applyBoundaryCondition(model,'dirichlet','Face',3:6,'u',0)
Data Types: double
Dirichlet condition h*u = r, specified as an N-by-N matrix, a vector with N^2 elements,
or a function handle. N is the number of PDEs in the system. For the syntax of the
function handle form of h, see “Nonconstant Boundary Conditions” on page 2-186.
Example: 'h',[2,1;1,2]
Data Types: double | function_handle
Complex Number Support: Yes
5-24
applyBoundaryCondition
u — Dirichlet conditions
zeros(N,1) (default) | vector of up to N elements | function handle
For the syntax of the function handle form of u, see “Nonconstant Boundary Conditions”
on page 2-186.
Example: applyBoundaryCondition(model,'dirichlet','Face',[2,4,11],'u',
0)
Data Types: double
Complex Number Support: Yes
5-25
5 Functions — Alphabetical List
Index of the known u components, specified as a vector of integers with entries from 1 to
N. EquationIndex and u must have the same length.
Example: applyBoundaryCondition(model,'mixed','Face',[2,4,11],'u',
[3,-1],'EquationIndex',[2,3])
Data Types: double
Vectorized function evaluation, specified as 'on' or 'off'. This evaluation applies when
you pass a function handle as an argument. To save time in function handle evaluation,
specify 'on', assuming that your function handle computes in a vectorized fashion. See
“Vectorization” (MATLAB). For details of this evaluation, see “Nonconstant Boundary
Conditions” on page 2-186.
Example: applyBoundaryCondition(model,'dirichlet','Face',
[2,4,11],'u',@ucalculator,'Vectorized','on')
Data Types: char | string
Output Arguments
bc — Boundary condition
BoundaryCondition object
Tips
• When there are multiple boundary condition assignments to the same geometric
region, the toolbox uses the last applied setting.
• To avoid assigning boundary conditions to a wrong region, ensure that you are using
the correct geometric region IDs by plotting and visually inspecting the geometry.
See Also
BoundaryCondition | PDEModel | findBoundaryConditions
5-26
applyBoundaryCondition
Topics
“Solve Problems Using PDEModel Objects” on page 2-6
Introduced in R2015a
5-27
5 Functions — Alphabetical List
area
Package: pde
Syntax
A = area(mesh)
[A,AE] = area(mesh)
A = area(mesh,elements)
Description
A = area(mesh) returns the area A of the entire mesh.
[A,AE] = area(mesh) also returns a row vector AE containing areas of each individual
element of the mesh.
Examples
Include the geometry of the built-in function lshapeg. Plot the geometry.
geometryFromEdges(model,@lshapeg);
pdegplot(model,'FaceLabels','on')
5-28
area
mesh = generateMesh(model);
figure
pdemesh(model)
5-29
5 Functions — Alphabetical List
ma = area(mesh)
ma = 3.0000
5-30
area
model = createpde;
Include the geometry of the built-in function lshapeg. Plot the geometry.
geometryFromEdges(model,@lshapeg);
pdegplot(model,'FaceLabels','on')
mesh = generateMesh(model);
figure
pdemesh(model)
5-31
5 Functions — Alphabetical List
Compute the area of the entire mesh and the area of each individual element of the mesh.
Display the areas of the first 5 elements.
[ma,mi] = area(mesh);
mi(1:5)
ans = 1×5
5-32
area
Find the combined area of the elements associated with a particular face of a 2-D mesh.
model = createpde;
Include the geometry of the built-in function lshapeg. Plot the geometry.
geometryFromEdges(model,@lshapeg);
pdegplot(model,'FaceLabels','on')
5-33
5 Functions — Alphabetical List
mesh = generateMesh(model);
figure
pdemesh(model)
Find the elements associated with face 1 and compute the total area of these elements.
Ef1 = findElements(mesh,'region','Face',1);
maf1 = area(mesh,Ef1)
maf1 = 1.0000
Find how much of the total mesh area belongs to these elements. Return the result as a
percentage.
maf1_percent = maf1/area(mesh)*100
5-34
area
maf1_percent = 33.3333
Input Arguments
mesh — Mesh object
Mesh property of a PDEModel object | output of generateMesh
Mesh object, specified as the Mesh property of a PDEModel object or as the output of
generateMesh.
Example: model.Mesh
Output Arguments
A — Area
positive number
Area of the entire mesh or the combined area of the specified elements of the mesh,
returned as a positive number.
See Also
FEMesh Properties | findElements | findNodes | meshQuality | volume
Topics
“Finite Element Method Basics” on page 1-27
5-35
5 Functions — Alphabetical List
Introduced in R2018a
5-36
assema
assema
(Not recommended) Assemble area integral contributions
Syntax
[K,M,F] = assema(model,c,a,f)
[K,M,F] = assema(p,t,c,a,f)
Description
[K,M,F] = assema(model,c,a,f) assembles the stiffness matrix K, the mass matrix
M, and the load vector F using the mesh contained in model, and the PDE coefficients c,
a, and f.
[K,M,F] = assema(p,t,c,a,f) assembles the matrices from the mesh data in p and
t.
Examples
5-37
5 Functions — Alphabetical List
c = 1;
a = 0;
f = 1;
Create a PDE model container. Import the ForearmLink.stl file into the model and
examine the geometry.
model = createpde;
importGeometry(model,'ForearmLink.stl');
pdegplot(model,'FaceAlpha',0.5)
5-38
assema
generateMesh(model);
Create the finite element matrices from the mesh and the coefficients.
[K,M,F] = assema(model,c,a,f);
Assemble finite element matrices for the 2-D L-shaped region, using the [p,e,t] mesh
representation.
Define the geometry using the lshapeg function included your software.
g = @lshapeg;
c = 1;
a = 0;
f = 1;
[p,e,t] = initmesh(g);
[K,M,F] = assema(p,t,c,a,f);
The returned matrix M has all zeros. The K matrix is quite sparse.
5-39
5 Functions — Alphabetical List
Input Arguments
model — PDE model
PDEModel object
c — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. c represents the c coefficient in the scalar
PDE
-— ◊ ( c—u ) + au = f
-— ◊ ( c ƒ — u ) + au = f
You can specifyc in various ways, detailed in “c Coefficient for Systems” on page 2-131.
See also “Specify Scalar PDE Coefficients in Character Form” on page 2-76, “Specify 2-D
Scalar Coefficients in Function Form” on page 2-82, and “Specify 3-D PDE Coefficients in
Function Form” on page 2-85.
Example: 'cosh(x+y.^2)'
Data Types: double | char | string | function_handle
Complex Number Support: Yes
a — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
5-40
assema
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. a represents the a coefficient in the scalar
PDE
-— ◊ ( c—u ) + au = f
-— ◊ ( c ƒ — u ) + au = f
You can specifya in various ways, detailed in “a or d Coefficient for Systems” on page 2-
154. See also “Specify Scalar PDE Coefficients in Character Form” on page 2-76, “Specify
2-D Scalar Coefficients in Function Form” on page 2-82, and “Specify 3-D PDE
Coefficients in Function Form” on page 2-85.
Example: 2*eye(3)
Data Types: double | char | string | function_handle
Complex Number Support: Yes
f — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. f represents the f coefficient in the scalar
PDE
-— ◊ ( c—u ) + au = f
-— ◊ ( c ƒ — u ) + au = f
You can specifyf in various ways, detailed in “f Coefficient for Systems” on page 2-104.
See also “Specify Scalar PDE Coefficients in Character Form” on page 2-76, “Specify 2-D
Scalar Coefficients in Function Form” on page 2-82, and “Specify 3-D PDE Coefficients in
Function Form” on page 2-85.
Example: char('sin(x)';'cos(y)';'tan(z)')
Data Types: double | char | string | function_handle
5-41
5 Functions — Alphabetical List
p — Mesh points
matrix
Mesh points, specified as a 2-by-Np matrix of points, where Np is the number of points in
the mesh. For a description of the (p,e,t) matrices, see “Mesh Data” on page 2-241.
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
t — Mesh triangles
matrix
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
Output Arguments
K — Stiffness matrix
sparse matrix
Stiffness matrix, returned as a sparse matrix. See “Elliptic Equations” on page 5-75.
M — Mass matrix
sparse matrix
Mass matrix. returned as a sparse matrix. See “Elliptic Equations” on page 5-75.
5-42
assema
F — Load vector
vector
See Also
assembleFEMatrices
5-43
5 Functions — Alphabetical List
assemb
(Not recommended) Assemble boundary condition contributions
Syntax
[Q,G,H,R] = assemb(model)
[Q,G,H,R] = assemb(b,p,e)
[Q,G,H,R] = assemb( ___ ,[],sdl)
Description
[Q,G,H,R] = assemb(model) assembles the matrices Q and H, and the vectors G and
R. Q should be added to the system matrix and contains contributions from mixed
boundary conditions.
[Q,G,H,R] = assemb( ___ ,[],sdl), for any of the previous input arguments,
restricts the finite element matrices to those that include the subdomain specified by the
subdomain labels in sdl. The empty argument is required in this syntax for historic and
compatibility reasons.
Examples
5-44
assemb
c = 1;
a = 0;
f = 1;
Create a PDE model container. Import the ForearmLink.stl file into the model and
examine the geometry.
model = createpde;
importGeometry(model,'Block.stl');
h = pdegplot(model,'FaceLabels','on');
h(1).FaceAlpha = 0.5;
5-45
5 Functions — Alphabetical List
Set zero Dirichlet boundary conditions on the narrow faces (numbered 1 through 4).
applyBoundaryCondition(model,'Face',1:4,'u',0);
applyBoundaryCondition(model,'Face',6,'g',-1);
applyBoundaryCondition(model,'Face',5,'g',1);
generateMesh(model);
5-46
assemb
[Q,G,H,R] = assemb(model);
Assemble boundary condition matrices for the 2-D L-shaped region with Dirichlet
boundary conditions, using the [p,e,t] mesh representation.
Define the geometry and boundary conditions using functions included in your software.
g = @lshapeg;
b = @lshapeb;
[p,e,t] = initmesh(g);
[Q,G,H,R] = assemb(b,p,e);
Only one of the resulting matrices is nonzero, namely H. The H matrix is quite sparse.
Input Arguments
model — PDE model
PDEModel object
5-47
5 Functions — Alphabetical List
b — Boundary conditions
boundary matrix | boundary file
Boundary conditions, specified as a boundary matrix or boundary file. Pass a boundary file
as a function handle or as a file name.
• A boundary matrix is generally an export from the PDE Modeler app. For details of the
structure of this matrix, see “Boundary Matrix for 2-D Geometry” on page 2-175.
• A boundary file is a file that you write in the syntax specified in “Boundary Conditions
by Writing Functions” on page 2-204.
p — Mesh points
matrix
Mesh points, specified as a 2-by-Np matrix of points, where Np is the number of points in
the mesh. For a description of the (p,e,t) matrices, see “Mesh Data” on page 2-241.
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
e — Mesh edges
matrix
Mesh edges, specified as a 7-by-Ne matrix of edges, where Ne is the number of edges in
the mesh. For a description of the (p,e,t) matrices, see “Mesh Data” on page 2-241.
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
5-48
assemb
Subdomain labels, specified as a vector of positive integers. For 2-D geometry only. View
the subdomain labels in your geometry using the command
pdegplot(g,'SubdomainLabels','on')
Output Arguments
Q — Neumann boundary condition matrix
sparse matrix
Neumann boundary condition vector, returned as a sparse vector. See “Elliptic Equations”
on page 5-75.
H — Dirichlet matrix
sparse matrix
R — Dirichlet vector
sparse vector
5-49
5 Functions — Alphabetical List
Algorithms
As explained in “Elliptic Equations” on page 5-75, the finite element matrices and
vectors correspond to the reduced linear system and are the following.
For more information on the reduced linear system form of the finite element matrices,
see the assempde “Definitions” on page 5-74 section, and the linear algebra approach
detailed in “Systems of PDEs” on page 5-84.
See Also
assembleFEMatrices
5-50
assembleFEMatrices
assembleFEMatrices
Assemble finite element matrices
Syntax
FEM = assembleFEMatrices(model)
FEM = assembleFEMatrices(model,bcmethod)
Description
FEM = assembleFEMatrices(model) returns a structure containing finite element
matrices for the PDE problem in model.
Examples
Create a PDEModel for the Poisson equation on the L-shaped membrane with zero
Dirichlet boundary conditions.
model = createpde(1);
geometryFromEdges(model,@lshapeg);
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',0,'f',1);
applyBoundaryCondition(model,'edge',1:model.Geometry.NumEdges,'u',0);
Generate a mesh and obtain the default finite element matrices for the problem and
mesh.
generateMesh(model,'Hmax',0.2);
FEM = assembleFEMatrices(model)
5-51
5 Functions — Alphabetical List
A: [401x401 double]
F: [401x1 double]
Q: [401x401 double]
G: [401x1 double]
H: [80x401 double]
R: [80x1 double]
M: [401x401 double]
Assemble Finite Element Matrices for a 2-D Problem With Boundary Conditions
Imposed Using nullspace Method and Obtain PDE Solution
Create a PDEModel for the Poisson equation on the L-shaped membrane with zero
Dirichlet boundary conditions.
model = createpde(1);
geometryFromEdges(model,@lshapeg);
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',0,'f',1);
applyBoundaryCondition(model,'edge',1:model.Geometry.NumEdges,'u',0);
Generate a mesh and obtain the nullspace finite element matrices for the problem and
mesh.
generateMesh(model,'Hmax',0.2);
FEM = assembleFEMatrices(model,'nullspace')
u = FEM.B*(FEM.Kc\FEM.Fc) + FEM.ud;
Compare to the solution using solvepde. The two solutions are identical.
u1 = solvepde(model);
norm(u - u1.NodalSolution)
5-52
assembleFEMatrices
ans = 0
Input Arguments
model — PDE model
PDEModel object
Output Arguments
FEM — Finite element matrices
structure
Finite element matrices, returned as a structure. The fields in the structure depend on
bcmethod. (These fields correspond to the legacy assempde outputs with the same
names, except that there are now both A and M matrices.)
For the meaning and use of FEM, see “Algorithms” on page 5-54.
5-53
5 Functions — Alphabetical List
Tips
• The mass matrix M is nonzero when the model is time-dependent. By using this matrix,
you can solve a model with Raleigh damping. See “Dynamics of Damped Cantilever
Beam”.
Algorithms
The full finite element matrices and vectors are the following:
• K is the stiffness matrix, the integral of the c coefficient against the basis functions.
• M is the mass matrix, the integral of the m or d coefficient against the basis functions.
• A is the integral of the a coefficient against the basis functions.
• F is the integral of the f coefficient against the basis functions.
• Q is the integral of the q boundary condition against the basis functions.
• G is the integral of the g boundary condition against the basis functions.
• The H and R matrices come directly from the Dirichlet conditions and the mesh.
Given these matrices, the 'nullspace' technique generates the combined finite element
matrices [Kc,Fc,B,ud] as follows. The combined stiffness matrix is for the reduced linear
system, Kc = K + M + Q. The corresponding combined load vector is Fc = F + G. The
B matrix spans the null space of the columns of H (the Dirichlet condition matrix
representing hu = r). The R vector represents the Dirichlet conditions in Hu = R. The ud
vector represents boundary condition solutions for the Dirichlet conditions.
u = B*(Kc\Fc) + ud.
5-54
assembleFEMatrices
See Also
solvepde
Topics
“Finite Element Method Basics” on page 1-27
Introduced in R2016a
5-55
5 Functions — Alphabetical List
assempde
(Not recommended) Assemble finite element matrices and solve elliptic PDE
Syntax
u = assempde(model,c,a,f)
u = assempde(b,p,e,t,c,a,f)
u = assempde(K,M,F,Q,G,H,R)
[Ks,Fs] = assempde(K,M,F,Q,G,H,R)
[Kc,Fc,B,ud] = assempde(K,M,F,Q,G,H,R)
Description
u = assempde(model,c,a,f) solves the PDE
-— ◊ ( c—u ) + au = f
with geometry, boundary conditions, and finite element mesh in model, and coefficients c,
a, and f. If the PDE is a system of equations (model.PDESystemSize > 1), then
assempde solves the system of equations
-— ◊ ( c ƒ — u ) + au = f
5-56
assempde
[Kc,Fc,B,ud] = assempde( ___ ), for any of the previous input syntaxes, assembles
finite element matrices using the reduced linear system form, which eliminates any
Dirichlet boundary conditions from the system of linear equations. You can calculate the
solution u at node points by the command u = B*(Kc\Fc) + ud. See “Reduced Linear
System” on page 5-74.
[Ks,Fs] = assempde( ___ ) assembles finite element matrices that represent any
Dirichlet boundary conditions using a stiff-spring approximation. You can calculate the
solution u at node points by the command u = Ks\Fs. See “Stiff-Spring Approximation”
on page 5-75.
Examples
5-57
5 Functions — Alphabetical List
applyBoundaryCondition(model,'Edge',1:model.Geometry.NumEdges,'u',0);
generateMesh(model,'GeometricOrder','linear');
c = 1;
a = 0;
f = 5;
u = assempde(model,c,a,f);
pdeplot(model,'XYData',u)
5-58
assempde
Create a PDE model container, import a 3-D geometry description, and view the geometry.
model = createpde;
importGeometry(model,'Block.stl');
pdegplot(model,'FaceLabels','on','FaceAlpha',0.5)
5-59
5 Functions — Alphabetical List
Set zero Dirichlet conditions on faces 1 through 4 (the edges). Set Neumann conditions
with g = -1 on face 6 and g = 1 on face 5.
applyBoundaryCondition(model,'Face',1:4,'u',0);
applyBoundaryCondition(model,'Face',6,'g',-1);
applyBoundaryCondition(model,'Face',5,'g',1);
c = 1;
a = 0;
f = 0.1;
5-60
assempde
generateMesh(model);
u = assempde(model,c,a,f);
5-61
5 Functions — Alphabetical List
g = @circleg;
b = @circleb1;
[p,e,t] = initmesh(g);
c = 1;
a = 0;
f = 'sin(x)';
u = assempde(b,p,e,t,c,a,f);
pdeplot(p,e,t,'XYData',u)
5-62
assempde
Obtain the finite-element matrices that represent the problem using a reduced linear
algebra representation of Dirichlet boundary conditions.
model = createpde;
importGeometry(model,'Block.stl');
5-63
5 Functions — Alphabetical List
applyBoundaryCondition(model,'dirichlet','Face',1:model.Geometry.NumFaces,'u',0);
You can obtain the solution u of the PDE at mesh nodes by executing the command
u = B*(K\F) + ud;
Generally, this solution is slightly more accurate than the stiff-spring solution, as
calculated in the next example.
5-64
assempde
c = 1;
a = 0;
f = 'log(1+x+y./(1+z))';
[Ks,Fs] = assempde(model,c,a,f);
You can obtain the solution u of the PDE at mesh nodes by executing the command
u = Ks\Fs;
Generally, this solution is slightly less accurate than the reduced linear algebra solution,
as calculated in the previous example.
Obtain the full collection of finite element matrices for an elliptic problem.
Import geometry and set up an elliptic problem with Dirichlet boundary conditions. The
Torus.stl geometry has only one face, so you need set only one boundary condition.
model = createpde();
importGeometry(model,'Torus.stl');
applyBoundaryCondition(model,'face',1,'u',0);
c = 1;
a = 0;
f = 1;
generateMesh(model);
Most of the resulting matrices are quite sparse. G, M, Q, and R are all zero sparse
matrices.
howsparse = @(x)nnz(x)/numel(x);
disp(['Maximum fraction of nonzero entries in K or H is ',...
num2str(max(howsparse(K),howsparse(H)))])
5-65
5 Functions — Alphabetical List
Input Arguments
model — PDE model
PDEModel object
c — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. c represents the c coefficient in the scalar
PDE
-— ◊ ( c—u ) + au = f
-— ◊ ( c ƒ — u ) + au = f
You can specifyc in various ways, detailed in “c Coefficient for Systems” on page 2-131.
See also “Specify Scalar PDE Coefficients in Character Form” on page 2-76, “Specify 2-D
Scalar Coefficients in Function Form” on page 2-82, and “Specify 3-D PDE Coefficients in
Function Form” on page 2-85.
Example: 'cosh(x+y.^2)'
Data Types: double | char | string | function_handle
Complex Number Support: Yes
a — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. a represents the a coefficient in the scalar
PDE
5-66
assempde
-— ◊ ( c—u ) + au = f
-— ◊ ( c ƒ — u ) + au = f
You can specifya in various ways, detailed in “a or d Coefficient for Systems” on page 2-
154. See also “Specify Scalar PDE Coefficients in Character Form” on page 2-76, “Specify
2-D Scalar Coefficients in Function Form” on page 2-82, and “Specify 3-D PDE
Coefficients in Function Form” on page 2-85.
Example: 2*eye(3)
Data Types: double | char | string | function_handle
Complex Number Support: Yes
f — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. f represents the f coefficient in the scalar
PDE
-— ◊ ( c—u ) + au = f
-— ◊ ( c ƒ — u ) + au = f
You can specifyf in various ways, detailed in “f Coefficient for Systems” on page 2-104.
See also “Specify Scalar PDE Coefficients in Character Form” on page 2-76, “Specify 2-D
Scalar Coefficients in Function Form” on page 2-82, and “Specify 3-D PDE Coefficients in
Function Form” on page 2-85.
Example: char('sin(x)';'cos(y)';'tan(z)')
Data Types: double | char | string | function_handle
Complex Number Support: Yes
b — Boundary conditions
boundary matrix | boundary file
5-67
5 Functions — Alphabetical List
Boundary conditions, specified as a boundary matrix or boundary file. Pass a boundary file
as a function handle or as a file name.
• A boundary matrix is generally an export from the PDE Modeler app. For details of the
structure of this matrix, see “Boundary Matrix for 2-D Geometry” on page 2-175.
• A boundary file is a file that you write in the syntax specified in “Boundary Conditions
by Writing Functions” on page 2-204.
p — Mesh points
matrix
Mesh points, specified as a 2-by-Np matrix of points, where Np is the number of points in
the mesh. For a description of the (p,e,t) matrices, see “Mesh Data” on page 2-241.
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
e — Mesh edges
matrix
Mesh edges, specified as a 7-by-Ne matrix of edges, where Ne is the number of edges in
the mesh. For a description of the (p,e,t) matrices, see “Mesh Data” on page 2-241.
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
t — Mesh triangles
matrix
5-68
assempde
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
K — Stiffness matrix
sparse matrix | full matrix
Stiffness matrix, specified as a sparse matrix or full matrix. Generally, you obtain K from a
previous call to assema or assempde. For the meaning of stiffness matrix, see “Elliptic
Equations” on page 5-75.
Example: [K,M,F,Q,G,H,R] = assempde(model,c,a,f)
Data Types: double
Complex Number Support: Yes
M — Mass matrix
sparse matrix | full matrix
Mass matrix, specified as a sparse matrix or full matrix. Generally, you obtain M from a
previous call to assema or assempde. For the meaning of mass matrix, see “Elliptic
Equations” on page 5-75.
Example: [K,M,F,Q,G,H,R] = assempde(model,c,a,f)
Data Types: double
Complex Number Support: Yes
5-69
5 Functions — Alphabetical List
Neumann boundary condition vector, specified as a sparse vector or full vector. Generally,
you obtain G from a previous call to assemb or assempde. For the meaning of this vector,
see “Elliptic Equations” on page 5-75.
Example: [K,M,F,Q,G,H,R] = assempde(model,c,a,f)
Data Types: double
Complex Number Support: Yes
Dirichlet boundary condition matrix, specified as a sparse matrix or full matrix. Generally,
you obtain H from a previous call to assemb or assempde. For the meaning of this matrix,
see “Algorithms” on page 5-75.
Example: [K,M,F,Q,G,H,R] = assempde(model,c,a,f)
Data Types: double
Complex Number Support: Yes
Dirichlet boundary condition vector, specified as a sparse vector or full vector. Generally,
you obtain R from a previous call to assemb or assempde. For the meaning of this vector,
see “Algorithms” on page 5-75.
Example: [K,M,F,Q,G,H,R] = assempde(model,c,a,f)
Data Types: double
Complex Number Support: Yes
5-70
assempde
Subdomain labels, specified as a vector of positive integers. For 2-D geometry only. View
the subdomain labels in your geometry using the command
pdegplot(g,'SubdomainLabels','on')
Output Arguments
u — PDE solution
vector
• If the PDE is scalar, meaning only one equation, then u is a column vector
representing the solution u at each node in the mesh. u(i) is the solution at the ith
column of model.Mesh.Nodes or the ith column of p.
• If the PDE is a system of N > 1 equations, then u is a column vector with N*Np
elements, where Np is the number of nodes in the mesh. The first Np elements of u
represent the solution of equation 1, then next Np elements represent the solution of
equation 2, etc.
To plot the solution, use pdeplot for 2-D geometry, or see “Plot 3-D Solutions and Their
Gradients” on page 3-277.
Kc — Stiffness matrix
sparse matrix
Stiffness matrix, returned as a sparse matrix. See “Elliptic Equations” on page 5-75.
u1 = Kc\Fc returns the solution on the non-Dirichlet points. To obtain the solution u at
the nodes of the mesh,
u = B*(Kc\Fc) + ud
5-71
5 Functions — Alphabetical List
Generally, Kc, Fc, B, and ud make a slower but more accurate solution than Ks and Fs.
Fc — Load vector
vector
u = B*(Kc\Fc) + ud
Generally, Kc, Fc, B, and ud make a slower but more accurate solution than Ks and Fs.
B — Dirichlet nullspace
sparse matrix
u = B*(Kc\Fc) + ud
Generally, Kc, Fc, B, and ud make a slower but more accurate solution than Ks and Fs.
ud — Dirichlet vector
vector
u = B*(Kc\Fc) + ud
Generally, Kc, Fc, B, and ud make a slower but more accurate solution than Ks and Fs.
Finite element matrix for stiff-spring approximation, returned as a sparse matrix. See
“Algorithms” on page 5-75.
u = Ks\Fs.
Generally, Ks and Fs make a quicker but less accurate solution than Kc, Fc, B, and ud.
5-72
assempde
u = Ks\Fs.
Generally, Ks and Fs make a quicker but less accurate solution than Kc, Fc, B, and ud.
K — Stiffness matrix
sparse matrix
Stiffness matrix, returned as a sparse matrix. See “Elliptic Equations” on page 5-75.
K represents the stiffness matrix alone, unlike Kc or Ks, which are stiffness matrices
combined with other terms to enable immediate solution of a PDE.
M — Mass matrix
sparse matrix
Mass matrix. returned as a sparse matrix. See “Elliptic Equations” on page 5-75.
F — Load vector
vector
F represents the load vector alone, unlike Fc or Fs, which are load vectors combined with
other terms to enable immediate solution of a PDE.
5-73
5 Functions — Alphabetical List
Neumann boundary condition vector, returned as a sparse vector. See “Elliptic Equations”
on page 5-75.
H — Dirichlet matrix
sparse matrix
R — Dirichlet vector
sparse vector
Definitions
See “Systems of PDEs” on page 5-84 for details on the approach used to eliminate
Dirichlet conditions.
5-74
assempde
Stiff-Spring Approximation
This form of the finite element matrices converts Dirichlet boundary conditions to
Neumann boundary conditions using a stiff-spring approximation. Using this
approximation, assempde returns a matrix Ks and a vector Fs that represent the
combined finite element matrices. The approximate solution u is u = Ks\Fs.
See “Elliptic Equations” on page 5-75. For details of the stiff-spring approximation, see
“Systems of PDEs” on page 5-84.
Algorithms
Elliptic Equations
Partial Differential Equation Toolbox solves equations of the form
∂ 2u ∂u
m +d - —·( c—u ) + au = f
2 ∂t
∂t
-— ◊ ( c—u ) + au = f
which the documentation calls an elliptic equation, whether or not the equation is elliptic
in the mathematical sense. The equation holds in Ω, where Ω is a bounded domain in two
or three dimensions. c, a, f, and the unknown solution u are complex functions defined on
Ω. c can also be a 2-by-2 matrix function on Ω. The boundary conditions specify a
combination of u and its normal derivative on the boundary:
5-75
5 Functions — Alphabetical List
Our nomenclature deviates slightly from the tradition for potential theory, where a
Neumann condition usually refers to the case q = 0 and our Neumann would be called a
mixed condition. In some contexts, the generalized Neumann boundary conditions is also
referred to as the Robin boundary conditions. In variational calculus, Dirichlet conditions
are also called essential boundary conditions and restrict the trial space. Neumann
conditions are also called natural conditions and arise as necessary conditions for a
solution. The variational form of the Partial Differential Equation Toolbox equation with
Neumann conditions is given below.
1 Describe the geometry of the domain Ω and the boundary conditions. For 2-D
geometry, create geometry using the PDE Modeler app or through MATLAB files. For
3-D geometry, import the geometry in STL file format. See “Geometry”, “STL File
Import” on page 2-47, and “Boundary Conditions”.
2 Build a triangular mesh on the domain Ω. The software has mesh generating and
mesh refining facilities. A mesh is described by three matrices of fixed format that
contain information about the mesh points, the boundary segments, and the
elements.
3 Discretize the PDE and the boundary conditions to obtain a linear system Ku = F. The
unknown vector u contains the values of the approximate solution at the mesh points,
the matrix K is assembled from the coefficients c, a, h, and q and the right-hand side
F contains, essentially, averages of f around each mesh point and contributions from
g. Once the matrices K and F are assembled, you have the entire MATLAB
environment at your disposal to solve the linear system and further process the
solution.
More elaborate applications make use of the Finite Element Method (FEM) specific
information returned by the different functions of the software. Therefore we quickly
summarize the theory and technique of FEM solvers to enable advanced applications to
make full use of the computed quantities.
FEM can be summarized in the following sentence: Project the weak form of the
differential equation onto a finite-dimensional function space. The rest of this section
deals with explaining the preceding statement.
We start with the weak form of the differential equation. Without restricting the
generality, we assume generalized Neumann conditions on the whole boundary, since
Dirichlet conditions can be approximated by generalized Neumann conditions. In the
simple case of a unit matrix h, setting g = qr and then letting q → ∞ yields the Dirichlet
5-76
assempde
condition because division with a very large q cancels the normal derivative terms. The
actual implementation is different, since the preceding procedure may create
conditioning problems. The mixed boundary condition of the system case requires a more
complicated treatment, described in “Systems of PDEs” on page 5-84.
Assume that u is a solution of the differential equation. Multiply the equation with an
arbitrary test function v and integrate on Ω:
Ú ( - (— · c—u ) v + auv) dx = Ú fv dx
W W
W ∂W W
Ú (( c—u) · —v + auv) dx - Ú (- qu + g ) v ds = Ú fv dx
W ∂W W
This equation is called the variational, or weak, form of the differential equation.
Obviously, any solution of the differential equation is also a solution of the variational
problem. The reverse is true under some restrictions on the domain and on the coefficient
functions. The solution of the variational problem is also called the weak solution of the
differential equation.
The solution u and the test functions v belong to some function space V. The next step is
in VN rather than V. The solution of the finite dimensional problem turns out to be the
p
element of VN that lies closest to the weak solution when measured in the energy norm.
p
5-77
5 Functions — Alphabetical List
Np
u( x) = Â U j f j ( x)
j =1
Np
 ÊÁ Ú (( c—f j ) · —fi + af jfi ) dx + Ú qf jfi ds ˆ˜U j = Ú f fi dx + Ú gfi ds, i = 1, ... , N p
j =1 Ë W ∂W ¯ W ∂W
Qi, j = Ú qf jfi ds
∂W
Fi = Ú ffi dx
W
Gi = Ú gfi ds
∂W
5-78
assempde
(K + M + Q)U = F + G. (5-2)
K, M, and Q are Np-by-Np matrices, and F and G are Np-vectors. K, M, and F are produced
by assema, while Q, G are produced by assemb. When it is not necessary to distinguish
K, M, and Q or F and G, we collapse the notations to KU = F, which form the output of
assempde.
When the problem is self-adjoint and elliptic in the usual mathematical sense, the matrix
K + M + Q becomes symmetric and positive definite. Many common problems have these
characteristics, most notably those that can also be formulated as minimization problems.
For the case of a scalar equation, K, M, and Q are obviously symmetric. If c(x) ≥ δ > 0,
a(x) ≥ 0 and q(x) ≥ 0 with q(x) > 0 on some part of ∂Ω, then, if U ≠ 0.
Ú (c u + au2 ) dx +
2
U T ( K + M + Q)U = Ú qu
2
ds > 0, if U π 0
W ∂W
UT(K + M + Q)U is the energy norm. There are many choices of the test-function spaces.
The software uses continuous functions that are linear on each element of a 2-D mesh,
and are linear or quadratic on elements of a 3-D mesh. Piecewise linearity guarantees
that the integrals defining the stiffness matrix K exist. Projection onto VN is nothing
p
more than linear interpolation, and the evaluation of the solution inside an element is
done just in terms of the nodal values. If the mesh is uniformly refined, VN
p
approximates the set of smooth functions on Ω.
A suitable basis for VN p in 2-D is the set of “tent” or “hat” functions ϕi. These are linear
on each element and take the value 0 at all nodes xj except for xi. For the definition of
basis functions for 3-D geometry, see “Finite Element Basis for 3-D” on page 5-87.
Requesting ϕi(xi) = 1 yields the very pleasant property
Np
u ( xi ) = Â U j f j ( x i ) = Ui
j =1
That is, by solving the FEM system we obtain the nodal values of the approximate
solution. The basis function ϕi vanishes on all the elements that do not contain the node
xi. The immediate consequence is that the integrals appearing in Ki,j, Mi,j, Qi,j, Fi and Gi
5-79
5 Functions — Alphabetical List
only need to be computed on the elements that contain the node xi. Secondly, it means
that Ki,j andMi,j are zero unless xi and xj are vertices of the same element and thus K and
M are very sparse matrices. Their sparse structure depends on the ordering of the indices
of the mesh points.
The integrals in the FEM matrices are computed by adding the contributions from each
element to the corresponding entries (i.e., only if the corresponding mesh point is a
vertex of the element). This process is commonly called assembling, hence the name of
the function assempde.
The assembling routines scan the elements of the mesh. For each element they compute
the so-called local matrices and add their components to the correct positions in the
sparse matrices or vectors.
The discussion now specializes to triangular meshes in 2-D. The local 3-by-3 matrices
contain the integrals evaluated only on the current triangle. The coefficients are assumed
constant on the triangle and they are evaluated only in the triangle barycenter. The
integrals are computed using the midpoint rule. This approximation is optimal since it has
the same order of accuracy as the piecewise linear interpolation.
Consider a triangle given by the nodes P1, P2, and P3 as in the following figure.
5-80
assempde
Note The local 3-by-3 matrices contain the integrals evaluated only on the current
triangle. The coefficients are assumed constant on the triangle and they are evaluated
only in the triangle barycenter.
area ( DP1 P2 P3 )
mi, j = Ú a ( Pc ) fi ( x ) f j ( x ) dx = a ( Pc )
12
(1 + d i, j )
DP1 P2 P3
5-81
5 Functions — Alphabetical List
P1 + P2 + P3
Pc =
3
area ( DP1 P2 P3 )
fi = f ( Pc )
3
For the local stiffness matrix we have to evaluate the gradients of the basis functions that
do not vanish on P1P2P3. Since the basis functions are linear on the triangle P1P2P3, the
gradients are constants. Denote the basis functions ϕ1, ϕ2, and ϕ3 such that ϕ(Pi) = 1. If P2
– P3 = [x1,y1]T then we have that
1 È y1 ˘
— f1 = Í ˙
2area ( DP1 P2 P3 ) Î - x1 ˚
1 È y1 ˘
ki, j = ÈÎ y j , - x j ˘˚ c ( Pc ) Í ˙
4 area ( DP1 P2 P3 ) Î- x1 ˚
If two vertices of the triangle lie on the boundary ∂Ω, they contribute to the line integrals
associated to the boundary conditions. If the two boundary points are P1 and P2, then we
have
P1 - P2
Qi, j = q ( Pb ) (1 + di, j ), i, j = 1, 2
6
and
P1 - P2
Gi = g ( Pb ) , i = 1, 2
2
For each triangle the vertices Pm of the local triangle correspond to the indices im of the
mesh points. The contributions of the individual triangle are added to the matrices such
that, e.g.,
5-82
assempde
This is done by the function assempde. The gradients and the areas of the triangles are
computed by the function pdetrg.
The Dirichlet boundary conditions are treated in a slightly different manner. They are
eliminated from the linear system by a procedure that yields a symmetric, reduced
system. The function assempde can return matrices K, F, B, and ud such that the solution
is u = Bv + ud where Kv = F. u is an Np-vector, and if the rank of the Dirichlet conditions
is rD, then v has Np – rD components.
1 Generate the finite element matrices [K,M,F,Q,G,H,R]. This step is equivalent to calling
assema to generate the matrices K, M, and F, and also calling assemb to generate the
matrices Q, G, H, and R.
2 Generate the combined finite element matrices [Kc,Fc,B,ud]. The combined stiffness
matrix is for the reduced linear system, Kc = K + M + Q. The corresponding
combined load vector is Fc = F + G. The B matrix spans the null space of the
columns of H (the Dirichlet condition matrix representing hu = r). The R vector
represents the Dirichlet conditions in Hu = R. The ud vector represents boundary
condition solutions for the Dirichlet conditions.
3 Calculate the solution u via
assempde uses one of two algorithms for assembling a problem into combined finite
element matrix form. A reduced linear system form leads to immediate solution via linear
algebra. You choose the algorithm by the number of outputs. For the reduced linear
system form, request four outputs:
For details, see “Reduced Linear System” on page 5-74 and “Stiff-Spring Approximation”
on page 5-75.
5-83
5 Functions — Alphabetical List
Systems of PDEs
Partial Differential Equation Toolbox software can also handle systems of N partial
differential equations over the domain Ω. We have the elliptic system
-— ◊ ( c ƒ — u ) + au = f
∂u
d - — ◊ ( c ƒ — u ) + au = f
∂t
∂2 u
d - — ◊ ( c ƒ — u ) + au = f
∂ t2
-— ◊ ( c ƒ — u ) + au = l du
For 2-D systems, the notation — ◊ (c ƒ —u ) represents an N-by-1 matrix with an (i,1)-
component
N
Ê ∂ ∂ ∂ ∂ ∂ ∂ ∂ ∂ ˆ
 ÁË ∂x ci, j ,1,1 ∂x + ∂x ci, j ,1,2 ∂y + ∂y ci, j,2,1 ∂x + ∂y ci, j ,2,2 ∂y ˜¯u j
j =1
For 3-D systems, the notation — ◊ (c ƒ —u ) represents an N-by-1 matrix with an (i,1)-
component
5-84
assempde
N
Ê ∂ ∂ ∂ ∂ ∂ ∂ ˆ
 ÁË ∂x ci, j ,1,1 ∂x + ∂x ci, j ,1,2 ∂y + ∂x ci, j,1,3 ∂z ˜¯ u j
j =1
N
Ê ∂ ∂ ∂ ∂ ∂ ∂ ˆ
+  ÁË ∂y ci, j,2,1 ∂x + ∂y ci, j ,2,2 ∂y + ∂y ci, j,2,3 ∂z ˜¯ u j
j =1
N
Ê ∂ ∂ ∂ ∂ ∂ ∂ ˆ
+  ÁË ∂z ci, j ,3,1 ∂x + ∂z ci, j ,3,2 ∂y + ∂z ci, j,3,3 ∂z ˜¯ u j
j =1
The symbols a and d denote N-by-N matrices, and f denotes a column vector of length N.
The elements cijkl, aij, dij, and fi of c, a, d, and f are stored row-wise in the MATLAB
matrices c, a, d, and f. The case of identity, diagonal, and symmetric matrices are
handled as special cases. For the tensor cijkl this applies both to the indices i and j, and to
the indices k and l.
Partial Differential Equation Toolbox software does not check the ellipticity of the
problem, and it is quite possible to define a system that is not elliptic in the mathematical
sense. The preceding procedure that describes the scalar case is applied to each
component of the system, yielding a symmetric positive definite system of equations
whenever the differential system possesses these characteristics.
The boundary conditions now in general are mixed, i.e., for each point on the boundary a
combination of Dirichlet and generalized Neumann conditions,
hu = r
n · ( c ƒ — u ) + qu = g + h ¢m
For 2-D systems, the notation n · ( c ƒ — u ) represents an N-by-1 matrix with (i,1)-
component
N
Ê ∂ ∂ ∂ ∂ ˆ
 ÁË cos(a )ci, j,1,1 ∂x + cos(a)ci, j ,1,2 ∂y + sin(a)ci, j ,2,1 ∂x + sin(a)ci, j,2,2 ∂y ˜¯u j
j =1
5-85
5 Functions — Alphabetical List
For 3-D systems, the notation n · ( c ƒ — u ) represents an N-by-1 matrix with (i,1)-
component
N
Ê ∂ ∂ ∂ ˆ
 ÁË cos(a )ci, j,1,1 ∂x + cos(a)ci, j ,1,2 ∂y + cos(a )ci, j ,1,3 ∂z ˜¯u j
j =1
N
Ê ∂ ∂ ∂ ˆ
+  ÁË cos(b )ci, j ,2,1 ∂x + cos(b )ci, j,2,2 ∂y + cos(b )ci, j,2,3 ∂z ˜¯u j
j =1
N
Ê ∂ ∂ ∂ ˆ
+  ÁË cos(g )ci, j ,3,1 ∂x + cos(g )ci, j,3,2 ∂y + cos (g )ci, j ,3,3 ∂z ˜¯u j
j =1
There are M Dirichlet conditions and the h-matrix is M-by-N, M ≥ 0. The generalized
Neumann condition contains a source h ¢m , where the Lagrange multipliers μ are
computed such that the Dirichlet conditions become satisfied. In a structural mechanics
problem, this term is exactly the reaction force necessary to satisfy the kinematic
constraints described by the Dirichlet conditions.
The rest of this section details the treatment of the Dirichlet conditions and may be
skipped on a first reading.
hu = r (5-6)
5-86
assempde
When this number is increased, hu = r will be more accurately satisfied, but the potential
ill-conditioning of the modified equations will become more serious.
The second method is also applicable to general mixed conditions with nondiagonal h,
and is free of the ill-conditioning, but is more involved computationally. Assume that there
are Np nodes in the mesh. Then the number of unknowns is NpN = Nu. When Dirichlet
boundary conditions fix some of the unknowns, the linear system can be correspondingly
reduced. This is easily done by removing rows and columns when u values are given, but
here we must treat the case when some linear combinations of the components of u are
given, hu = r. These are collected into HU = R where H is an M-by-Nu matrix and R is an
M-vector.
KU +H´ µ = F (5-7)
HU = R. (5-8)
The constraints can be solved for M of the U-variables, the remaining called V, an Nu – M
vector. The null space of H is spanned by the columns of B, and U = BV + ud makes U
satisfy the Dirichlet conditions. A permutation to block-diagonal form exploits the sparsity
of H to speed up the following computation to find B in a numerically stable way. µ can be
eliminated by premultiplying by B´ since, by the construction, HB = 0 or B´H´ = 0. The
reduced system becomes
5-87
5 Functions — Alphabetical List
p4
p1
p2 p3
r s
f1 = 1 - r - s - t
f2 = r
f3 = s
f4 = t
For a quadratic tetrahedron, there are additional nodes at the edge midpoints.
5-88
assempde
p4
p8
p9 p1 p10
p5 p7
p2 p3
p6
r s
2
f1 = 2 ( 1 - r - s - t) - (1 - r - s - t )
f2 = 2r 2 - r
f3 = 2s2 - s
f4 = 2t2 - t
f5 = 4 r ( 1 - r - s - t )
f6 = 4 rs
f7 = 4 s (1 - r - s - t )
f8 = 4t (1 - r - s - t )
f9 = 4 rt
f10 = 4 st
As in the 2-D case, a 3-D basis function ϕi takes the value 0 at all nodes j, except for node
i, where it takes the value 1.
See Also
assembleFEMatrices | solvepde
5-89
5 Functions — Alphabetical List
5-90
BodyLoadAssignment Properties
BodyLoadAssignment Properties
Body load assignments
Description
A BodyLoadAssignment object contains a description of the body loads for a structural
analysis model. A StructuralModel container has a vector of BodyLoadAssignment
objects in its BodyLoads.BodyLoadAssignments property.
To create body load assignments for your structural analysis model, use the
structuralBodyLoad function.
Properties
Properties of BodyLoadAssignment
Region type, returned as 'Face' for a 2-D region or 'Cell' for a 3-D region.
Data Types: char
RegionID — Region ID
vector of positive integers
Acceleration due to gravity, returned as a numeric vector. This property must be specified
in units consistent with the geometry and material properties units.
5-91
5 Functions — Alphabetical List
Example:
structuralBodyLoad(structuralmodel,'GravitationalAcceleration',
[0,0,-9.8])
Data Types: double
See Also
findBodyLoad | structuralBodyLoad
Introduced in R2017b
5-92
BoundaryCondition Properties
BoundaryCondition Properties
Boundary condition for PDE model
Description
A BoundaryCondition object specifies the type of PDE boundary condition on a set of
geometry boundaries. A PDEModel object contains a vector of BoundaryCondition
objects in its BoundaryConditions property.
Properties
Properties
Geometric region type, returned as 'Face' for 3-D geometry or 'Edge' for 2-D
geometry.
Example: applyBoundaryCondition(model,'dirichlet','Face',3,'u',0)
Data Types: char
5-93
5 Functions — Alphabetical List
Geometric region ID, returned as a vector of positive integers. Find the region IDs using
pdegplot with the 'FaceLabels' (3-D) or 'EdgeLabels' (2-D) value set to 'on'.
Example: applyBoundaryCondition(model,'dirichlet','Face',3:6,'u',0)
Data Types: double
Dirichlet condition h*u = r, returned as an N-by-N matrix, a vector with N^2 elements,
or a function handle. N is the number of PDEs in the system. For the syntax of the
function handle form of h, see “Nonconstant Boundary Conditions” on page 2-186.
Example: 'h',[2,1;1,2]
Data Types: double | function_handle
Complex Number Support: Yes
5-94
BoundaryCondition Properties
u — Dirichlet conditions
zeros(N,1) (default) | vector of up to N elements | function handle
For the syntax of the function handle form of u, see “Nonconstant Boundary Conditions”
on page 2-186.
Example: applyBoundaryCondition(model,'dirichlet','Face',[2,4,11],'u',
0)
Data Types: double
Complex Number Support: Yes
Index of the known u components, returned as a vector of integers with entries from 1 to
N. EquationIndex and u must have the same length.
Example: applyBoundaryCondition(model,'mixed','Face',[2,4,11],'u',
[3,-1],'EquationIndex',[2,3])
Data Types: double
Vectorized function evaluation, returned as 'on' or 'off'. This evaluation applies when
you pass a function handle as an argument. To save time in function handle evaluation,
specify 'on', assuming that your function handle computes in a vectorized fashion. See
5-95
5 Functions — Alphabetical List
See Also
PDEModel | applyBoundaryCondition | findBoundaryConditions
Topics
“Specify Boundary Conditions” on page 2-181
“View, Edit, and Delete Boundary Conditions” on page 2-199
“Solve Problems Using PDEModel Objects” on page 2-6
Introduced in R2015a
5-96
CoefficientAssignment Properties
CoefficientAssignment Properties
Coefficient assignments
Description
A CoefficientAssignment object contains a description of the PDE coefficients. A
PDEModel container has a vector of CoefficientAssignment objects in its
EquationCoefficients.CoefficientAssignments property.
∂ 2u ∂u
m +d - —·( c—u ) + au = f
2 ∂t
∂t
- —·( c— u) + au = l du
or
- —·( c— u) + au = l 2mu
Properties
Properties
Region type, returned as 'face' for a 2-D region, or 'cell' for a 3-D region.
Data Types: char
RegionID — Region ID
vector of positive integers
5-97
5 Functions — Alphabetical List
Solution multiplier coefficient, returned as a scalar, column vector, or function handle. For
details of the a coefficient specification, see “m, d, or a Coefficient for specifyCoefficients”
on page 2-149.
Data Types: double | function_handle
5-98
CoefficientAssignment Properties
f — Source coefficient
scalar | column vector | function handle
Source coefficient, returned as a scalar, column vector, or function handle. For details of
the f coefficient specification, see “f Coefficient for specifyCoefficients” on page 2-107.
Data Types: double | function_handle
Complex Number Support: Yes
See Also
findCoefficients | specifyCoefficients
Topics
“PDE Coefficients”
“Solve Problems Using PDEModel Objects” on page 2-6
Introduced in R2016a
5-99
5 Functions — Alphabetical List
createpde
Create model
Syntax
model = createpde(N)
thermalmodel = createpde('thermal',ThermalAnalysisType)
structuralmodel = createpde('structural',StructuralAnalysisType)
Description
model = createpde(N) returns a PDE model object for a system of N equations. A
complete PDE model object contains a description of the problem you want to solve,
including the geometry, mesh, and boundary conditions.
structuralmodel = createpde('structural',StructuralAnalysisType)
returns a structural analysis model for the specified analysis type. This model lets you
solve small-strain linear elasticity problems.
Examples
model = createpde(3)
model =
PDEModel with properties:
PDESystemSize: 3
5-100
createpde
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
thermalmodel =
ThermalModel with properties:
AnalysisType: 'steadystate'
Geometry: []
MaterialProperties: []
5-101
5 Functions — Alphabetical List
HeatSources: []
StefanBoltzmannConstant: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
thermalmodel =
ThermalModel with properties:
AnalysisType: 'transient'
Geometry: []
MaterialProperties: []
HeatSources: []
StefanBoltzmannConstant: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
staticStructural =
StructuralModel with properties:
AnalysisType: 'static-solid'
Geometry: []
MaterialProperties: []
BodyLoads: []
BoundaryConditions: []
ReferenceTemperature: []
Mesh: []
5-102
createpde
transientStructural =
StructuralModel with properties:
AnalysisType: 'transient-planestress'
Geometry: []
MaterialProperties: []
BodyLoads: []
BoundaryConditions: []
DampingModels: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
Create a modal analysis structural model for solving a plane-strain (2-D) problem.
modalStructural = createpde('structural','modal-planestrain')
modalStructural =
StructuralModel with properties:
AnalysisType: 'modal-planestrain'
Geometry: []
MaterialProperties: []
BoundaryConditions: []
Mesh: []
Input Arguments
N — Number of equations
1 (default) | positive integer
Number of equations, specified as a positive integer. You do not need to specify N for a
model where N = 1.
Example: model = createpde
Example: model = createpde(3);
5-103
5 Functions — Alphabetical List
5-104
createpde
Output Arguments
model — PDE model
PDEModel object
See Also
PDEModel | StructuralModel | ThermalModel
Topics
“Solve Problems Using PDEModel Objects” on page 2-6
5-105
5 Functions — Alphabetical List
Introduced in R2015a
5-106
createPDEResults
createPDEResults
Create solution object
Note This page describes the legacy workflow. New features might not be compatible
with the legacy workflow. For the corresponding step in the recommended workflow, see
solvepde and solvepdeeig.
The original (R2015b) version of createPDEResults had only one syntax, and created a
PDEResults object. Beginning with R2016a, you generally do not need to use
createPDEResults, because the solvepde and solvepdeeig functions return solution
objects. Furthermore, createPDEResults returns an object of a newer type than
PDEResults. If you open an existing PDEResults object, it is converted to a
StationaryResults object.
If you use one of the older solvers such as adaptmesh, then you can use
createPDEResults to obtain a solution object. Stationary and time-dependent solution
objects have gradients available, whereas PDEResults did not include gradients.
Syntax
results = createPDEResults(model,u)
results = createPDEResults(model,u,'stationary')
results = createPDEResults(model,u,utimes,'time-dependent')
results = createPDEResults(model,eigenvectors,eigenvalues,'eigen')
Description
results = createPDEResults(model,u) creates a StationaryResults solution
object from model and its solution u.
5-107
5 Functions — Alphabetical List
results = createPDEResults(model,eigenvectors,eigenvalues,'eigen')
creates an EigenResults solution object from model, its eigenvector solution
eigenvectors, and its eigenvalues eigenvalues.
Examples
Create a PDE model for a system of three equations. Import the geometry of a bracket
and plot the face labels.
model = createpde(3);
importGeometry(model,'BracketWithHole.stl');
figure
pdegplot(model,'FaceLabels','on')
view(30,30)
title('Bracket with Face Labels')
5-108
createPDEResults
figure
pdegplot(model,'FaceLabels','on')
view(-134,-32)
title('Bracket with Face Labels, Rear View')
5-109
5 Functions — Alphabetical List
Set boundary conditions: face 3 is immobile, and there is a force in the negative z
direction on face 6.
applyBoundaryCondition(model,'dirichlet','face',4,'u',[0,0,0]);
applyBoundaryCondition(model,'neumann','face',8,'g',[0,0,-1e4]);
5-110
createPDEResults
generateMesh(model,'Hmax',1e-2);
u = assempde(model,c,a,f);
results = createPDEResults(model,u)
results =
StationaryResults with properties:
pdeplot3D(model,'ColorMapData',results.NodalSolution(:,3))
5-111
5 Functions — Alphabetical List
model = createpde();
importGeometry(model,'Tetrahedron.stl');
pdegplot(model,'FaceLabels','on','FaceAlpha',0.5)
view(45,45)
5-112
createPDEResults
Set the temperature on face 2 to 100. Leave the other boundary conditions at their
default values (insulating).
applyBoundaryCondition(model,'dirichlet','face',2,'u',100);
d = 1;
c = 1;
a = 0;
f = 0;
u0 = 0;
Create a mesh and solve the PDE for times from 0 through 200 in steps of 10.
5-113
5 Functions — Alphabetical List
tlist = 0:10:200;
generateMesh(model);
u = parabolic(u0,tlist,model,c,a,f,d);
results = createPDEResults(model,u,tlist,'time-dependent');
pdeplot3D(model,'ColorMapData',results.NodalSolution(:,11))
5-114
createPDEResults
Create the geometry and mesh for the L-shaped membrane. Apply Dirichlet boundary
conditions to all edges.
model = createpde;
geometryFromEdges(model,@lshapeg);
generateMesh(model,'Hmax',0.05,'GeometricOrder','linear');
applyBoundaryCondition(model,'dirichlet','Edge',1:model.Geometry.NumEdges,'u',0);
5-115
5 Functions — Alphabetical List
Solve the eigenvalue problem for coefficients c = 1, a = 0, and d = 1. Obtain solutions for
eigenvalues from 0 through 100.
c = 1;
a = 0;
d = 1;
r = [0,100];
[eigenvectors,eigenvalues] = pdeeig(model,c,a,d,r);
results = createPDEResults(model,eigenvectors,eigenvalues,'eigen')
results =
EigenResults with properties:
pdeplot(model,'XYData',results.Eigenvectors(:,10))
5-116
createPDEResults
Input Arguments
model — PDE model
PDEModel object
u — PDE solution
vector | matrix
5-117
5 Functions — Alphabetical List
Times for a PDE solution, specified as a monotone vector. These times should be the same
as the tlist times that you specified for the solution by the hyperbolic or parabolic
solvers.
Example: utimes = 0:0.2:5;
Output Arguments
results — PDE solution
StationaryResults object (default) | TimeDependentResults object |
EigenResults object
5-118
createPDEResults
Tips
• Dimensions of the returned solutions and gradients are the same as those returned by
solvepde and solvepdeeig. For details, see “Dimensions of Solutions, Gradients,
and Fluxes” on page 3-299.
Algorithms
The procedure for evaluating gradients at nodal locations is as follows:
1 Calculate the gradients at the Gauss points located inside each element.
2 Extrapolate the gradients at the nodal locations.
3 Average the value of the gradient from all elements that meet at the nodal point. This
step is needed because of the inter-element discontinuity of gradients. The elements
that connect at the same nodal point give different extrapolated values of the
gradient for the point. createPDEResults performs area-weighted averaging for 2-
D meshes and volume-weighted averaging for 3-D meshes.
See Also
EigenResults | StationaryResults | TimeDependentResults |
evaluateGradient | interpolateSolution
5-119
5 Functions — Alphabetical List
Topics
“Linear Elasticity Equations” on page 3-98
Introduced in R2015b
5-120
csgchk
csgchk
Check validity of Geometry Description matrix
Syntax
gstat = csgchk(gd,xlim,ylim)
gstat = csgchk(gd)
Description
gstat = csgchk(gd,xlim,ylim) checks if the solid objects in the Geometry
Description matrix gd are valid, given optional real numbers xlim and ylim as current
length of the x- and y-axis, and using a special format for polygons. For a polygon, the last
vertex coordinate can be equal to the first one, to indicate a closed polygon. If xlim and
ylim are specified and if the first and the last vertices are not equal, the polygon is
considered as closed if these vertices are within a certain “closing distance.” These
optional input arguments are meant to be used only when calling csgchk from the PDE
Modeler app.
gstat = csgchk(gd) is identical to the preceding call, except for using the same
format of gd that is used by decsg. This call is recommended when using csgchk as a
command-line function.
gstat is a row vector of integers that indicates the validity status of the corresponding
solid objects, i.e., columns, in gd.
For a circle solid, gstat = 0 indicates that the circle has a positive radius, 1 indicates a
nonpositive radius, and 2 indicates that the circle is not unique.
For a polygon, gstat = 0 indicates that the polygon is closed and does not intersect
itself, i.e., it has a well-defined, unique interior region. 1 indicates an open and non-self-
intersecting polygon, 2 indicates a closed and self-intersecting polygon, and 3 indicates
an open and self-intersecting polygon.
5-121
5 Functions — Alphabetical List
For an ellipse solid, gstat = 0 indicates that the ellipse has positive semiaxes, 1
indicates that at least one of the semiaxes is nonpositive, and 2 indicates that the ellipse
is not unique.
If gstat consists of zero entries only, then gd is valid and can be used as input argument
by decsg.
See Also
decsg
5-122
csgdel
csgdel
Delete borders between minimal regions
Syntax
[dl1,bt1] = csgdel(dl,bt,bl)
[dl1,bt1] = csgdel(dl,bt)
Description
[dl1,bt1] = csgdel(dl,bt,bl) deletes the border segments in the list bl. If the
consistency of the Decomposed Geometry matrix is not preserved by deleting the
elements in the list bl, additional border segments are deleted. Boundary segments
cannot be deleted.
For an explanation of the concepts or border segments, boundary segments, and minimal
regions, see decsg.
dl and dl1 are Decomposed Geometry matrices. For a description of the Decomposed
Geometry matrix, see decsg. The format of the Boolean tables bt and bt1 is also
described in the entry on decsg.
See Also
csgchk | decsg
5-123
5 Functions — Alphabetical List
decsg
Decompose constructive solid geometry into minimal regions
Syntax
dl = decsg(gd,sf,ns)
dl = decsg(gd)
[dl,bt] = decsg( ___ )
Description
dl = decsg(gd,sf,ns) decomposes the geometry description matrix gd into the
geometry matrix dl and returns the minimal regions that satisfy the set formula sf. The
name-space matrix ns is a text matrix that relates the columns in gd to variable names in
sf.
Typically, you draw a geometry in the PDE Modeler app, then export it to the MATLAB
Command Window by selecting Export Geometry Description, Set Formula, Labels
from the Draw menu in the app. The resulting geometry description matrix gd represents
the CSG model. decsg analyzes the model and constructs a set of disjointed minimal
regions bounded by boundary segments and border segments. This set of minimal regions
constitutes the decomposed geometry and allows other Partial Differential Equation
Toolbox functions to work with the geometry.
Alternatively, you can use the decsg function when creating a geometry without using the
app. See “2-D Geometry Creation at Command Line” on page 2-10 for details.
To return all minimal regions (sf corresponds to the union of all shapes in gd), use the
shorter syntax dl = decsg(gd).
[dl,bt] = decsg( ___ ) returns a Boolean table (matrix) that relates the original
shapes to the minimal regions. A column in bt corresponds to the column with the same
index in gd. A row in bt corresponds to the index of a minimal region. You can use bt to
remove boundaries between subdomains.
5-124
decsg
Examples
Create a 2-D geometry in the PDE Modeler app, then export it to the MATLAB workspace
and decompose it to minimal regions by using decsg.
Start the PDE Modeler app and draw a unit circle and a unit square.
pdecirc(0,0,1)
pderect([0 1 0 1])
Export the geometry description matrix, set formula, and name-space matrix to the
MATLAB workspace by selecting the Export Geometry Description option from the
Draw menu.
Decompose the exported geometry into minimal regions. The result is one minimal region
with five edge segments: three circle edge segments and two line edge segments.
dl = decsg(gd,sf,ns)
dl =
2.0000 2.0000 1.0000 1.0000 1.0000
0 0 -1.0000 0.0000 0.0000
1.0000 0 0.0000 1.0000 -1.0000
0 1.0000 -0.0000 -1.0000 1.0000
0 0 -1.0000 0 -0.0000
0 0 1.0000 1.0000 1.0000
1.0000 1.0000 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 1.0000 1.0000 1.0000
View the geometry. Display the edge labels and the subdomain labels.
pdegplot(dl,'EdgeLabels','on','SubdomainLabels','on')
axis equal
5-125
5 Functions — Alphabetical List
For comparison, decompose the same geometry without specifying the set formula sf and
the name-space matrix ns. This syntax returns the union of all shapes in the geometry gd.
dl_all = decsg(gd)
dl_all =
2.0000 2.0000 2.0000 2.0000 1.0000 1.0000 1.0000 1.0000
0 1.0000 1.0000 0 -1.0000 0.0000 1.0000 0.0000
1.0000 1.0000 0 0 0.0000 1.0000 0.0000 -1.0000
0 0 1.0000 1.0000 -0.0000 -1.0000 0 1.0000
0 1.0000 1.0000 0 -1.0000 0 1.0000 -0.0000
3.0000 2.0000 2.0000 3.0000 1.0000 1.0000 3.0000 1.0000
1.0000 0 0 1.0000 0 0 2.0000 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 1.0000 1.0000 1.0000 1.0000
5-126
decsg
pdegplot(dl_all,'EdgeLabels','on','SubdomainLabels','on')
axis equal
Start the PDE Modeler app and draw a unit circle and a unit square.
pdecirc(0,0,1)
pderect([0 1 0 1])
Export the Geometry Description matrix, set formula, and Name Space matrix to the
MATLAB workspace by selecting the Export Geometry Description option from the
Draw menu.
5-127
5 Functions — Alphabetical List
Decompose the exported geometry into minimal regions. Because the geometry is a union
of all regions, C1+SQ1, you can omit the arguments specifying the set formula and name-
space matrix when using decsg.
[dl,bt] = decsg(gd)
dl =
2.0000 2.0000 2.0000 2.0000 1.0000 1.0000 1.0000 1.0000
0 1.0000 1.0000 0 -1.0000 0.0000 1.0000 0.0000
1.0000 1.0000 0 0 0.0000 1.0000 0.0000 -1.0000
0 0 1.0000 1.0000 -0.0000 -1.0000 0 1.0000
0 1.0000 1.0000 0 -1.0000 0 1.0000 -0.0000
3.0000 2.0000 2.0000 3.0000 1.0000 1.0000 3.0000 1.0000
1.0000 0 0 1.0000 0 0 2.0000 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 1.0000 1.0000 1.0000 1.0000
bt =
1 0
0 1
1 1
View the geometry. Display the edge labels and the subdomain labels.
pdegplot(dl,'EdgeLabels','on','SubdomainLabels','on')
axis equal
5-128
decsg
[dl2,bt2] = csgdel(dl,bt);
figure
pdegplot(dl2,'EdgeLabels','on','SubdomainLabels','on')
axis equal
5-129
5 Functions — Alphabetical List
Input Arguments
gd — Geometry description matrix
matrix of double-precision numbers
• For a circle, the first row contains 1. The second and third rows contain the x- and y-
coordinates of the center. The fourth row contains the radius of the circle.
• For a polygon, the first row contains 2. The second row contains n, which is the
number of line segments in the boundary of the polygon. The next n rows contain the
5-130
decsg
x-coordinates of the starting points of the edges, and the n rows after that contain the
y-coordinates of the starting points of the edges.
• For a rectangle, the first row contains 3, and the second row contains 4. The next four
rows contain the x-coordinates of the starting points of the edges, and the four rows
after that contain the y-coordinates of the starting points of the edges.
• For an ellipse, the first row contains 4. The second and third rows contain the x- and y-
coordinates of the center. The fourth and fifth rows contain the semiaxes of the ellipse.
The sixth row contains the rotational angle of the ellipse, measured in radians.
All shapes in a geometry description matrix have the same number of rows. Rows that are
not required for a particular shape are filled with zeros.
When you export geometry from the PDE Modeler app by selecting Export Geometry
Description, Set Formula, Labels from the Draw menu in the app, you can use any
variable name for the exported geometry description matrix in the MATLAB workspace.
The default name is gd.
Data Types: double
sf — Set formula
character vector | string scalar
Set formula, specified as a character vector or a string including the names of shapes,
such as C1, SQ2, E3, and the operators +, *, and - corresponding to the set operations
union, intersection, and set difference, respectively. The operators + and * have the same
precedence. The operator - has a higher precedence. You can control the precedence by
using parentheses.
When you export geometry from the PDE Modeler app by selecting Export Geometry
Description, Set Formula, Labels from the Draw menu in the app, you can use any
variable name for the formula in the MATLAB workspace. The default name is sf.
Example: '(SQ1+C1)-C2'
Data Types: char | string
ns — Name-space matrix
matrix of double-precision numbers
5-131
5 Functions — Alphabetical List
column assigns a name to the corresponding geometric object in gd, so you can refer to a
specific object in gd in the set formula sf.
When you export geometry from the PDE Modeler app by selecting Export Geometry
Description, Set Formula, Labels from the Draw menu in the app, you can use any
variable name for the name-space matrix in the MATLAB workspace. The default name is
ns.
Data Types: double
Output Arguments
dl — Decomposed geometry matrix
matrix of double-precision numbers
• For circle edge segments, the first row is 1. The eighth and ninth rows contain the
coordinates of the center of the circle. The 10th row contains the radius.
• For line edge segments, the first row is 2.
• For ellipse edge segments, the first row is 4. The eighth and ninth rows contain the
coordinates of the center of the ellipse. The 10th and 11th rows contain the semiaxes
of the ellipse. The 12th row contains the rotational angle of the ellipse.
All shapes in a decomposed geometry matrix have the same number of rows. Rows that
are not required for a particular shape are filled with zeros.
5-132
decsg
Boolean table relating the original shapes to the minimal regions, returned as a matrix of
1s and 0s.
Data Types: double
5-133
5 Functions — Alphabetical List
Limitations
• In rare cases decsg can error or create an invalid geometry because of the limitations
of its algorithm. Such issues can occur when two or more edges of a geometry
partially overlap, almost coincide, or are almost tangent.
Tips
• decsg does not check the input CSG model for correctness. It assumes that no circles
or ellipses are identical or degenerated and that no lines have zero length. Polygons
must not be self-intersecting. Use the function csgchk to check the CSG model.
• decsg returns NaN if it cannot evaluate the set formula sf.
See Also
PDE Modeler | csgchk | csgdel | geometryFromEdges | pdecirc | pdeellip |
pdepoly | pderect | wgeom
Topics
“2-D Geometry Creation at Command Line” on page 2-10
“Three Ways to Create 2-D Geometry” on page 2-8
5-134
DiscreteGeometry Properties
DiscreteGeometry Properties
3-D geometry description
Description
DiscreteGeometry describes 3-D geometry in the form of an object. A PDEModel object
has a Geometry property. For 3-D geometry, the Geometry property is a
DiscreteGeometry object.
Properties
Properties
5-135
5 Functions — Alphabetical List
See Also
PDEModel | geometryFromMesh | importGeometry | multicuboid | multicylinder
| multisphere
Topics
“Solve Problems Using PDEModel Objects” on page 2-6
Introduced in R2015a
5-136
dstidst
dstidst
(Not recommended) Discrete sine transform
Syntax
y = dst(x)
y = dst(x,n)
x = idst(y)
x = idst(y,n)
Description
The dst function implements the following equation:
N
Ê kn ˆ
y( k) =  x(n) sin ÁË p N + 1 ˜¯, k = 1,..., N
n =1
y = dst(x) computes the discrete sine transform of the columns of x. For best
performance speed, the number of rows in x should be 2m – 1, for some integer m.
N
2 Ê kn ˆ
x(k) = Â
N + 1 n=1
y( n) sin Á p
Ë N
˜, k = 1,..., N
+ 1¯
x = idst(y) calculates the inverse discrete sine transform of the columns of y. For best
performance speed, the number of rows in y should be 2m – 1, for some integer m.
5-137
5 Functions — Alphabetical List
5-138
EigenResults
EigenResults
PDE eigenvalue solution and derived quantities
Description
An EigenResults object contains the solution of a PDE eigenvalue problem in a form
convenient for plotting and postprocessing.
Creation
There are several ways to create an EigenResults object:
• Solve an eigenvalue problem using the solvepdeeig function. This function returns a
PDE eigenvalue solution as an EigenResults object. This is the recommended
approach.
• Solve an eigenvalue problem using the pdeeig function. Then use the
createPDEResults function to obtain an EigenResults object from a PDE
eigenvalue solution returned by pdeeig. Note that pdeeig is a legacy function. It is
not recommended for solving eigenvalue problems.
Properties
Mesh — Finite element mesh
FEMesh object
5-139
5 Functions — Alphabetical List
Solution eigenvectors, returned as a matrix or 3-D array. The solution is a matrix for
scalar eigenvalue problems, and a 3-D array for eigenvalue systems. For details, see
“Dimensions of Solutions, Gradients, and Fluxes” on page 3-299.
Data Types: double
Solution eigenvalues, returned as a vector. The vector is in order by the real part of the
eigenvalues from smallest to largest.
Data Types: double
Object Functions
interpolateSolution Interpolate PDE solution to arbitrary points
Examples
Create the geometry for the L-shaped membrane. Apply zero Dirichlet boundary
conditions to all edges.
model = createpde;
geometryFromEdges(model,@lshapeg);
applyBoundaryCondition(model,'dirichlet','Edge',1:model.Geometry.NumEdges,'u',0);
specifyCoefficients(model,'m',0,'d',1,'c',1,'a',0,'f',0);
Create the mesh and solve the eigenvalue problem for eigenvalues from 0 through 100.
generateMesh(model,'Hmax',0.05);
ev = [0,100];
results = solvepdeeig(model,ev)
5-140
EigenResults
5-141
5 Functions — Alphabetical List
results =
EigenResults with properties:
pdeplot(model,'XYData',results.Eigenvectors(:,10))
5-142
EigenResults
See Also
StationaryResults | TimeDependentResults | solvepdeeig
Topics
“Eigenvalues and Eigenmodes of the L-Shaped Membrane” on page 3-233
“Eigenvalues and Eigenmodes of a Square” on page 3-244
“Solve Problems Using PDEModel Objects” on page 2-6
Introduced in R2016a
5-143
5 Functions — Alphabetical List
evaluate
Package: pde
Note This function supports the legacy workflow. Using the [p,e,t] representation of
FEMesh data is not recommended. Use interpolateSolution and
evaluateGradient to interpolate a PDE solution and its gradient to arbitrary points
without switching to a [p,e,t] representation.
Syntax
uOut = evaluate(F,pOut)
uOut = evaluate(F,x,y)
uOut = evaluate(F,x,y,z)
Description
uOut = evaluate(F,pOut) returns the interpolated values from the interpolant F at
the points pOut.
Note If a query point is outside the mesh, evaluate returns NaN for that point.
uOut = evaluate(F,x,y) returns the interpolated values from the interpolant F at the
points [x(k),y(k)], for k from 1 through numel(x). This syntax applies to 2-D
geometry.
5-144
evaluate
Examples
This example shows how to interpolate a solution to a scalar problem using a pOut matrix
of values.
Solve the equation on the unit disk with zero Dirichlet conditions.
g0 = [1;0;0;1]; % circle centered at (0,0) with radius 1
sf = 'C1';
g = decsg(g0,sf,sf'); % decomposed geometry matrix
problem = allzerobc(g); % zero Dirichlet conditions
[p,e,t] = initmesh(g);
c = 1;
a = 0;
f = 1;
u = assempde(problem,p,e,t,c,a,f); % solve the PDE
Generate a random set of coordinates in the unit square. Evaluate the interpolated
solution at the random points.
rng default % for reproducibility
pOut = rand(2,25); % 25 numbers between 0 and 1
uOut = evaluate(F,pOut);
numNaN = sum(isnan(uOut))
numNaN = 9
uOut contains some NaN entries because some points in pOut are outside of the unit disk.
Interpolate to x, y values
This example shows how to interpolate a solution to a scalar problem using x, y values.
Solve the equation on the unit disk with zero Dirichlet conditions.
5-145
5 Functions — Alphabetical List
Evaluate the interpolated solution at grid points in the unit square with spacing 0.2.
[x,y] = meshgrid(0:0.2:1);
uOut = evaluate(F,x,y);
numNaN = sum(isnan(uOut))
numNaN = 12
uOut contains some NaN entries because some points in the unit square are outside of the
unit disk.
Solve the system of equations with Dirichlet boundary conditions on the unit
disk, where
5-146
evaluate
c = 1;
a = 0;
f = char('sin(x) + cos(y)','cosh(x.*y)','x.*y./(1+x.^2+y.^2)');
u = assempde(problem,p,e,t,c,a,f); % solve the PDE
s = linspace(0,2*pi);
x = 0.5 + 0.4*cos(s);
y = 0.4*sin(s);
uOut = evaluate(F,x,y);
npts = length(x);
plot3(x,y,uOut(1:npts),'b')
hold on
plot3(x,y,uOut(npts+1:2*npts),'k')
plot3(x,y,uOut(2*npts+1:end),'r')
hold off
view(35,35)
5-147
5 Functions — Alphabetical List
on the unit disk with zero Dirichlet conditions and zero initial conditions. Solve at five
times from 0 to 1.
5-148
evaluate
52 successful steps
0 failed attempts
106 function evaluations
1 partial derivatives
13 LU decompositions
105 solutions of linear systems
F = pdeInterpolant(p,t,u);
x = 0.1;
y = -0.1;
uOut = evaluate(F,x,y)
uOut = 1×5
Interpolate to a Grid
5-149
5 Functions — Alphabetical List
Use the built-in geometry functions to create an L-shaped region with zero Dirichlet
boundary conditions. Solve an elliptic PDE with coefficients , , , with
zero Dirichlet boundary conditions.
[p,e,t] = initmesh('lshapeg'); % Predefined geometry
u = assempde('lshapeb',p,e,t,1,0,1); % Predefined boundary condition
Create an Interpolant
xgrid = -1:0.1:1;
ygrid = -1:0.2:1;
[X,Y] = meshgrid(xgrid,ygrid);
The resulting grid has some points that are outside the L-shaped region.
uout = evaluate(F,X,Y);
The interpolated solution uout is a column vector. You can reshape it to match the size of
X or Y. This gives a matrix, like the output of the tri2grid function.
Z = reshape(uout,size(X));
Input Arguments
F — Interpolant
output of pdeInterpolant
5-150
evaluate
Query points, specified as a matrix with two or three rows. The first row represents the x
component of the query points, the second row represents the y component, and, for 3-D
geometry, the third row represents the z component. evaluate computes the interpolant
at each column of pOut. In other words, evaluate interpolates at the points pOut(:,k).
Example: pOut = [-1.5,0,1;
1,1,2.2]
Data Types: double
evaluate transforms query point components to the linear index representation, such as
x(:).
Example: x = -1:0.2:3
Data Types: double
evaluate transforms query point components to the linear index representation, such as
y(:).
Example: y = -1:0.2:3
Data Types: double
5-151
5 Functions — Alphabetical List
evaluate transforms query point components to the linear index representation, such as
z(:).
Example: z = -1:0.2:3
Data Types: double
Output Arguments
uOut — Interpolated values
array
Interpolated values, returned as an array. uOut has the same number of columns as the
data u used in creating F. If u depends on time, uOut contains a column for each time
step. For time-independent u, uOut has one column.
The number of rows in uOut is the number of equations in the PDE system, N, times the
number of query points, pOut. The first pOut rows correspond to equation 1, the next
pOut rows correspond to equation 2, and so on.
If a query point is outside the mesh, evaluate returns NaN for that point.
Definitions
Element
An element is a basic unit in the finite-element method.
For 3-D problems, an element is a tetrahedron with either four or ten points. A four-point
(linear) tetrahedron has nodes only at its corners. A ten-point (quadratic) tetrahedron has
nodes at its corners and at the center point of each edge.
5-152
evaluate
Algorithms
For each point where a solution is requested (pOut), there are two steps in the
interpolation process. First, the element containing the point must be located and second,
interpolation within that element must be performed using the element shape functions
and the values of the solution at the element’s node points.
See Also
pdeInterpolant
Topics
“Mesh Data” on page 2-241
Introduced in R2014b
5-153
5 Functions — Alphabetical List
evaluateCGradient
Package: pde
Syntax
[cgradx,cgrady] = evaluateCGradient(results,xq,yq)
[cgradx,cgrady,cgradz] = evaluateCGradient(results,xq,yq,zq)
[ ___ ] = evaluateCGradient(results,querypoints)
[cgradx,cgrady] = evaluateCGradient(results)
[cgradx,cgrady,cgradz] = evaluateCGradient(results)
Description
[cgradx,cgrady] = evaluateCGradient(results,xq,yq) returns the flux of PDE
solution for the stationary equation at the 2-D points specified in xq and yq. The flux of
the solution is the tensor product of c-coefficient and gradients of the PDE solution,
c ƒ —u .
[cgradx,cgrady,cgradz] = evaluateCGradient(results,xq,yq,zq) returns
the flux of PDE solution for the stationary equation at the 3-D points specified in xq, yq,
and zq.
[ ___ ] = evaluateCGradient( ___ ,iU) returns the flux of the solution of the PDE
system for equation indices (components) iU. When evaluating flux for a system of PDEs,
specify iU after the input arguments in any of the previous syntaxes.
5-154
evaluateCGradient
The first dimension of cgradx, cgrady, and, in the 3-D case, cgradz corresponds to
query points. The second dimension corresponds to equation indices iU.
[ ___ ] = evaluateCGradient( ___ ,iT) returns the flux of PDE solution for the time-
dependent equation or system of time-dependent equations at times iT. When evaluating
flux for a time-dependent PDE, specify iT after the input arguments in any of the previous
syntaxes. For a system of time-dependent PDEs, specify both equation indices
(components) iU and time indices iT.
The first dimension of cgradx, cgrady, and, in the 3-D case, cgradz corresponds to
query points. For a single time-dependent PDE, the second dimension corresponds to
time-steps iT. For a system of time-dependent PDEs, the second dimension corresponds
to equation indices iU, and the third dimension corresponds to time-steps iT.
Examples
Solve the problem on the L-shaped membrane with zero Dirichlet boundary
conditions. Evaluate the tensor product of c-coefficient and gradients of the solution to a
scalar elliptic problem at nodal and arbitrary locations. Plot the results.
5-155
5 Functions — Alphabetical List
model = createpde;
geometryFromEdges(model,@lshapeg);
pdegplot(model,'FaceLabels','on')
applyBoundaryCondition(model,'dirichlet','Edge',1:model.Geometry.NumEdges,'u',0);
specifyCoefficients(model,'m',0,'d',0,'c',10,'a',0,'f',1,'Face',1);
specifyCoefficients(model,'m',0,'d',0,'c',5,'a',0,'f',1,'Face',2);
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',0,'f',1,'Face',3);
5-156
evaluateCGradient
generateMesh(model,'Hmax',0.05);
results = solvepde(model);
u = results.NodalSolution;
[cgradx,cgrady] = evaluateCGradient(results);
figure
pdeplot(model,'XYData',u,'Contour','on','FlowData',[cgradx,cgrady])
Compute the flux of the solution on the grid from -1 to 1 in each direction using the query
points matrix.
5-157
5 Functions — Alphabetical List
v = linspace(-1,1,37);
[X,Y] = meshgrid(v);
querypoints = [X(:),Y(:)]';
[cgradxq,cgradyq] = evaluateCGradient(results,querypoints);
Alternatively, you can specify the query points as X,Y instead of specifying them as a
matrix.
[cgradxq,cgradyq] = evaluateCGradient(results,X,Y);
figure
quiver(X(:),Y(:),cgradxq,cgradyq)
xlabel('x')
ylabel('y')
5-158
evaluateCGradient
N = 3;
model = createpde(N);
importGeometry(model,'SquareBeam.STL');
pdegplot(model,'FaceLabels','on')
5-159
5 Functions — Alphabetical List
E = 2.1e11;
nu = 0.3;
c = elasticityC3D(E, nu);
a = 0;
f = [0;0;0];
specifyCoefficients(model,'m',0,'d',0,'c',c,'a',a','f',f);
applyBoundaryCondition(model,'dirichlet','Face',6,'u',[0 0 0]);
applyBoundaryCondition(model,'neumann','Face',5,'g',[0,0,-3e3]);
5-160
evaluateCGradient
generateMesh(model,'Hmax',25,'GeometricOrder','quadratic');
results = solvepde(model);
Compute stress, that is, the product of c-coefficient and gradients of displacement.
[sig_xx,sig_yy,sig_zz] = evaluateCGradient(results);
Plot normal component of stress along x-direction. The top portion of the beam
experiences tension, and the bottom portion experiences compression.
figure
pdeplot3D(model,'ColorMapData',sig_xx(:,1))
Define a line across the beam from the bottom to the top at mid-span and mid-width.
Compute stresses along the line.
5-161
5 Functions — Alphabetical List
[sig_xx,sig_xy,sig_xz] = evaluateCGradient(results,xg,yg,zg,1);
figure
plot(sig_xx,zg)
grid on
xlabel('\sigma_{xx}')
ylabel('z')
5-162
evaluateCGradient
Compute stresses in an idealized 3-D mechanical part under an applied load. First, create
a PDE model for this problem.
N = 3;
model = createpde(N);
importGeometry(model,'BracketWithHole.stl');
figure
pdegplot(model,'FaceLabels','on')
view(30,30)
title('Bracket with Face Labels')
5-163
5 Functions — Alphabetical List
figure
pdegplot(model,'FaceLabels','on')
view(-134,-32)
title('Bracket with Face Labels, Rear View')
5-164
evaluateCGradient
applyBoundaryCondition(model,'dirichlet','Face',4,'u',[0,0,0]);
distributedLoad = 1e4; % Applied load in Pascals
applyBoundaryCondition(model,'neumann','Face',8,'g',[0,0,-distributedLoad]);
5-165
5 Functions — Alphabetical List
result = solvepde(model);
Create a grid. For this grid, compute the stress tensor, which is the product of c-
coefficient and gradients of displacement.
v = linspace(0,0.2,21);
[xq,yq,zq] = meshgrid(v);
[cgradx,cgrady,cgradz] = evaluateCGradient(result);
sxx = cgradx(:,1);
sxy = cgradx(:,2);
sxz = cgradx(:,3);
syx = cgrady(:,1);
syy = cgrady(:,2);
syz = cgrady(:,3);
szx = cgradz(:,1);
szy = cgradz(:,2);
szz = cgradz(:,3);
Plot von Mises stress. The maximum stress occurs at the weakest section. This section
has the least material to support the applied load.
pdeplot3D(model,'colormapdata',sVonMises)
5-166
evaluateCGradient
Solve a 2-D transient heat transfer problem on a square domain and compute heat flow
across convective boundary.
numberOfPDE = 1;
model = createpde(numberOfPDE);
5-167
5 Functions — Alphabetical List
g = @squareg;
geometryFromEdges(model,g);
pdegplot(model,'EdgeLabels','on')
xlim([-1.2,1.2])
ylim([-1.2,1.2])
axis equal
rho = 7800;
cp = 500;
k = 100;
Text = 25;
hext = 5000;
5-168
evaluateCGradient
Specify the coefficients. Apply insulated boundary conditions on three edges and the free
convection boundary condition on the right edge.
specifyCoefficients(model,'m',0,'d',rho*cp,'c',k,'a',0,'f',0);
applyBoundaryCondition(model,'neumann','Edge', [1,3,4],'q',0,'g',0);
applyBoundaryCondition(model,'neumann','Edge', 2,'q',hext,'g',Text*hext);
Set the initial conditions: uniform room temperature across domain and higher
temperature on the left edge.
setInitialConditions(model,25);
setInitialConditions(model, 100, 'Edge', 4);
Generate a mesh and solve the problem using 0:1000:200000 as a vector of times.
generateMesh(model);
tlist = 0:1000:200000;
results = solvepde(model,tlist);
yg = -1:0.1:1;
xg = ones(size(yg));
[qx,qy] = evaluateCGradient(results,xg,yg,1:length(tlist));
HeatFlowX(1:length(tlist)) = -trapz(yg,qx(:,1:length(tlist)));
figure
plot(tlist,HeatFlowX)
title('Heat flow across convection boundary')
xlabel('Time')
ylabel('Heat flow')
5-169
5 Functions — Alphabetical List
Solve the heat transfer problem for the following 2-D geometry consisting of a square and
a diamond made of different materials. Compute the heat flux density and plot it as a
vector field.
5-170
evaluateCGradient
geometryFromEdges(model,dl);
pdegplot(model,'EdgeLabels','on','FaceLabels','on')
xlim([-1.5,4.5])
ylim([-0.5,3.5])
axis equal
5-171
5 Functions — Alphabetical List
rho_sq = 2;
C_sq = 0.1;
k_sq = 10;
Q_sq = 0;
h_sq = 0;
rho_d = 1;
C_d = 0.1;
k_d = 2;
Q_d = 4;
h_d = 0;
Specify the coefficients for both subdomains. Apply the boundary and initial conditions.
specifyCoefficients(model,'m',0,'d',rho_sq*C_sq,'c',k_sq,'a',h_sq,'f',Q_sq,'Face',1);
specifyCoefficients(model,'m',0,'d',rho_d*C_d,'c',k_d,'a',h_d,'f',Q_d,'Face',2);
applyBoundaryCondition(model,'dirichlet','Edge',[1,2,7,8],'h',1,'r',0);
setInitialConditions(model,0);
Mesh the geometry and solve the problem. To capture the most dynamic part of heat
distribution process, solve the problem using logspace(-2,-1,10) as a vector of times.
generateMesh(model);
tlist = logspace(-2,-1,10);
results = solvepde(model,tlist);
u = results.NodalSolution;
Compute the heat flux density. Plot the solution with isothermal lines using a contour plot,
and plot the heat flux vector field using arrows. The direction of the heat flow (from
higher to lower temperatures) is opposite to the direction of . Therefore, use -
cgradx and -cgrady to show the heat flow.
[cgradx,cgrady] = evaluateCGradient(results);
figure
pdeplot(model,'XYData',u(:,10),'Contour','on','FlowData',[-cgradx(:,10),-cgrady(:,10)],
5-172
evaluateCGradient
Input Arguments
results — PDE solution
StationaryResults object | TimeDependentResults object
5-173
5 Functions — Alphabetical List
evaluateCGradient converts query points to column vectors xq(:), yq(:), and (if
present) zq(:). For a single stationary PDE, the result consists of column vectors of the
same size. To ensure that the dimensions of the returned x-, y-, and z-components are
consistent with the dimensions of the original query points, use reshape. For example,
use cgradx = reshape(cgradx,size(xq)).
For a time-dependent PDE or a system of PDEs, the first dimension of the resulting arrays
corresponds to spatial points specified by the column vectors xq(:), yq(:), and (if
present) zq(:).
Data Types: double
evaluateCGradient converts query points to column vectors xq(:), yq(:), and (if
present) zq(:). For a single stationary PDE, the result consists of column vectors of the
same size. To ensure that the dimensions of the returned x-, y-, and z-components are
consistent with the dimensions of the original query points, use reshape. For example,
use cgrady = reshape(cgrady,size(yq)).
For a time-dependent PDE or a system of PDEs, the first dimension of the resulting arrays
corresponds to spatial points specified by the column vectors xq(:), yq(:), and (if
present) zq(:).
Data Types: double
5-174
evaluateCGradient
For a time-dependent PDE or a system of PDEs, the first dimension of the resulting arrays
corresponds to spatial points specified by the column vectors xq(:), yq(:), and (if
present) zq(:).
Data Types: double
Query points, specified as a real matrix with either two rows for 2-D geometry or three
rows for 3-D geometry. evaluateCGradient evaluates the tensor product of c-
coefficient and gradients of the PDE solution at the coordinate points
querypoints(:,i), so each column of querypoints contains exactly one 2-D or 3-D
query point.
Example: For 2-D geometry, querypoints = [0.5,0.5,0.75,0.75; 1,2,0,0.5]
Data Types: double
iT — Time indices
vector of positive integers
Time indices, specified as a vector of positive integers. Each entry in iT specifies a time
index.
Example: iT = 1:5:21 specifies every fifth time-step up to 21.
Data Types: double
iU — Equation indices
vector of positive integers
5-175
5 Functions — Alphabetical List
Example: iU = [1,5] specifies the indices for the first and fifth equations.
Data Types: double
Output Arguments
cgradx — x-component of the flux of the PDE solution
array
x-component of the flux of the PDE solution, returned as an array. The first array
dimension represents the node index. If results is a StationaryResults object, the
second array dimension represents the equation index for a system of PDEs. If results
is a TimeDependentResults object, the second array dimension represents either the
time-step for a single PDE or the equation index for a system of PDEs. The third array
dimension represents the time-step index for a system of time-dependent PDEs. For
information about the size of cgradx, see “Dimensions of Solutions, Gradients, and
Fluxes” on page 3-299.
For query points that are outside the geometry, cgradx = NaN.
y-component of the flux of the PDE solution, returned as an array. The first array
dimension represents the node index. If results is a StationaryResults object, the
second array dimension represents the equation index for a system of PDEs. If results
is a TimeDependentResults object, the second array dimension represents either the
time-step for a single PDE or the equation index for a system of PDEs. The third array
dimension represents the time-step index for a system of time-dependent PDEs. For
information about the size of cgrady, see “Dimensions of Solutions, Gradients, and
Fluxes” on page 3-299.
For query points that are outside the geometry, cgrady = NaN.
z-component of the flux of the PDE solution, returned as an array. The first array
dimension represents the node index. If results is a StationaryResults object, the
second array dimension represents the equation index for a system of PDEs. If results
is a TimeDependentResults object, the second array dimension represents either the
5-176
evaluateCGradient
time-step for a single PDE or the equation index for a system of PDEs. The third array
dimension represents the time-step index for a system of time-dependent PDEs. For
information about the size of cgradz, see “Dimensions of Solutions, Gradients, and
Fluxes” on page 3-299.
For query points that are outside the geometry, cgradz = NaN.
Tips
• While the results object contains the solution and its gradient (both calculated at
the nodal points of the triangular or tetrahedral mesh), it does not contain the flux of
the PDE solution. To compute the flux at the nodal locations, call
evaluateCGradient without specifying locations. By default, evaluateCGradient
uses nodal locations.
See Also
PDEModel | StationaryResults | TimeDependentResults | evaluateGradient |
interpolateSolution
Topics
“Deflection Analysis of Bracket”
“Dynamics of Damped Cantilever Beam”
“Heat Transfer Between Two Squares Made of Different Materials: PDE Modeler App” on
page 3-130
Introduced in R2016b
5-177
5 Functions — Alphabetical List
evaluateGradient
Package: pde
Syntax
[gradx,grady] = evaluateGradient(results,xq,yq)
[gradx,grady,gradz] = evaluateGradient(results,xq,yq,zq)
[ ___ ] = evaluateGradient(results,querypoints)
Description
[gradx,grady] = evaluateGradient(results,xq,yq) returns the interpolated
values of gradients of the PDE solution results at the 2-D points specified in xq and yq.
The first dimension of gradx, grady, and, in 3-D case, gradz corresponds to query
points. The second dimension corresponds to equation indices iU.
5-178
evaluateGradient
times iT. When evaluating gradient for a time-dependent PDE, specify iT after the input
arguments in any of the previous syntaxes. For a system of time-dependent equations,
specify both time indices iT and equation indices (components) iU.
The first dimension of gradx, grady, and, in 3-D case, gradz corresponds to query
points. For a single time-dependent PDE, the second dimension corresponds to time-steps
iT. For a system of time-dependent PDEs, the second dimension corresponds to equation
indices iU, and the third dimension corresponds to time-steps iT.
Examples
Evaluate gradients of the solution to a scalar elliptic problem along a line. Plot the
results.
Create the solution to the problem on the L-shaped membrane with zero
Dirichlet boundary conditions.
model = createpde;
geometryFromEdges(model,@lshapeg);
applyBoundaryCondition(model,'dirichlet','Edge',1:model.Geometry.NumEdges,'u',0);
specifyCoefficients(model,'m',0,...
'd',0,...
'c',1,...
'a',0,...
'f',1);
generateMesh(model,'Hmax',0.05);
results = solvepde(model);
Evaluate gradients of the solution along the straight line from (x,y)=(-1,-1) to (1,1).
Plot the results as a quiver plot by using quiver.
xq = linspace(-1,1,101);
yq = xq;
[gradx,grady] = evaluateGradient(results,xq,yq);
gradx = reshape(gradx,size(xq));
grady = reshape(grady,size(yq));
5-179
5 Functions — Alphabetical List
quiver(xq,yq,gradx,grady)
xlabel('x')
ylabel('y')
Calculate gradients for the mean exit time of a Brownian particle from a region that
contains absorbing (escape) boundaries and reflecting boundaries. Use the Poisson's
equation with constant coefficients and 3-D rectangular block geometry to model this
problem.
5-180
evaluateGradient
model = createpde;
importGeometry(model,'Block.stl');
applyBoundaryCondition(model,'dirichlet','Face',[1,2,5],'u',0);
specifyCoefficients(model,'m',0,...
'd',0,...
'c',1,...
'a',0,...
'f',2);
generateMesh(model);
results = solvepde(model);
[X,Y,Z] = meshgrid(1:16:100,1:6:20,1:7:50);
[gradx,grady,gradz] = evaluateGradient(results,X,Y,Z);
Reshape the gradients to the shape of the grid and plot the gradients.
gradx = reshape(gradx,size(X));
grady = reshape(grady,size(Y));
gradz = reshape(gradz,size(Z));
quiver3(X,Y,Z,gradx,grady,gradz)
axis equal
xlabel('x')
ylabel('y')
zlabel('z')
5-181
5 Functions — Alphabetical List
Solve a scalar elliptic problem and interpolate gradients of the solution to a dense grid.
Use a query matrix to specify the grid.
Create the solution to the problem on the L-shaped membrane with zero
Dirichlet boundary conditions.
model = createpde;
geometryFromEdges(model,@lshapeg);
applyBoundaryCondition(model,'dirichlet','Edge',1:model.Geometry.NumEdges,'u',0);
5-182
evaluateGradient
specifyCoefficients(model,'m',0,...
'd',0,...
'c',1,...
'a',0,...
'f',1);
generateMesh(model,'Hmax',0.05);
results = solvepde(model);
Interpolate gradients of the solution to the grid from -1 to 1 in each direction. Plot the
result using the quiver plotting function.
v = linspace(-1,1,101);
[X,Y] = meshgrid(v);
querypoints = [X(:),Y(:)]';
[gradx,grady] = evaluateGradient(results,querypoints);
quiver(X(:),Y(:),gradx,grady)
xlabel('x')
ylabel('y')
5-183
5 Functions — Alphabetical List
Zoom in on a particular part of the plot to see more details. For example, limit the plotting
range to 0.2 in each direction.
5-184
evaluateGradient
Evaluate gradients of the solution to a two-component elliptic system and plot the results.
model = createpde(2);
Create the 2-D geometry as a rectangle with a circular hole in its center. For details about
creating the geometry, see the example in “Solve PDEs with Constant Boundary
Conditions” on page 2-188.
5-185
5 Functions — Alphabetical List
R1 = [3,4,-0.3,0.3,0.3,-0.3,-0.3,-0.3,0.3,0.3]';
C1 = [1,0,0,0.1]';
C1 = [C1;zeros(length(R1)-length(C1),1)];
geom = [R1,C1];
ns = (char('R1','C1'))';
sf = 'R1 - C1';
g = decsg(geom,sf,ns);
geometryFromEdges(model,g);
pdegplot(model,'EdgeLabels','on')
axis equal
axis([-0.4,0.4,-0.4,0.4])
5-186
evaluateGradient
specifyCoefficients(model,'m',0,...
'd',0,...
'c',1,...
'a',0,...
'f',[2; -2]);
applyBoundaryCondition(model,'dirichlet','Edge',3,'u',[-1,1]);
applyBoundaryCondition(model,'dirichlet','Edge',1,'u',[1,-1]);
applyBoundaryCondition(model,'neumann','Edge',[2,4:8],'g',[0,0]);
generateMesh(model,'Hmax',0.1);
results = solvepde(model);
Interpolate the gradients of the solution to the grid from -0.3 to 0.3 in each direction for
each of the two components.
v = linspace(-0.3,0.3,15);
[X,Y] = meshgrid(v);
[gradx,grady] = evaluateGradient(results,X,Y,[1,2]);
figure
gradx1 = gradx(:,1);
grady1 = grady(:,1);
quiver(X(:),Y(:),gradx1,grady1)
title('Component 1')
axis equal
xlim([-0.3,0.3])
5-187
5 Functions — Alphabetical List
figure
gradx2 = gradx(:,2);
grady2 = grady(:,2);
quiver(X(:),Y(:),gradx2,grady2)
title('Component 2')
axis equal
xlim([-0.3,0.3])
5-188
evaluateGradient
Import slab geometry for a 3-D problem with three solution components. Plot the
geometry.
model = createpde(3);
importGeometry(model,'Plate10x10x1.stl');
pdegplot(model,'FaceLabels','on','FaceAlpha',0.5)
5-189
5 Functions — Alphabetical List
Set boundary conditions such that face 2 is fixed (zero deflection in any direction) and
face 5 has a load of 1e3 in the positive z-direction. This load causes the slab to bend
upward. Set the initial condition that the solution is zero, and its derivative with respect
to time is also zero.
applyBoundaryCondition(model,'dirichlet','Face',2,'u',[0,0,0]);
applyBoundaryCondition(model,'neumann','Face',5,'g',[0,0,1e3]);
setInitialConditions(model,0,0);
Create PDE coefficients for the equations of linear elasticity. Set the material properties
to be similar to those of steel. See 3-D Linear Elasticity Equations in Toolbox Form.
E = 200e9;
nu = 0.3;
5-190
evaluateGradient
specifyCoefficients(model,'m',1,...
'd',0,...
'c',elasticityC3D(E,nu),...
'a',0,...
'f',[0;0;0]);
Solve the problem for times 0 through 5e-3 in steps of 1e-4. You might have to wait a
few minutes for the solution.
tlist = 0:5e-4:5e-3;
results = solvepde(model,tlist);
Evaluate the gradients of the solution at fixed x- and z-coordinates in the centers of their
ranges, 5 and 0.5 respectively. Evaluate for y from 0 through 10 in steps of 0.2. Obtain
just component 3, the z-component.
yy = 0:0.2:10;
zz = 0.5*ones(size(yy));
xx = 10*zz;
component = 3;
[gradx,grady,gradz] = evaluateGradient(results,xx,yy,zz,component,1:length(tlist));
The three projections of the gradients of the solution are 51-by-1-by-51 arrays. Use
squeeze to remove the singleton dimension. Removing the singleton dimension
transforms these arrays to 51-by-51 matrices which simplifies indexing into them.
gradx = squeeze(gradx);
grady = squeeze(grady);
gradz = squeeze(gradz);
Plot the interpolated gradient component grady along the y axis for the following six
values from the time interval tlist.
figure
t = [1:2:11];
for i = t
p(i) = plot(yy,grady(:,i),'DisplayName', strcat('t=', num2str(tlist(i))));
hold on
end
legend(p(t))
xlabel('y')
5-191
5 Functions — Alphabetical List
ylabel('grady')
ylim([-5e-6, 20e-6])
Input Arguments
results — PDE solution
StationaryResults object | TimeDependentResults object
5-192
evaluateGradient
evaluateGradient converts query points to column vectors xq(:), yq(:), and (if
present) zq(:). For a single stationary PDE, the result consists of column vectors of the
same size. To ensure that the dimensions of the gradient components are consistent with
the dimensions of the original query points, use reshape. For example, use gradx =
reshape(gradx,size(xq)).
For a time-dependent PDE or a system of PDEs, the first dimension of the resulting arrays
corresponds to spatial points specified by the column vectors xq(:), yq(:), and (if
present) zq(:).
Data Types: double
evaluateGradient converts query points to column vectors xq(:), yq(:), and (if
present) zq(:). For a single stationary PDE, the result consists of column vectors of the
same size. To ensure that the dimensions of the gradient components are consistent with
the dimensions of the original query points, use reshape. For example, use grady =
reshape(grady,size(yq)).
For a time-dependent PDE or a system of PDEs, the first dimension of the resulting arrays
corresponds to spatial points specified by the column vectors xq(:), yq(:), and (if
present) zq(:).
Data Types: double
5-193
5 Functions — Alphabetical List
evaluateGradient converts query points to column vectors xq(:), yq(:), and (if
present) zq(:). For a single stationary PDE, the result consists of column vectors of the
same size. To ensure that the dimensions of the gradient components are consistent with
the dimensions of the original query points, use reshape. For example, use gradz =
reshape(gradz,size(zq)).
For a time-dependent PDE or a system of PDEs, the first dimension of the resulting arrays
corresponds to spatial points specified by the column vectors xq(:), yq(:), and (if
present) zq(:).
Data Types: double
Query points, specified as a real matrix with either two rows for 2-D geometry, or three
rows for 3-D geometry. evaluateGradient evaluates the gradients of the solution at the
coordinate points querypoints(:,i), so each column of querypoints contains exactly
one 2-D or 3-D query point.
Example: For 2-D geometry, querypoints = [0.5,0.5,0.75,0.75; 1,2,0,0.5]
Data Types: double
iU — Equation indices
vector of positive integers
iT — Time indices
vector of positive integers
Time indices, specified as a vector of positive integers. Each entry in iT specifies a time
index.
Example: iT = 1:5:21 specifies every fifth time-step up to 21.
5-194
evaluateGradient
Output Arguments
gradx — x-component of the gradient
array
x-component of the gradient, returned as an array. For query points that are outside the
geometry, gradx = NaN. For information about the size of gradx, see “Dimensions of
Solutions, Gradients, and Fluxes” on page 3-299.
y-component of the gradient, returned as an array. For query points that are outside the
geometry, grady = NaN. For information about the size of grady, see “Dimensions of
Solutions, Gradients, and Fluxes” on page 3-299.
z-component of the gradient, returned as an array. For query points that are outside the
geometry, gradz = NaN. For information about the size of gradz, see “Dimensions of
Solutions, Gradients, and Fluxes” on page 3-299.
Tips
The results object contains the solution and its gradient calculated at the nodal points
of the triangular or tetrahedral mesh. You can access the solution and three components
of the gradient at nodal points by using dot notation.
interpolateSolution and evaluateGradient let you interpolate the solution and its
gradient to a custom grid, for example, specified by meshgrid.
See Also
PDEModel | StationaryResults | TimeDependentResults | contour |
evaluateCGradient | interpolateSolution | quiver | quiver3
5-195
5 Functions — Alphabetical List
Topics
“Plot 2-D Solutions and Their Gradients” on page 3-266
“Plot 3-D Solutions and Their Gradients” on page 3-277
“Dimensions of Solutions, Gradients, and Fluxes” on page 3-299
Introduced in R2016a
5-196
evaluateHeatFlux
evaluateHeatFlux
Package: pde
Syntax
[qx,qy] = evaluateHeatFlux(thermalresults,xq,yq)
[qx,qy,qz] = evaluateHeatFlux(thermalresults,xq,yq,zq)
[ ___ ] = evaluateHeatFlux(thermalresults,querypoints)
[qx,qy] = evaluateHeatFlux(thermalresults)
[qx,qy,qz] = evaluateHeatFlux(thermalresults)
Description
[qx,qy] = evaluateHeatFlux(thermalresults,xq,yq) returns the heat flux for a
thermal problem at the 2-D points specified in xq and yq. This syntax is valid for both the
steady-state and transient thermal models.
[ ___ ] = evaluateHeatFlux( ___ ,iT) returns the heat flux for a thermal problem at
the times specified in iT. You can specify iT after the input arguments in any of the
previous syntaxes.
The first dimension of qx, qy, and, in the 3-D case, qz corresponds to query points. The
second dimension corresponds to time steps iT.
5-197
5 Functions — Alphabetical List
Examples
For a 2-D steady-state thermal model, evaluate heat flux at the nodal locations and at the
points specified by x and y coordinates.
thermalmodel = createpde('thermal');
R1 = [3,4,-1,1,1,-1,1,1,-1,-1]';
g = decsg(R1,'R1',('R1')');
geometryFromEdges(thermalmodel,g);
pdegplot(thermalmodel,'EdgeLabels','on')
xlim([-1.5 1.5])
axis equal
5-198
evaluateHeatFlux
Assuming that this geometry represents an iron plate, the thermal conductivity is
.
thermalProperties(thermalmodel,'ThermalConductivity',79.5,'Face',1);
Apply a constant temperature of 500 K to the bottom of the plate (edge 3). Also, assume
that the top of the plate (edge 1) is insulated, and apply convection on the two sides of the
plate (edges 2 and 4).
thermalBC(thermalmodel,'Edge',3,'Temperature',500);
thermalBC(thermalmodel,'Edge',1,'HeatFlux',0);
thermalBC(thermalmodel,'Edge',[2 4], ...
'ConvectionCoefficient',25, ...
'AmbientTemperature',50);
5-199
5 Functions — Alphabetical List
generateMesh(thermalmodel);
results = solve(thermalmodel)
results =
SteadyStateThermalResults with properties:
[qx,qy] = evaluateHeatFlux(results);
figure
pdeplot(thermalmodel,'FlowData',[qx qy])
5-200
evaluateHeatFlux
Create a grid specified by x and y coordinates, and evaluate heat flux to the grid.
v = linspace(-0.5,0.5,11);
[X,Y] = meshgrid(v);
[qx,qy] = evaluateHeatFlux(results,X,Y);
Reshape the qTx and qTy vectors, and plot the resulting heat flux.
qx = reshape(qx,size(X));
qy = reshape(qy,size(Y));
figure
quiver(X,Y,qx,qy)
5-201
5 Functions — Alphabetical List
Alternatively, you can specify the grid by using a matrix of query points.
qx = reshape(qx,size(X));
qy = reshape(qy,size(Y));
figure
quiver(X,Y,qx,qy)
5-202
evaluateHeatFlux
For a 3-D steady-state thermal model, evaluate heat flux at the nodal locations and at the
points specified by x, y, and z coordinates.
thermalmodel = createpde('thermal');
5-203
5 Functions — Alphabetical List
importGeometry(thermalmodel,'Block.stl');
pdegplot(thermalmodel,'FaceLabels','on','FaceAlpha',0.5)
title('Copper block, cm')
axis equal
Assuming that this is a copper block, the thermal conductivity of the block is
approximately .
thermalProperties(thermalmodel,'ThermalConductivity',4);
Apply a constant temperature of 373 K to the left side of the block (face 1) and a constant
temperature of 573 K to the right side of the block (face 3).
5-204
evaluateHeatFlux
thermalBC(thermalmodel,'Face',1,'Temperature',373);
thermalBC(thermalmodel,'Face',3,'Temperature',573);
thermalBC(thermalmodel,'Face',4,'HeatFlux',-20);
generateMesh(thermalmodel);
thermalresults = solve(thermalmodel)
thermalresults =
SteadyStateThermalResults with properties:
[qx,qy,qz] = evaluateHeatFlux(thermalresults);
figure
pdeplot3D(thermalmodel,'FlowData',[qx qy qz])
5-205
5 Functions — Alphabetical List
Create a grid specified by x, y, and z coordinates, and evaluate heat flux to the grid.
[X,Y,Z] = meshgrid(1:26:100,1:6:20,1:11:50);
[qx,qy,qz] = evaluateHeatFlux(thermalresults,X,Y,Z);
Reshape the qx, qy, and qz vectors, and plot the resulting heat flux.
qx = reshape(qx,size(X));
qy = reshape(qy,size(Y));
qz = reshape(qz,size(Z));
figure
quiver3(X,Y,Z,qx,qy,qz)
5-206
evaluateHeatFlux
Alternatively, you can specify the grid by using a matrix of query points.
qx = reshape(qx,size(X));
qy = reshape(qy,size(Y));
qz = reshape(qz,size(Z));
figure
quiver3(X,Y,Z,qx,qy,qz)
5-207
5 Functions — Alphabetical List
Solve a 2-D transient heat transfer problem on a square domain, and compute heat flow
across a convective boundary.
thermalmodel = createpde('thermal','transient');
5-208
evaluateHeatFlux
g = @squareg;
geometryFromEdges(thermalmodel,g);
pdegplot(thermalmodel,'EdgeLabels','on')
xlim([-1.2 1.2])
ylim([-1.2 1.2])
axis equal
5-209
5 Functions — Alphabetical List
Apply insulated boundary conditions on three edges and the free convection boundary
condition on the right edge.
thermalBC(thermalmodel,'Edge',[1 3 4],'HeatFlux',0);
thermalBC(thermalmodel,'Edge',2,...
'ConvectionCoefficient',5000, ...
'AmbientTemperature',25);
Set the initial conditions: uniform room temperature across domain and higher
temperature on the top edge.
thermalIC(thermalmodel,25);
thermalIC(thermalmodel,100,'Edge',1);
Generate a mesh and solve the problem using 0:1000:200000 as a vector of times.
generateMesh(thermalmodel);
tlist = 0:1000:200000;
thermalresults = solve(thermalmodel,tlist)
thermalresults =
TransientThermalResults with properties:
Create a grid specified by x and y coordinates, and evaluate heat flux to the grid.
v = linspace(-1,1,11);
[X,Y] = meshgrid(v);
[qx,qy] = evaluateHeatFlux(thermalresults,X,Y,1:length(tlist));
Reshape qx and qy, and plot the resulting heat flux for the 25th solution step.
tlist(25)
ans = 24000
figure
5-210
evaluateHeatFlux
quiver(X(:),Y(:),qx(:,25),qy(:,25));
xlim([-1,1])
axis equal
Heat Flux for Transient Thermal Model on Two Squares Made of Different
Materials
Solve the heat transfer problem for the following 2-D geometry consisting of a square and
a diamond made of different materials. Compute the heat flux, and plot it as a vector field.
5-211
5 Functions — Alphabetical List
thermalmodel = createpde('thermal','transient');
5-212
evaluateHeatFlux
For the square region, assign the following thermal properties: thermal conductivity is
, mass density is , and specific heat is .
thermalProperties(thermalmodel,'ThermalConductivity',10, ...
'MassDensity',2, ...
'SpecificHeat',0.1, ...
'Face',1);
For the diamond-shaped region, assign the following thermal properties: thermal
conductivity is , mass density is , and specific heat is .
thermalProperties(thermalmodel,'ThermalConductivity',2, ...
'MassDensity',1, ...
5-213
5 Functions — Alphabetical List
'SpecificHeat',0.1, ...
'Face',2);
Assume that the diamond-shaped region is a heat source with the density of .
internalHeatSource(thermalmodel,4,'Face',2);
thermalBC(thermalmodel,'Temperature',0,'Edge',[1 2 7 8]);
thermalIC(thermalmodel,0);
generateMesh(thermalmodel);
The dynamic for this problem is very fast: the temperature reaches steady state in about
0.1 seconds. To capture the interesting part of the dynamics, set the solution time to
logspace(-2,-1,10). This gives 10 logarithmically spaced solution times between 0.01
and 0.1. Solve the equation.
tlist = logspace(-2,-1,10);
thermalresults = solve(thermalmodel,tlist);
temp = thermalresults.Temperature;
Compute the heat flux density. Plot the solution with isothermal lines using a contour plot,
and plot the heat flux vector field using arrows.
[qTx,qTy] = evaluateHeatFlux(thermalresults);
figure
pdeplot(thermalmodel,'XYData',temp(:,10),'Contour','on', ...
'FlowData',[qTx(:,10) qTy(:,10)], ...
'ColorMap','hot')
5-214
evaluateHeatFlux
Input Arguments
thermalresults — Solution of thermal problem
SteadyStateThermalResults object | TransientThermalResults object
5-215
5 Functions — Alphabetical List
evaluateHeatFlux converts query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns the heat flux in a form of a column vector of the same size. To
ensure that the dimensions of the returned solution are consistent with the dimensions of
the original query points, use reshape. For example, use qx =
reshape(qx,size(xq)).
Data Types: double
evaluateHeatFlux converts query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns the heat flux in a form of a column vector of the same size. To
ensure that the dimensions of the returned solution is consistent with the dimensions of
the original query points, use reshape. For example, use qy =
reshape(qy,size(yq)).
Data Types: double
evaluateHeatFlux converts query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns the heat flux in a form of a column vector of the same size. To
ensure that the dimensions of the returned solution is consistent with the dimensions of
5-216
evaluateHeatFlux
Query points, specified as a real matrix with two rows for 2-D geometry or three rows for
3-D geometry. evaluateHeatFlux evaluates the heat flux at the coordinate points
querypoints(:,i), so each column of querypoints contains exactly one 2-D or 3-D
query point.
Example: For 2-D geometry, querypoints = [0.5 0.5 0.75 0.75; 1 2 0 0.5]
Data Types: double
iT — Time indices
vector of positive integers
Time indices, specified as a vector of positive integers. Each entry in iT specifies a time
index.
Example: iT = 1:5:21 specifies every fifth time-step up to 21.
Data Types: double
Output Arguments
qx — x-component of the heat flux
array
x-component of the heat flux, returned as an array. The first array dimension represents
the node index. The second array dimension represents the time step.
y-component of the heat flux, returned as an array. The first array dimension represents
the node index. The second array dimension represents the time step.
5-217
5 Functions — Alphabetical List
z-component of the heat flux, returned as an array. The first array dimension represents
the node index. The second array dimension represents the time step.
See Also
SteadyStateThermalResults | ThermalModel | TransientThermalResults |
evaluateHeatRate | evaluateTemperatureGradient | interpolateTemperature
Introduced in R2017a
5-218
evaluateHeatRate
evaluateHeatRate
Package: pde
Syntax
Qn = evaluateHeatRate(thermalresults,RegionType,RegionID)
Description
Qn = evaluateHeatRate(thermalresults,RegionType,RegionID) returns the
integrated heat flow rate normal to the boundary specified by RegionType and
RegionID.
Examples
Compute the heat flow rate across a face of the block geometry.
thermalmodel = createpde('thermal','steadystate');
importGeometry(thermalmodel,'Block.stl');
pdegplot(thermalmodel,'FaceLabels','on','FaceAlpha',0.5)
5-219
5 Functions — Alphabetical List
Apply constant temperatures on the opposite ends of the block. All other faces are
insulated by default.
thermalBC(thermalmodel,'Face',1,'Temperature',100);
thermalBC(thermalmodel,'Face',3,'Temperature',50);
Generate mesh.
generateMesh(thermalmodel,'GeometricOrder','linear');
5-220
evaluateHeatRate
thermalresults = solve(thermalmodel);
Qn = evaluateHeatRate(thermalresults,'Face',3)
Qn = 4.0000e+04
Compute the heat flow rate across the surface of the cooling sphere.
thermalmodel = createpde('thermal','transient');
gm = multisphere(1);
thermalmodel.Geometry = gm;
Generate mesh.
generateMesh(thermalmodel,'GeometricOrder','linear');
thermalProperties(thermalmodel,'ThermalConductivity',80, ...
'SpecificHeat',460, ...
'MassDensity',7800);
thermalBC(thermalmodel,'Face',1,...
'ConvectionCoefficient',500, ...
'AmbientTemperature',30);
thermalIC(thermalmodel,800);
5-221
5 Functions — Alphabetical List
tlist = 0:100:2000;
result = solve(thermalmodel,tlist);
Compute the heat flow rate across the surface of the sphere over time.
Qn = evaluateHeatRate(result,'Face',1);
plot(tlist,Qn)
xlabel('Time')
ylabel('Heat Flow Rate')
5-222
evaluateHeatRate
Input Arguments
thermalresults — Solution of thermal problem
SteadyStateThermalResults object
Geometric region type, specified as 'Face' for 3-D geometry or 'Edge' for 2-D
geometry.
Example: Qn = evaluateHeatRate(thermalresults,'Face',3)
Data Types: char | string
Geometric region ID, specified as a positive integer. Find the region IDs using the
pdegplot function with the 'FaceLabels' (3-D) or 'EdgeLabels' (2-D) value set to
'on'.
Example: Qn = evaluateHeatRate(thermalresults,'Face',3)
Data Types: double
Output Arguments
Qn — Heat flow rate
real number | vector of real numbers
Heat flow rate, returned as a real number or, for time-dependent results, a vector of real
numbers. This value represents the integrated heat flow rate, measured in energy per
unit time, flowing in the direction normal to the boundary. Qn is positive if the heat flows
out of the domain, and negative if the heat flows into the domain.
5-223
5 Functions — Alphabetical List
See Also
SteadyStateThermalResults | ThermalModel | TransientThermalResults |
evaluateHeatFlux | evaluateTemperatureGradient | interpolateTemperature
Introduced in R2017a
5-224
evaluatePrincipalStrain
evaluatePrincipalStrain
Package: pde
Syntax
pStrain = evaluatePrincipalStrain(structuralresults)
Description
pStrain = evaluatePrincipalStrain(structuralresults) evaluates principal
strain at nodal locations using strain values from structuralresults. For a dynamic
structural model, evaluatePrincipalStrain evaluates principal strain for all time-
steps.
Examples
Solve a static structural model representing a bimetallic cable under tension, and
compute octahedral shear strain.
structuralmodel = createpde('structural','static-solid');
Create the geometry and include it in the model. Plot the geometry.
gm = multicylinder([0.01,0.015],0.05);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on', ...
'CellLabels','on', ...
'FaceAlpha',0.5)
5-225
5 Functions — Alphabetical List
Specify the Young's modulus and Poisson's ratio for each metal.
structuralProperties(structuralmodel,'Cell',1,'YoungsModulus',110E9, ...
'PoissonsRatio',0.28);
structuralProperties(structuralmodel,'Cell',2,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3);
5-226
evaluatePrincipalStrain
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel)
structuralresults =
StaticStructuralResults with properties:
pStrain = evaluatePrincipalStrain(structuralresults);
Use the principal strain to evaluate the first and second invariant of strain.
5-227
5 Functions — Alphabetical List
Evaluate the principal strain and octahedral shear strain in a beam under a harmonic
excitation.
structuralmodel = createpde('structural','transient-solid');
5-228
evaluatePrincipalStrain
gm = multicuboid(0.06,0.005,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
Specify the Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3, ...
'MassDensity',7800);
structuralBC(structuralmodel,'Face',5,'Constraint','fixed');
5-229
5 Functions — Alphabetical List
Apply a sinusoidal displacement along the y-direction on the end opposite the fixed end of
the beam.
structuralBC(structuralmodel,'Face',3,'YDisplacement',1E-4,'Frequency',50);
Generate a mesh.
generateMesh(structuralmodel,'Hmax',0.01);
structuralIC(structuralmodel,'Displacement',[0;0;0],'Velocity',[0;0;0]);
tlist = 0:0.002:0.2;
structuralresults = solve(structuralmodel,tlist);
pStrain = evaluatePrincipalStrain(structuralresults);
Use the principal strain to evaluate the first and second invariants.
figure
pdeplot3D(structuralmodel,'ColorMapData',tauOct(:,end))
5-230
evaluatePrincipalStrain
Input Arguments
structuralresults — Solution of structural analysis problem
StaticStructuralResults object | TransientStructuralResults object
5-231
5 Functions — Alphabetical List
Output Arguments
pStrain — Principal strain at nodal locations
structure array
See Also
StaticStructuralResults | StructuralModel | evaluatePrincipalStress |
evaluateReaction | interpolateDisplacement | interpolateStrain |
interpolateStress | interpolateVonMisesStress
Introduced in R2017b
5-232
evaluatePrincipalStress
evaluatePrincipalStress
Package: pde
Syntax
pStress = evaluatePrincipalStress(structuralresults)
Description
pStress = evaluatePrincipalStress(structuralresults) evaluates principal
stress at nodal locations using stress values from structuralresults. For a dynamic
structural model, evaluatePrincipalStress evaluates principal stress for all time-
steps.
Examples
Solve a static structural model representing a bimetallic cable under tension, and
compute octahedral shear stress.
structuralmodel = createpde('structural','static-solid');
gm = multicylinder([0.01,0.015],0.05);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on', ...
'CellLabels','on', ...
'FaceAlpha',0.5)
5-233
5 Functions — Alphabetical List
Specify the Young's modulus and Poisson's ratio for each metal.
structuralProperties(structuralmodel,'Cell',1,'YoungsModulus',110E9, ...
'PoissonsRatio',0.28);
structuralProperties(structuralmodel,'Cell',2,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3);
5-234
evaluatePrincipalStress
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel)
structuralresults =
StaticStructuralResults with properties:
pStress = evaluatePrincipalStress(structuralresults);
Use the principal stress to evaluate the first and second invariant of stress.
5-235
5 Functions — Alphabetical List
Evaluate the principal stress and octahedral shear stress in a beam under a harmonic
excitation.
structuralmodel = createpde('structural','transient-solid');
Create the geometry and include it in the model. Plot the geometry.
5-236
evaluatePrincipalStress
gm = multicuboid(0.06,0.005,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
Specify the Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3, ...
'MassDensity',7800);
structuralBC(structuralmodel,'Face',5,'Constraint','fixed');
5-237
5 Functions — Alphabetical List
Apply a sinusoidal displacement along the y-direction on the end opposite the fixed end of
the beam.
structuralBC(structuralmodel,'Face',3,'YDisplacement',1E-4,'Frequency',50);
Generate a mesh.
generateMesh(structuralmodel,'Hmax',0.01);
structuralIC(structuralmodel,'Displacement',[0;0;0],'Velocity',[0;0;0]);
tlist = 0:0.002:0.2;
structuralresults = solve(structuralmodel,tlist);
pStress = evaluatePrincipalStress(structuralresults);
Use the principal stress to evaluate the first and second invariants.
figure
pdeplot3D(structuralmodel,'ColorMapData',tauOct(:,end))
5-238
evaluatePrincipalStress
Input Arguments
structuralresults — Solution of structural analysis problem
StaticStructuralResults object | TransientStructuralResults object
5-239
5 Functions — Alphabetical List
Output Arguments
pStress — Principal stress at nodal locations
structure array
See Also
StaticStructuralResults | StructuralModel | evaluatePrincipalStrain |
evaluateReaction | interpolateDisplacement | interpolateStrain |
interpolateStress | interpolateVonMisesStress
Introduced in R2017b
5-240
evaluateReaction
evaluateReaction
Package: pde
Syntax
F = evaluateReaction(structuralresults,RegionType,RegionID)
Description
F = evaluateReaction(structuralresults,RegionType,RegionID) evaluates
reaction forces on the boundary specified by RegionType and RegionID. The function
uses the global Cartesian coordinate system. For a dynamic structural model,
evaluateReaction evaluates reaction forces for all time-steps.
Examples
structuralmodel = createpde('structural','static-solid');
Create a cuboid geometry and include it in the model. Plot the geometry.
structuralmodel.Geometry = multicuboid(0.01,0.01,0.05);
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5);
5-241
5 Functions — Alphabetical List
Fix one end of the bar and apply pressure to the opposite end.
structuralBC(structuralmodel,'Face',1,'Constraint','fixed')
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 1
Vectorized: 'off'
5-242
evaluateReaction
Boundary Loads
SurfaceTraction: []
Pressure: []
TranslationalStiffness: []
structuralBoundaryLoad(structuralmodel,'Face',2,'Pressure',100)
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 2
Vectorized: 'off'
Boundary Loads
SurfaceTraction: []
Pressure: 100
TranslationalStiffness: []
5-243
5 Functions — Alphabetical List
Fy: 1.8707e-06
Fz: 0.0104
Evaluate the reaction forces at the fixed end of a beam subject to harmonic excitation.
structuralmodel = createpde('structural','transient-solid');
gm = multicuboid(0.06,0.005,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
5-244
evaluateReaction
Specify the Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3, ...
'MassDensity',7800);
structuralBC(structuralmodel,'Face',5,'Constraint','fixed');
Apply a sinusoidal displacement along the y-direction on the end opposite the fixed end of
the beam.
structuralBC(structuralmodel,'Face',3,'YDisplacement',1E-4,'Frequency',50);
5-245
5 Functions — Alphabetical List
Generate a mesh.
generateMesh(structuralmodel,'Hmax',0.01);
structuralIC(structuralmodel,'Displacement',[0;0;0],'Velocity',[0;0;0]);
tlist = 0:0.002:0.2;
structuralresults = solve(structuralmodel,tlist);
reaction = evaluateReaction(structuralresults,'Face',5)
Input Arguments
structuralresults — Solution of structural analysis problem
StaticStructuralResults object | TransientStructuralResults object
Geometric region type, specified as 'Edge' for a 2-D model or 'Face' for a 3-D model.
Example: evaluateReaction(structuralresults,'Face',2)
Data Types: char | string
5-246
evaluateReaction
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot, as shown in “Create Geometry and Remove Face Boundaries” on page 2-13 or
“STL File Import” on page 2-47.
Example: evaluateReaction(structuralresults,'Face',2)
Data Types: double
Output Arguments
F — Reaction forces
structure array
Reaction forces, returned as a structure array. The array fields represent the integrated
reaction forces and surface traction vector, which are computed by using the state of
stress on the boundary and the outward normal.
See Also
StaticStructuralResults | StructuralModel | evaluatePrincipalStrain |
evaluatePrincipalStress | interpolateDisplacement | interpolateStrain |
interpolateStress | interpolateVonMisesStress
Introduced in R2017b
5-247
5 Functions — Alphabetical List
evaluateStrain
Package: pde
Syntax
nodalStrain = evaluateStrain(structuralresults)
Description
nodalStrain = evaluateStrain(structuralresults) evaluates strain at nodal
locations for all time steps.
Examples
structuralmodel = createpde('structural','transient-solid');
Create the geometry and include it in the model. Plot the geometry.
gm = multicuboid(0.06,0.005,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
5-248
evaluateStrain
Specify the Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3, ...
'MassDensity',7800);
structuralBC(structuralmodel,'Face',5,'Constraint','fixed');
Apply a sinusoidal displacement along the y-direction on the end opposite the fixed end of
the beam.
structuralBC(structuralmodel,'Face',3,'YDisplacement',1E-4,'Frequency',50);
5-249
5 Functions — Alphabetical List
Generate a mesh.
generateMesh(structuralmodel,'Hmax',0.01);
structuralIC(structuralmodel,'Displacement',[0,0,0],'Velocity',[0,0,0]);
tlist = 0:0.002:0.2;
structuralresults = solve(structuralmodel,tlist);
strain = evaluateStrain(structuralresults);
Plot the normal strain along x-direction for the last time-step.
figure
pdeplot3D(structuralmodel,'ColorMapData',strain.exx(:,end))
title('x-Direction Normal Strain in the Beam of the Last Time-Step')
5-250
evaluateStrain
Input Arguments
structuralresults — Solution of dynamic structural analysis problem
TransientStructuralResults object
5-251
5 Functions — Alphabetical List
Output Arguments
nodalStrain — Strain at nodes
structure array
Strain at the nodes, returned as a structure array with the fields representing the
components of strain tensor at nodal locations.
See Also
StructuralModel | TransientStructuralResults | evaluatePrincipalStrain |
evaluatePrincipalStress | evaluateReaction | evaluateStress |
evaluateVonMisesStress | interpolateAcceleration |
interpolateDisplacement | interpolateStrain | interpolateStress |
interpolateVelocity | interpolateVonMisesStress
Introduced in R2018a
5-252
evaluateStress
evaluateStress
Package: pde
Syntax
nodalStress = evaluateStress(structuralresults)
Description
nodalStress = evaluateStress(structuralresults) evaluates stress at nodal
locations for all time steps.
Examples
structuralmodel = createpde('structural','transient-solid');
Create the geometry and include it in the model. Plot the geometry.
gm = multicuboid(0.06,0.005,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
5-253
5 Functions — Alphabetical List
Specify the Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3, ...
'MassDensity',7800);
structuralBC(structuralmodel,'Face',5,'Constraint','fixed');
Apply a sinusoidal displacement along the y-direction on the end opposite the fixed end of
the beam.
structuralBC(structuralmodel,'Face',3,'YDisplacement',1E-4,'Frequency',50);
5-254
evaluateStress
Generate a mesh.
generateMesh(structuralmodel,'Hmax',0.01);
structuralIC(structuralmodel,'Displacement',[0,0,0],'Velocity',[0,0,0]);
tlist = 0:0.002:0.2;
structuralresults = solve(structuralmodel,tlist);
stress = evaluateStress(structuralresults);
Plot the normal stress along x-direction for the last time-step.
figure
pdeplot3D(structuralmodel,'ColorMapData',stress.sxx(:,end))
title('x-Direction Normal Stress in the Beam of the Last Time-Step')
5-255
5 Functions — Alphabetical List
Input Arguments
structuralresults — Solution of dynamic structural analysis problem
TransientStructuralResults object
5-256
evaluateStress
Output Arguments
nodalStress — Stress at nodes
structure array
Stress at the nodes, returned as a structure array with the fields representing the
components of a stress tensor at nodal locations.
See Also
StructuralModel | TransientStructuralResults | evaluatePrincipalStrain |
evaluatePrincipalStress | evaluateReaction | evaluateStrain |
evaluateVonMisesStress | interpolateAcceleration |
interpolateDisplacement | interpolateStrain | interpolateStress |
interpolateVelocity | interpolateVonMisesStress
Introduced in R2018a
5-257
5 Functions — Alphabetical List
evaluateTemperatureGradient
Package: pde
Syntax
[gradTx,gradTy] = evaluateTemperatureGradient(thermalresults,xq,yq)
[gradTx,gradTy,gradTz] = evaluateTemperatureGradient(thermalresults,
xq,yq,zq)
[ ___ ] = evaluateTemperatureGradient(thermalresults,querypoints)
[ ___ ] = evaluateTemperatureGradient( ___ ,iT)
Description
[gradTx,gradTy] = evaluateTemperatureGradient(thermalresults,xq,yq)
returns the interpolated values of temperature gradients of the thermal model solution
thermalresults at the 2-D points specified in xq and yq. This syntax is valid for both
the steady-state and transient thermal models.
[gradTx,gradTy,gradTz] = evaluateTemperatureGradient(thermalresults,
xq,yq,zq) returns the interpolated temperature gradients at the 3-D points specified in
xq, yq, and zq. This syntax is valid for both the steady-state and transient thermal
models.
[ ___ ] = evaluateTemperatureGradient(thermalresults,querypoints)
returns the interpolated values of the temperature gradients at the points specified in
querypoints. This syntax is valid for both the steady-state and transient thermal
models.
The first dimension of gradTx, gradTy, and, in 3-D case, gradTz corresponds to query
points. The second dimension corresponds to time-steps iT.
5-258
evaluateTemperatureGradient
Examples
For a 2-D steady-state thermal model, evaluate temperature gradients at the nodal
locations and at the points specified by x and y coordinates.
thermalmodel = createpde('thermal');
R1 = [3,4,-1,1,1,-1,1,1,-1,-1]';
g = decsg(R1,'R1',('R1')');
geometryFromEdges(thermalmodel,g);
pdegplot(thermalmodel,'EdgeLabels','on')
xlim([-1.5 1.5])
axis equal
5-259
5 Functions — Alphabetical List
Assuming that this geometry represents an iron plate, the thermal conductivity is
.
thermalProperties(thermalmodel,'ThermalConductivity',79.5,'Face',1);
Apply a constant temperature of 300 K to the bottom of the plate (edge 3). Also, assume
that the top of the plate (edge 1) is insulated, and apply convection on the two sides of the
plate (edges 2 and 4).
thermalBC(thermalmodel,'Edge',3,'Temperature',300);
thermalBC(thermalmodel,'Edge',1,'HeatFlux',0);
thermalBC(thermalmodel,'Edge',[2 4], ...
'ConvectionCoefficient',25, ...
'AmbientTemperature',50);
5-260
evaluateTemperatureGradient
generateMesh(thermalmodel);
results = solve(thermalmodel)
results =
SteadyStateThermalResults with properties:
The solver finds the temperatures and temperature gradients at the nodal locations. To
access these values, use results.Temperature, results.XGradients, and so on. For
example, plot the temperature gradients at nodal locations.
figure;
pdeplot(thermalmodel,'FlowData',[results.XGradients results.YGradients]);
5-261
5 Functions — Alphabetical List
Create a grid specified by x and y coordinates, and evaluate temperature gradients to the
grid.
v = linspace(-0.5,0.5,11);
[X,Y] = meshgrid(v);
[gradTx,gradTy] = evaluateTemperatureGradient(results,X,Y);
Reshape the gradTx and gradTy vectors, and plot the resulting temperature gradients.
gradTx = reshape(gradTx,size(X));
gradTy = reshape(gradTy,size(Y));
figure
quiver(X,Y,gradTx,gradTy)
5-262
evaluateTemperatureGradient
Alternatively, you can specify the grid by using a matrix of query points.
gradTx = reshape(gradTx,size(X));
gradTy = reshape(gradTy,size(Y));
figure
quiver(X,Y,gradTx,gradTy)
5-263
5 Functions — Alphabetical List
For a 3-D steady-state thermal model, evaluate temperature gradients at the nodal
locations and at the points specified by x, y, and z coordinates.
thermalmodel = createpde('thermal');
5-264
evaluateTemperatureGradient
importGeometry(thermalmodel,'Block.stl');
pdegplot(thermalmodel,'FaceLabels','on','FaceAlpha',0.5)
title('Copper block, cm')
axis equal
Assuming that this is a copper block, the thermal conductivity of the block is
approximately .
thermalProperties(thermalmodel,'ThermalConductivity',4);
Apply a constant temperature of 373 K to the left side of the block (edge 1) and a constant
temperature of 573 K to the right side of the block.
5-265
5 Functions — Alphabetical List
thermalBC(thermalmodel,'Face',1,'Temperature',373);
thermalBC(thermalmodel,'Face',3,'Temperature',573);
thermalBC(thermalmodel,'Face',4,'HeatFlux',-20);
generateMesh(thermalmodel);
thermalresults = solve(thermalmodel)
thermalresults =
SteadyStateThermalResults with properties:
The solver finds the values of temperatures and temperature gradients at the nodal
locations. To access these values, use results.Temperature, results.XGradients,
and so on.
[X,Y,Z] = meshgrid(1:26:100,1:6:20,1:11:50);
[gradTx,gradTy,gradTz] = evaluateTemperatureGradient(thermalresults,X,Y,Z);
Reshape the gradTx, gradTy, and gradTz vectors, and plot the resulting temperature
gradients.
gradTx = reshape(gradTx,size(X));
gradTy = reshape(gradTy,size(Y));
gradTz = reshape(gradTz,size(Z));
figure
quiver3(X,Y,Z,gradTx,gradTy,gradTz)
axis equal
xlabel('x')
5-266
evaluateTemperatureGradient
ylabel('y')
zlabel('z')
Alternatively, you can specify the grid by using a matrix of query points.
gradTx = reshape(gradTx,size(X));
gradTy = reshape(gradTy,size(Y));
gradTz = reshape(gradTz,size(Z));
figure
quiver3(X,Y,Z,gradTx,gradTy,gradTz)
5-267
5 Functions — Alphabetical List
axis equal
xlabel('x')
ylabel('y')
zlabel('z')
Solve a 2-D transient heat transfer problem on a square domain and compute
temperature gradients at the convective boundary.
5-268
evaluateTemperatureGradient
thermalmodel = createpde('thermal','transient');
5-269
5 Functions — Alphabetical List
thermalProperties(thermalmodel,'ThermalConductivity',100, ...
'MassDensity',7800, ...
'SpecificHeat',500);
Apply insulated boundary conditions on three edges and the free convection boundary
condition on the right edge.
thermalBC(thermalmodel,'Edge',[1 3 4],'HeatFlux',0);
thermalBC(thermalmodel,'Edge',2, ...
'ConvectionCoefficient',5000, ...
'AmbientTemperature',25);
Set the initial conditions: uniform room temperature across domain and higher
temperature on the left edge.
thermalIC(thermalmodel,25);
thermalIC(thermalmodel,100,'Edge',4);
Generate a mesh and solve the problem using 0:1000:200000 as a vector of times.
generateMesh(thermalmodel);
tlist = 0:1000:200000;
thermalresults = solve(thermalmodel,tlist)
thermalresults =
TransientThermalResults with properties:
Define a line at convection boundary and compute temperature gradients across that line.
X = -1:0.1:1;
Y = ones(size(X));
[gradTx,gradTy] = evaluateTemperatureGradient(thermalresults,X,Y,1:length(tlist));
Plot the interpolated gradient component gradTx along the x axis for the following
values from the time interval tlist.
5-270
evaluateTemperatureGradient
figure
t = [51:50:201];
for i = t
p(i) = plot(X,gradTx(:,i),'DisplayName', strcat('t=', num2str(tlist(i))));
hold on
end
legend(p(t))
xlabel('x')
ylabel('gradTx')
5-271
5 Functions — Alphabetical List
Input Arguments
thermalresults — Solution of thermal problem
SteadyStateThermalResults object | TransientThermalResults object
5-272
evaluateTemperatureGradient
Query points, specified as a real matrix with either two rows for 2-D geometry, or three
rows for 3-D geometry. evaluateTemperatureGradient evaluates the temperature
gradient at the coordinate points querypoints(:,i), so each column of querypoints
contains exactly one 2-D or 3-D query point.
Example: For 2-D geometry, querypoints = [0.5 0.5 0.75 0.75; 1 2 0 0.5]
Data Types: double
iT — Time indices
vector of positive integers
Time indices, specified as a vector of positive integers. Each entry in iT specifies a time
index.
Example: iT = 1:5:21 specifies every fifth time-step up to 21.
Data Types: double
Output Arguments
gradTx — x-component of the temperature gradient
matrix
5-273
5 Functions — Alphabetical List
x-component of the temperature gradient, returned as a matrix. For query points that are
outside the geometry, gradTx = NaN.
y-component of the temperature gradient, returned as a matrix. For query points that are
outside the geometry, gradTy = NaN.
z-component of the temperature gradient, returned as a matrix. For query points that are
outside the geometry, gradTz = NaN.
See Also
SteadyStateThermalResults | ThermalModel | TransientThermalResults |
evaluateHeatFlux | evaluateHeatRate | interpolateTemperature
Introduced in R2017a
5-274
evaluateVonMisesStress
evaluateVonMisesStress
Package: pde
Syntax
vmStress = evaluateVonMisesStress(structuralresults)
Description
vmStress = evaluateVonMisesStress(structuralresults) evaluates von Mises
stress at nodal locations for all time steps.
Examples
structuralmodel = createpde('structural','transient-solid');
Create the geometry and include it in the model. Plot the geometry.
gm = multicuboid(0.06,0.005,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
5-275
5 Functions — Alphabetical List
Specify the Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3, ...
'MassDensity',7800);
structuralBC(structuralmodel,'Face',5,'Constraint','fixed');
Apply a sinusoidal displacement along the y-direction on the end opposite the fixed end of
the beam.
structuralBC(structuralmodel,'Face',3,'YDisplacement',1E-4,'Frequency',50);
5-276
evaluateVonMisesStress
Generate a mesh.
generateMesh(structuralmodel,'Hmax',0.01);
structuralIC(structuralmodel,'Displacement',[0;0;0],'Velocity',[0;0;0]);
tlist = 0:0.002:0.2;
structuralresults = solve(structuralmodel,tlist);
vmStress = evaluateVonMisesStress(structuralresults);
figure
pdeplot3D(structuralmodel,'ColorMapData',vmStress(:,end))
title('von Mises Stress in the Beam for the Last Time-Step')
5-277
5 Functions — Alphabetical List
Input Arguments
structuralresults — Solution of dynamic structural analysis problem
TransientStructuralResults object
5-278
evaluateVonMisesStress
Output Arguments
vmStress — Von Mises Stress at nodes
matrix
Von Mises Stress at the nodes, returned as a matrix. The rows of the matrix contain the
values of von Mises stress at nodal locations, while the columns correspond to the time
steps.
See Also
StructuralModel | TransientStructuralResults | evaluatePrincipalStrain |
evaluatePrincipalStress | evaluateReaction | evaluateStrain |
evaluateStress | interpolateAcceleration | interpolateDisplacement |
interpolateStrain | interpolateStress | interpolateVelocity |
interpolateVonMisesStress
Introduced in R2018a
5-279
5 Functions — Alphabetical List
FEMesh Properties
Mesh object
Description
An FEMesh object contains a description of the finite element mesh. A PDEModel
container has an FEMesh object in its Mesh property.
Properties
Properties
Mesh nodes, returned as a matrix. Nodes is a D-by-Nn matrix, where D is the number of
geometry dimensions (2 or 3), and Nn is the number of nodes in the mesh. Each column of
Nodes contains the x, y, and in 3-D, z coordinates for that mesh node.
2-D meshes have nodes at the mesh triangle corners for linear elements, and at the
corners and edge midpoints for 'quadratic' elements. 3-D meshes have nodes at
tetrahedral vertices, and the 'quadratic' elements have additional nodes at the center
points of each edge. See “Mesh Data” on page 2-241.
Data Types: double
Mesh elements, returned as an M-by-Ne matrix, where Ne is the number of elements in the
mesh, and M is:
5-280
FEMesh Properties
Each column in Elements contains the indices of the nodes for that mesh element.
Data Types: double
Target maximum mesh element size, returned as a positive real number. The maximum
mesh element size is the length of the longest edge in the mesh. The generateMesh
Hmax name-value pair sets the target maximum size at the time it creates the mesh.
generateMesh can occasionally create a mesh with some elements that exceed
MaxElementSize by a few percent.
Data Types: double
Target minimum mesh element size, returned as a positive real number. The minimum
mesh element size is the length of the shortest edge in the mesh. The Hmin name-value
pair passed to the generateMesh function sets the target minimum size the at the time it
creates the mesh. generateMesh can occasionally create a mesh with some elements
that are smaller than MinElementSize.
Data Types: double
5-281
5 Functions — Alphabetical List
See Also
PDEModel | area | findElements | findNodes | generateMesh | meshQuality |
meshToPet | volume
Topics
“Solve Problems Using PDEModel Objects” on page 2-6
“Finite Element Method Basics” on page 1-27
“Mesh Data” on page 2-241
Introduced in R2015a
5-282
findBodyLoad
findBodyLoad
Package: pde
Syntax
bl = findBodyLoad(structuralmodel.BodyLoads,RegionType,RegionID)
Description
bl = findBodyLoad(structuralmodel.BodyLoads,RegionType,RegionID)
returns the body load assigned to a geometric region of the structural model. A body load
must use units consistent with the geometry and other model attributes.
Examples
structuralModel = createpde('structural','static-solid');
gm = multicuboid(0.5,0.1,0.1);
structuralModel.Geometry = gm;
pdegplot(structuralModel,'FaceAlpha',0.5)
5-283
5 Functions — Alphabetical List
Specify the Young's modulus, Poisson's ratio, and mass density. Notice that the mass
density value is required for modeling gravitational effects.
structuralProperties(structuralModel,'YoungsModulus',210E3, ...
'PoissonsRatio',0.3,...
'MassDensity',2.7E-6);
structuralBodyLoad(structuralModel,'GravitationalAcceleration',[0;0;-9.8]);
findBodyLoad(structuralModel.BodyLoads,'Cell',1)
5-284
findBodyLoad
ans =
BodyLoadAssignment with properties:
RegionType: 'Cell'
RegionID: 1
GravitationalAcceleration: [3x1 double]
Temperature: []
TimeStep: []
Input Arguments
structuralmodel.BodyLoads — Body loads
BodyLoads property of StructuralModel object
Geometric region type, specified as 'Face' for a 2-D model or 'Cell' for a 3-D model.
Example: findBodyLoad(structuralmodel.BodyLoads,'Cell',1)
Data Types: char | string
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot, as shown in “Create Geometry and Remove Face Boundaries” on page 2-13 or
“STL File Import” on page 2-47.
Example: findBodyLoad(structuralmodel.BodyLoads,'Cell',1)
Data Types: double
5-285
5 Functions — Alphabetical List
Output Arguments
bl — Body load assignment
BodyLoadAssignment object
See Also
structuralBodyLoad
Introduced in R2017b
5-286
findBoundaryConditions
findBoundaryConditions
Package: pde
Syntax
BCregion = findBoundaryConditions(BCs,RegionType,RegionID)
Description
BCregion = findBoundaryConditions(BCs,RegionType,RegionID) returns
boundary condition BCregion assigned to the specified region.
Examples
Create a PDE model and import a simple block geometry. Plot the geometry displaying the
face labels.
model = createpde(3);
importGeometry(model,'Block.stl');
pdegplot(model,'FaceLabels','on','FaceAlpha',0.5)
5-287
5 Functions — Alphabetical List
applyBoundaryCondition(model,'dirichlet','Face',1:2,'u',[0,0,0]);
On face 3, set the Neumann boundary condition for equation 1 and Dirichlet boundary
condition for equations 2 and 3.
Set Neumann boundary conditions with opposite signs on faces 5 and 6 for all equations.
5-288
findBoundaryConditions
applyBoundaryCondition(model,'neumann','Face',4:5,'g',[1;1;1]);
applyBoundaryCondition(model,'neumann','Face',6,'g',[-1;-1;-1]);
ans =
BoundaryCondition with properties:
BCType: 'dirichlet'
RegionType: 'Face'
RegionID: [1 2]
r: []
h: []
g: []
q: []
u: [0 0 0]
EquationIndex: []
Vectorized: 'off'
ans =
BoundaryCondition with properties:
BCType: 'mixed'
RegionType: 'Face'
RegionID: 3
r: [3x1 double]
h: [3x3 double]
g: [3x1 double]
q: [3x3 double]
u: []
EquationIndex: []
Vectorized: 'off'
ans =
BoundaryCondition with properties:
5-289
5 Functions — Alphabetical List
BCType: 'neumann'
RegionType: 'Face'
RegionID: [4 5]
r: []
h: []
g: [3x1 double]
q: []
u: []
EquationIndex: []
Vectorized: 'off'
Input Arguments
BCs — Boundary conditions of a PDE model
BoundaryConditions property of a PDE model
Geometric region type, specified as 'Face' for 3-D geometry or 'Edge' for 2-D
geometry.
Example: findBoundaryConditions(model.BoundaryConditions,'Face',3)
Data Types: char | string
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot with the 'FaceLabels' (3-D) or 'EdgeLabels' (2-D) value set to 'on'.
Example: findBoundaryConditions(model.BoundaryConditions,'Face',3)
Data Types: double
5-290
findBoundaryConditions
Output Arguments
BCregion — Boundary condition for a particular region
BoundaryCondition object
See Also
BoundaryCondition | applyBoundaryCondition
Topics
“Solve Problems Using PDEModel Objects” on page 2-6
Introduced in R2016b
5-291
5 Functions — Alphabetical List
findCoefficients
Package: pde
Syntax
CA = findCoefficients(coeffs,RegionType,RegionID)
Description
CA = findCoefficients(coeffs,RegionType,RegionID) returns the active
coefficient assignment CA for the coefficients in the specified region.
Examples
model = createpde();
geometryFromEdges(model,@lshapeg);
pdegplot(model,'FaceLabels','on')
ylim([-1.1,1.1])
axis equal
5-292
findCoefficients
ca =
CoefficientAssignment with properties:
RegionType: 'face'
5-293
5 Functions — Alphabetical List
RegionID: [1 3]
m: 0
d: 0
c: 13
a: 0
f: 2
Input Arguments
coeffs — Model coefficients
EquationCoefficients property of a PDE model
Geometric region type, specified as 'Face' for a 2-D model, or 'Cell' for a 3-D model.
Example: ca = findCoefficients(coeffs,'Face',[1,3])
Data Types: char | string
RegionID — Region ID
vector of positive integers
Region ID, specified as a vector of positive integers. View the subdomain labels for a 2-D
model using pdegplot(model,'FaceLabels','on'). Currently, there are no
subdomains for 3-D models, so the only acceptable value for a 3-D model is 1.
Example: ca = findCoefficients(coeffs,'Face',[1,3])
Data Types: double
5-294
findCoefficients
Output Arguments
CA — Coefficient assignment
CoefficientAssignment object
See Also
CoefficientAssignment | specifyCoefficients
Topics
“View, Edit, and Delete PDE Coefficients” on page 2-157
“Solve Problems Using PDEModel Objects” on page 2-6
“PDE Coefficients”
Introduced in R2016a
5-295
5 Functions — Alphabetical List
findElements
Package: pde
Syntax
elemIDs = findElements(mesh,'region',RegionType,RegionID)
elemIDs = findElements(mesh,'box',xlim,ylim)
elemIDs = findElements(mesh,'box',xlim,ylim,zlim)
elemIDs = findElements(mesh,'radius',center,radius)
elemIDs = findElements(mesh,'attached',nodeID)
Description
elemIDs = findElements(mesh,'region',RegionType,RegionID) returns the
IDs of the mesh elements that belong to the specified geometric region.
5-296
findElements
Examples
model = createpde;
Include the geometry of the built-in function lshapeg. Plot the geometry.
geometryFromEdges(model,@lshapeg);
pdegplot(model,'FaceLabels','on','EdgeLabels','on')
5-297
5 Functions — Alphabetical List
Generate a mesh.
mesh = generateMesh(model,'Hmax',0.5);
Ef2 = findElements(mesh,'region','Face',2);
figure
pdemesh(mesh,'ElementLabels','on')
hold on
pdemesh(mesh.Nodes,mesh.Elements(:,Ef2),'EdgeColor','green')
5-298
findElements
5-299
5 Functions — Alphabetical List
Generate a mesh.
mesh = generateMesh(model,'Hmax',2,'Hmin',0.4)
mesh =
FEMesh with properties:
5-300
findElements
figure
pdemesh(model)
hold on
pdemesh(mesh.Nodes,mesh.Elements(:,Eb),'EdgeColor','green')
5-301
5 Functions — Alphabetical List
model = createpde;
importGeometry(model,'PlateHolePlanar.stl');
pdegplot(model)
Generate a mesh.
5-302
findElements
mesh = generateMesh(model,'Hmax',2,'Hmin',0.4,'GeometricOrder','linear')
mesh =
FEMesh with properties:
Find the elements located within radius 2 from the center [5,10].
Er = findElements(mesh,'radius',[5 10],2);
figure
pdemesh(model)
hold on
pdemesh(mesh.Nodes,mesh.Elements(:,Er),'EdgeColor','green')
5-303
5 Functions — Alphabetical List
5-304
findElements
Generate a linear triangular mesh by setting the geometric order value to linear. This
mesh contains only corner nodes.
mesh = generateMesh(model,'Hmax',2,'Hmin',0.4, ...
'GeometricOrder','linear');
N_ID = 10
5-305
5 Functions — Alphabetical List
En = 1×3
95 97 98
Highlight the node and the elements in green on the mesh plot.
figure
pdemesh(model)
hold on
plot(mesh.Nodes(1,N_ID),mesh.Nodes(2,N_ID),'or','Color','g', ...
'MarkerFaceColor','g')
pdemesh(mesh.Nodes,mesh.Elements(:,En),'EdgeColor','green')
5-306
findElements
Input Arguments
mesh — Mesh object
Mesh property of a PDEModel object | output of generateMesh
Mesh object, specified as the Mesh property of a PDEModel object or as the output of
generateMesh.
Example: model.Mesh
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot, as shown in “Create Geometry and Remove Face Boundaries” on page 2-13 or
“STL File Import” on page 2-47.
Example: findElements(mesh,'region','Face',1:3)
Data Types: double
x-limits of the bounding box, specified as a two-element row vector. The first element of
xlim is the lower x-bound, and the second element is the upper x-bound.
Example: findElements(mesh,'box',[5 10],[10 20])
Data Types: double
y-limits of the bounding box, specified as a two-element row vector. The first element of
ylim is the lower y-bound, and the second element is the upper y-bound.
5-307
5 Functions — Alphabetical List
z-limits of the bounding box, specified as a two-element row vector. The first element of
zlim is the lower z-bound, and the second element is the upper z-bound. You can specify
zlim only for 3-D meshes.
Example: findElements(mesh,'box',[5 10],[10 20],[1 2])
Data Types: double
Center of the bounding circle or sphere, specified as a two-element row vector for a 2-D
mesh or three-element row vector for a 3-D mesh. The elements of these vectors contain
the coordinates of the center of a circle or a sphere.
Example: findElements(mesh,'radius',[0 0 0],0.5)
Data Types: double
ID of the corner node of the element, specified as a positive integer or a vector of positive
integers. The findElements function can find an ID of the element by the ID of the
corner node of the element. The function ignores IDs of the nodes located in the middle of
element edges. For multiple nodes, specify nodeID as a vector.
Example: findElements(mesh,'attached',[7 8 21])
Data Types: double
5-308
findElements
Output Arguments
elemIDs — Element IDs
positive integer | row vector of positive integers
See Also
FEMesh Properties | area | findNodes | meshQuality | volume
Topics
“Finite Element Method Basics” on page 1-27
Introduced in R2018a
5-309
5 Functions — Alphabetical List
findHeatSource
Package: pde
Syntax
hsa = findHeatSource(thermalmodel.HeatSources,RegionType,RegionID)
Description
hsa = findHeatSource(thermalmodel.HeatSources,RegionType,RegionID)
returns the heat source value hsa assigned to the specified region.
Examples
thermalmodel = createpde('thermal');
geometryFromEdges(thermalmodel,@lshapeg);
pdegplot(thermalmodel,'FaceLabels','on')
ylim([-1.1 1.1])
axis equal
5-310
findHeatSource
Specify that face 1 generates heat at 10 W/m^3, face 2 generates heat at 20 W/m^3, and
face 3 generates heat at 30 W/m^3.
internalHeatSource(thermalmodel,10,'Face',1);
internalHeatSource(thermalmodel,20,'Face',2);
internalHeatSource(thermalmodel,30,'Face',3);
hsaFace1 = findHeatSource(thermalmodel.HeatSources,'Face',1)
hsaFace1 =
HeatSourceAssignment with properties:
5-311
5 Functions — Alphabetical List
RegionType: 'face'
RegionID: 1
HeatSource: 10
hsaFace2 =
HeatSourceAssignment with properties:
RegionType: 'face'
RegionID: 2
HeatSource: 20
hsaFace3 = hsa(2)
hsaFace3 =
HeatSourceAssignment with properties:
RegionType: 'face'
RegionID: 3
HeatSource: 30
Create a geometry that consists of three stacked cylinders and include the geometry in a
thermal model.
gm = multicylinder(10,[1 2 3],'ZOffset',[0 1 3])
gm =
DiscreteGeometry with properties:
NumCells: 3
NumFaces: 7
NumEdges: 4
NumVertices: 4
5-312
findHeatSource
thermalmodel = createpde('thermal');
thermalmodel.Geometry = gm;
pdegplot(thermalmodel,'CellLabels','on','FaceAlpha',0.5)
Specify that the cylinder C1 generates heat at , the cylinder C2 generates heat
at , and the cylinder C3 generates heat at .
internalHeatSource(thermalmodel,10,'Cell',1);
internalHeatSource(thermalmodel,20,'Cell',2);
internalHeatSource(thermalmodel,30,'Cell',3);
5-313
5 Functions — Alphabetical List
hsaCell1 = findHeatSource(thermalmodel.HeatSources,'Cell',1)
hsaCell1 =
HeatSourceAssignment with properties:
RegionType: 'cell'
RegionID: 1
HeatSource: 10
hsaCell2 =
HeatSourceAssignment with properties:
RegionType: 'cell'
RegionID: 2
HeatSource: 20
hsaCell3 = hsa(2)
hsaCell3 =
HeatSourceAssignment with properties:
RegionType: 'cell'
RegionID: 3
HeatSource: 30
Input Arguments
thermalmodel.HeatSources — Internal heat source of the model
HeatSources property of a thermal model
5-314
findHeatSource
Geometric region type, specified as 'Face' for a 2-D model or 'Cell' for a 3-D model.
Data Types: char | string
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
the pdegplot function, as shown in “Create Geometry and Remove Face Boundaries” on
page 2-13 or “STL File Import” on page 2-47.
Data Types: double
Output Arguments
hsa — Heat source assignment
HeatSourceAssignment object
See Also
HeatSourceAssignment | internalHeatSource
Introduced in R2017a
5-315
5 Functions — Alphabetical List
findInitialConditions
Package: pde
Syntax
ic = findInitialConditions(ics,RegionType,RegionID)
Description
ic = findInitialConditions(ics,RegionType,RegionID) returns the active
initial condition assignment ic for the initial conditions in the specified region.
Examples
This example shows find the active initial conditions for a region.
model = createpde();
geometryFromEdges(model,@lshapeg);
pdegplot(model,'FaceLabels','on')
ylim([-1.1,1.1])
axis equal
5-316
findInitialConditions
ic =
GeometricInitialConditions with properties:
RegionType: 'face'
5-317
5 Functions — Alphabetical List
RegionID: [1 3]
InitialValue: 13
InitialDerivative: []
Input Arguments
ics — Model initial conditions
InitialConditions property of a PDE model
Geometric region type, specified as 'Edge' for a 2-D model, 'Face' for a 2-D model or
3-D model, or 'Cell' for a 3-D model.
Example: ca = findInitialConditions(ics,'Face',[1,3])
Data Types: char | string
RegionID — Region ID
vector of positive integers
Region ID, specified as a vector of positive integers. View the subdomain labels for a 2-D
model using pdegplot(model,'FaceLabels','on'). Currently, there are no
subdomains for 3-D models, so the only acceptable value for a 3-D model is 1.
Example: ca = findInitialConditions(ics,'Face',[1,3])
Data Types: double
Output Arguments
ic — Initial condition assignment
GeometricInitialConditions object | NodalInitialConditions object
5-318
findInitialConditions
See Also
GeometricInitialConditions | NodalInitialConditions | setInitialConditions
Topics
“View, Edit, and Delete Initial Conditions” on page 2-164
“Solve Problems Using PDEModel Objects” on page 2-6
“Initial Conditions”
Introduced in R2016a
5-319
5 Functions — Alphabetical List
findNodes
Package: pde
Syntax
nodes = findNodes(mesh,'region',RegionType,RegionID)
nodes = findNodes(mesh,'box',xlim,ylim)
nodes = findNodes(mesh,'box',xlim,ylim,zlim)
nodes = findNodes(mesh,'radius',center,radius)
nodes = findNodes(mesh,'nearest',point)
Description
nodes = findNodes(mesh,'region',RegionType,RegionID) returns the IDs of
the mesh nodes that belong to the specified geometric region.
Examples
5-320
findNodes
model = createpde;
Include the geometry of the built-in function lshapeg. Plot the geometry.
geometryFromEdges(model,@lshapeg);
pdegplot(model,'FaceLabels','on','EdgeLabels','on')
Generate a mesh.
5-321
5 Functions — Alphabetical List
mesh = generateMesh(model,'Hmax',0.5);
Nf2 = findNodes(mesh,'region','Face',2);
figure
pdemesh(model,'NodeLabels','on')
hold on
plot(mesh.Nodes(1,Nf2),mesh.Nodes(2,Nf2),'ok','MarkerFaceColor','g')
5-322
findNodes
5-323
5 Functions — Alphabetical List
model = createpde;
importGeometry(model,'PlateHolePlanar.stl');
pdegplot(model)
Generate a mesh.
mesh = generateMesh(model,'Hmax',2,'Hmin',0.4,'GeometricOrder','linear');
5-324
findNodes
figure
pdemesh(model)
hold on
plot(mesh.Nodes(1,Nb),mesh.Nodes(2,Nb),'or','MarkerFaceColor','g')
5-325
5 Functions — Alphabetical List
model = createpde;
importGeometry(model,'PlateHolePlanar.stl');
pdegplot(model)
Generate a mesh.
5-326
findNodes
mesh = generateMesh(model,'Hmax',2,'Hmin',0.4,'GeometricOrder','linear');
Find the nodes located within radius 2 from the center [5 10].
Nb = findNodes(mesh,'radius',[5 10],2);
5-327
5 Functions — Alphabetical List
Find the node closest to a specified point and highlight it on the mesh plot.
model = createpde;
importGeometry(model,'PlateHolePlanar.stl');
pdegplot(model)
Generate a mesh.
5-328
findNodes
mesh = generateMesh(model,'Hmax',2,'Hmin',0.4);
N_ID = 10
5-329
5 Functions — Alphabetical List
Input Arguments
mesh — Mesh object
Mesh property of a PDEModel object | output of generateMesh
Mesh object, specified as the Mesh property of a PDEModel object or as the output of
generateMesh.
Example: model.Mesh
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot, as shown in “Create Geometry and Remove Face Boundaries” on page 2-13 or
“STL File Import” on page 2-47.
Example: findNodes(mesh,'region','Face',1:3)
Data Types: double
x-limits of the bounding box, specified as a two-element row vector. The first element of
xlim is the lower x-bound, and the second element is the upper x-bound.
Example: findNodes(mesh,'box',[5 10],[10 20])
Data Types: double
y-limits of the bounding box, specified as a two-element row vector. The first element of
ylim is the lower y-bound, and the second element is the upper y-bound.
5-330
findNodes
z-limits of the bounding box, specified as a two-element row vector. The first element of
zlim is the lower z-bound, and the second element is the upper z-bound. You can specify
zlim only for 3-D meshes.
Example: findNodes(mesh,'box',[5 10],[10 20],[1 2])
Data Types: double
Center of the bounding circle or sphere, specified as a two-element row vector for a 2-D
mesh or three-element row vector for a 3-D mesh. The elements of these vectors contain
the coordinates of the center of a circle or a sphere.
Example: findNodes(mesh,'radius',[0 0 0],0.5)
Data Types: double
5-331
5 Functions — Alphabetical List
Output Arguments
nodes — Node IDs
positive integer | row vector of positive integers
See Also
FEMesh Properties | area | findElements | meshQuality | volume
Topics
“Finite Element Method Basics” on page 1-27
Introduced in R2018a
5-332
findStructuralBC
findStructuralBC
Package: pde
Find structural boundary conditions and boundary loads assigned to geometric region
Syntax
sbca = findStructuralBC(structuralmodel.BoundaryConditions,
RegionType,RegionID)
Description
sbca = findStructuralBC(structuralmodel.BoundaryConditions,
RegionType,RegionID) returns the structural boundary conditions and boundary loads
assigned to the region specified by RegionType and RegionID. The function returns
structural boundary conditions assigned by structuralBC and boundary loads assigned
by structuralBoundaryLoad.
Examples
Find the structural boundary conditions for the faces of a 3-D geometry.
structuralmodel = createpde('structural','static-solid');
Include the block geometry in the model and plot the geometry.
importGeometry(structuralmodel,'Block.stl');
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
5-333
5 Functions — Alphabetical List
structuralBoundaryLoad(structuralmodel,'Face',1,'SurfaceTraction',[100;10;300]);
structuralBoundaryLoad(structuralmodel,'Face',3,'Pressure',300);
structuralBC(structuralmodel,'Face',[5,6],'Constraint','free');
5-334
findStructuralBC
sbca = findStructuralBC(structuralmodel.BoundaryConditions,'Face',[1,3]);
sbcaFace1 = sbca(1)
sbcaFace1 =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 1
Vectorized: 'off'
Boundary Loads
SurfaceTraction: [3x1 double]
Pressure: []
TranslationalStiffness: []
sbcaFace3 = sbca(2)
sbcaFace3 =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 3
Vectorized: 'off'
Boundary Loads
SurfaceTraction: []
Pressure: 300
TranslationalStiffness: []
5-335
5 Functions — Alphabetical List
sbca = findStructuralBC(structuralmodel.BoundaryConditions,'Face',[5,6]);
sbcaFace5 = sbca(1)
sbcaFace5 =
StructuralBC with properties:
RegionType: 'Face'
RegionID: [5 6]
Vectorized: 'off'
Boundary Loads
SurfaceTraction: []
Pressure: []
TranslationalStiffness: []
sbcaFace6 = sbca(2)
sbcaFace6 =
StructuralBC with properties:
RegionType: 'Face'
RegionID: [5 6]
Vectorized: 'off'
Boundary Loads
SurfaceTraction: []
Pressure: []
5-336
findStructuralBC
TranslationalStiffness: []
Input Arguments
structuralmodel.BoundaryConditions — Structural boundary conditions
BoundaryConditions property of StructuralModel object
Geometric region type, specified as 'Edge' for a 2-D model or 'Face' for a 3-D model.
Example: findStructuralBC(structuralmodel.BoundaryConditions,'Edge',1)
Data Types: char | string
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot, as shown in “Create Geometry and Remove Face Boundaries” on page 2-13 or
“STL File Import” on page 2-47.
Example: findStructuralBC(structuralmodel.BoundaryConditions,'Face',
1:3)
Data Types: double
Output Arguments
sbca — Structural boundary conditions and boundary loads assignment
StructuralBC object
5-337
5 Functions — Alphabetical List
See Also
structuralBC | structuralBoundaryLoad
Introduced in R2017b
5-338
findStructuralIC
findStructuralIC
Package: pde
Syntax
sica = findStructuralIC(structuralmodel.InitialConditions,
RegionType,RegionID)
Description
sica = findStructuralIC(structuralmodel.InitialConditions,
RegionType,RegionID) returns the initial displacement and velocity assigned to the
specified region.
Examples
Find the initial displacement and velocity assigned to the cells of a 3-D geometry.
structuralmodel = createpde('structural','transient-solid');
Create the geometry consisting of the three nested cylinders and include it in the model.
Plot the geometry.
gm = multicylinder([5 10 15],2);
structuralmodel = createpde('structural','transient-solid');
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'CellLabels','on','FaceAlpha',0.5)
5-339
5 Functions — Alphabetical List
Set the initial conditions for each cell. When you specify only the initial velocity or initial
displacement, structuralIC assumes that the omitted parameter is zero.
structuralIC(structuralmodel,'Displacement',[0;0;0],'Velocity',[0;0;0],'Cell',1);
structuralIC(structuralmodel,'Displacement',[0;0.1;0],'Cell',2);
structuralIC(structuralmodel,'Velocity',[0;0.2;0],'Cell',3);
SICACell1 = findStructuralIC(structuralmodel.InitialConditions,'Cell',1)
SICACell1 =
GeometricStructuralICs with properties:
5-340
findStructuralIC
RegionType: 'Cell'
RegionID: 1
InitialDisplacement: [3x1 double]
InitialVelocity: [3x1 double]
SICACell1.InitialDisplacement
ans = 3×1
0
0
0
SICACell1.InitialVelocity
ans = 3×1
0
0
0
Use a static solution as an initial condition for a dynamic structural model. Check and plot
the initial displacement.
staticmodel = createpde('structural','static-solid');
Create the geometry and include it in the model. Plot the geometry.
gm = multicuboid(0.06,0.005,0.01);
staticmodel.Geometry = gm;
pdegplot(staticmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
5-341
5 Functions — Alphabetical List
structuralProperties(staticmodel,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3,...
'MassDensity',7800);
structuralBC(staticmodel,'Face',5,'Constraint','fixed');
structuralBoundaryLoad(staticmodel,'Face',3,'SurfaceTraction',[0;1E6;0]);
generateMesh(staticmodel,'Hmax',0.02);
Rstatic = solve(staticmodel);
5-342
findStructuralIC
dynamicmodel = createpde('structural','transient-solid');
gm = multicuboid(0.06,0.005,0.01);
dynamicmodel.Geometry = gm;
structuralBC(dynamicmodel,'Face',5,'Constraint','fixed');
generateMesh(dynamicmodel,'Hmax',0.02);
structuralIC(dynamicmodel,Rstatic)
ans =
NodalStructuralICs with properties:
sica = findStructuralIC(dynamicmodel.InitialConditions,'Cell',1)
sica =
NodalStructuralICs with properties:
pdeplot3D(dynamicmodel,'ColorMapData',sica.InitialDisplacement(:,3))
title('Initial Displacement in the Z-direction')
5-343
5 Functions — Alphabetical List
Input Arguments
structuralmodel.InitialConditions — Initial conditions
InitialConditions property of a StructuralModel object
5-344
findStructuralIC
Geometric region type, specified as 'Face', 'Edge', or 'Vertex' for a 2-D model or 3-
D model, or 'Cell' for a 3-D model.
Data Types: char
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot, as shown in “Create Geometry and Remove Face Boundaries” on page 2-13 or
“STL File Import” on page 2-47.
Data Types: double
Output Arguments
sica — Structural initial condition assignment
GeometricStructuralICs object | NodalStructuralICs object
See Also
GeometricStructuralICs Properties | NodalStructuralICs Properties | StructuralModel |
structuralIC
Introduced in R2018a
5-345
5 Functions — Alphabetical List
findStructuralProperties
Package: pde
Syntax
smpa = findStructuralProperties(structuralmodel.MaterialProperties,
RegionType,RegionID)
Description
smpa = findStructuralProperties(structuralmodel.MaterialProperties,
RegionType,RegionID) returns the structural material properties assigned to the
specified region. Structural properties include the Young's modulus, Poisson's ratio, and
mass density of the material.
Examples
Find Young's modulus and Poisson's ratio for cells of a 3-D geometry.
structuralmodel = createpde('structural','static-solid');
Create the geometry consisting of three stacked cylinders and include it in the model.
Plot the geometry.
5-346
findStructuralProperties
Assign different values of the Young's modulus and Poisson's ratio to each cell.
structuralProperties(structuralmodel,'Cell',1,'YoungsModulus',200E9, ...
'PoissonsRatio',0.3);
structuralProperties(structuralmodel,'Cell',2,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3);
structuralProperties(structuralmodel,'Cell',3,'YoungsModulus',110E9, ...
'PoissonsRatio',0.35);
mC1 =
StructuralMaterialAssignment with properties:
5-347
5 Functions — Alphabetical List
RegionType: 'Cell'
RegionID: 1
YoungsModulus: 2.0000e+11
PoissonsRatio: 0.3000
MassDensity: []
CTE: []
mC23 = findStructuralProperties(structuralmodel.MaterialProperties,'Cell',[2,3]);
mC2 = mC23(1)
mC2 =
StructuralMaterialAssignment with properties:
RegionType: 'Cell'
RegionID: 2
YoungsModulus: 2.1000e+11
PoissonsRatio: 0.3000
MassDensity: []
CTE: []
mC3 = mC23(2)
mC3 =
StructuralMaterialAssignment with properties:
RegionType: 'Cell'
RegionID: 3
YoungsModulus: 1.1000e+11
PoissonsRatio: 0.3500
MassDensity: []
CTE: []
Input Arguments
structuralmodel.MaterialProperties — Material properties
MaterialProperties property of StructuralModel object
5-348
findStructuralProperties
Geometric region type, specified as 'Face' for a 2-D model or 'Cell' for a 3-D model.
Example:
findStructuralProperties(structuralmodel.MaterialProperties,'Cell',
1)
Data Types: char | string
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot, as shown in “Create Geometry and Remove Face Boundaries” on page 2-13 or
“STL File Import” on page 2-47.
Example:
findStructuralProperties(structuralmodel.MaterialProperties,'Face',
1:3)
Data Types: double
Output Arguments
smpa — Material properties assignment
StructuralMaterialAssignment object
See Also
StructuralMaterialAssignment Properties | structuralProperties
5-349
5 Functions — Alphabetical List
Introduced in R2017b
5-350
findThermalBC
findThermalBC
Package: pde
Syntax
tbca = findThermalBC(thermalmodel.BoundaryConditions,RegionType,
RegionID)
Description
tbca = findThermalBC(thermalmodel.BoundaryConditions,RegionType,
RegionID) returns the thermal boundary condition assigned to the specified region.
Examples
thermalmodel = createpde('thermal');
geometryFromEdges(thermalmodel,@squareg);
pdegplot(thermalmodel,'EdgeLabels','on')
ylim([-1.1 1.1])
axis equal
5-351
5 Functions — Alphabetical List
tbcaEdge1 =
ThermalBC with properties:
5-352
findThermalBC
RegionType: 'Edge'
RegionID: [1 3]
Temperature: 100
HeatFlux: []
ConvectionCoefficient: []
Emissivity: []
AmbientTemperature: []
Vectorized: 'off'
tbca = findThermalBC(thermalmodel.BoundaryConditions,'Edge',[3:4]);
tbcaEdge3 = tbca(1)
tbcaEdge3 =
ThermalBC with properties:
RegionType: 'Edge'
RegionID: [1 3]
Temperature: 100
HeatFlux: []
ConvectionCoefficient: []
Emissivity: []
AmbientTemperature: []
Vectorized: 'off'
tbcaEdge4 = tbca(2)
tbcaEdge4 =
ThermalBC with properties:
RegionType: 'Edge'
RegionID: 4
Temperature: []
HeatFlux: 20
ConvectionCoefficient: []
Emissivity: []
AmbientTemperature: []
Vectorized: 'off'
5-353
5 Functions — Alphabetical List
thermalmodel = createpde('thermal','transient');
gm = importGeometry(thermalmodel,'Block.stl');
pdegplot(thermalmodel,'FaceLabels','on','FaceAlpha',0.5)
thermalBC(thermalmodel,'Face',1,'Temperature',100);
thermalBC(thermalmodel,'Face',3,'Temperature',300);
5-354
findThermalBC
thermalBC(thermalmodel,'Face',[5,6],...
'ConvectionCoefficient',5,...
'AmbientTemperature',27);
tbcaFace1 =
ThermalBC with properties:
RegionType: 'Face'
RegionID: 1
Temperature: 100
HeatFlux: []
ConvectionCoefficient: []
Emissivity: []
AmbientTemperature: []
Vectorized: 'off'
tbcaFace3 = tbca(2)
tbcaFace3 =
ThermalBC with properties:
RegionType: 'Face'
RegionID: 3
Temperature: 300
HeatFlux: []
ConvectionCoefficient: []
Emissivity: []
AmbientTemperature: []
Vectorized: 'off'
tbcaFace5 =
ThermalBC with properties:
RegionType: 'Face'
RegionID: [5 6]
5-355
5 Functions — Alphabetical List
Temperature: []
HeatFlux: []
ConvectionCoefficient: 5
Emissivity: []
AmbientTemperature: 27
Vectorized: 'off'
tbcaFace6 = findThermalBC(thermalmodel.BoundaryConditions,'Face',6)
tbcaFace6 =
ThermalBC with properties:
RegionType: 'Face'
RegionID: [5 6]
Temperature: []
HeatFlux: []
ConvectionCoefficient: 5
Emissivity: []
AmbientTemperature: 27
Vectorized: 'off'
Input Arguments
thermalmodel.BoundaryConditions — Boundary conditions of a thermal model
BoundaryConditions property of a thermal model
Geometric region type, specified as 'Face' for 3-D geometry or 'Edge' for 2-D
geometry.
Data Types: char | string
5-356
findThermalBC
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot with the 'FaceLabels' (3-D) or 'EdgeLabels' (2-D) value set to 'on'.
Data Types: double
Output Arguments
tbca — Thermal boundary condition for a particular region
ThermalBC object
See Also
ThermalBC | thermalBC
Introduced in R2017a
5-357
5 Functions — Alphabetical List
findThermalIC
Package: pde
Syntax
tica = findThermalIC(thermalmodel.InitialConditions,RegionType,
RegionID)
Description
tica = findThermalIC(thermalmodel.InitialConditions,RegionType,
RegionID) returns the thermal initial condition assigned to the specified region.
Examples
thermalmodel = createpde('thermal','transient');
geometryFromEdges(thermalmodel,@lshapeg);
pdegplot(thermalmodel,'FaceLabels','on')
ylim([-1.1 1.1])
axis equal
5-358
findThermalIC
ticaFace1 =
GeometricThermalICs with properties:
RegionType: 'face'
RegionID: 1
5-359
5 Functions — Alphabetical List
InitialTemperature: 10
ticaFace2 =
GeometricThermalICs with properties:
RegionType: 'face'
RegionID: 2
InitialTemperature: 20
ticaFace3 = tica(2)
ticaFace3 =
GeometricThermalICs with properties:
RegionType: 'face'
RegionID: 3
InitialTemperature: 30
Create a geometry that consists of three nested cylinders and include the geometry in a
transient thermal model.
gm = multicylinder([5 10 15],2)
gm =
DiscreteGeometry with properties:
NumCells: 3
NumFaces: 9
NumEdges: 6
NumVertices: 6
5-360
findThermalIC
thermalmodel = createpde('thermal','transient');
thermalmodel.Geometry = gm;
pdegplot(thermalmodel,'CellLabels','on','FaceAlpha',0.5)
thermalIC(thermalmodel,0,'Cell',1);
thermalIC(thermalmodel,100,'Cell',2);
thermalIC(thermalmodel,0,'Cell',3);
ticaCell1 = findThermalIC(thermalmodel.InitialConditions,'Cell',1)
5-361
5 Functions — Alphabetical List
ticaCell1 =
GeometricThermalICs with properties:
RegionType: 'cell'
RegionID: 1
InitialTemperature: 0
tica = findThermalIC(thermalmodel.InitialConditions,'Cell',[2:3]);
ticaCell2 = tica(1)
ticaCell2 =
GeometricThermalICs with properties:
RegionType: 'cell'
RegionID: 2
InitialTemperature: 100
ticaCell3 = tica(2)
ticaCell3 =
GeometricThermalICs with properties:
RegionType: 'cell'
RegionID: 3
InitialTemperature: 0
thermalmodel = createpde('thermal','transient');
gm = @squareg;
geometryFromEdges(thermalmodel,gm);
pdegplot(thermalmodel,'FaceLabels','on')
ylim([-1.1 1.1])
axis equal
5-362
findThermalIC
Specify material properties, heat source, set initial and boundary conditions.
thermalProperties(thermalmodel,'ThermalConductivity',500,...
'MassDensity',200,...
'SpecificHeat',100);
internalHeatSource(thermalmodel,2);
thermalBC(thermalmodel,'Edge',[1 3],'Temperature',100);
thermalIC(thermalmodel,0);
generateMesh(thermalmodel);
tlist = 0:0.5:10;
result1 = solve(thermalmodel,tlist)
5-363
5 Functions — Alphabetical List
result1 =
TransientThermalResults with properties:
tica =
GeometricThermalICs with properties:
RegionType: 'face'
RegionID: 1
InitialTemperature: 0
Now, resume the analysis and solve the problem for times from 10 to 15 seconds. Use the
previously obtained solution for 10 seconds as an initial condition. Since 10 seconds is the
last element in tlist, you do not need to specify the solution time index. By default,
thermalIC uses the last solution index.
ic = thermalIC(thermalmodel,result1);
tica =
NodalThermalICs with properties:
pdeplot(thermalmodel,'XYData',tica.InitialTemperature)
5-364
findThermalIC
Input Arguments
thermalmodel.InitialConditions — Initial conditions of a thermal model
InitialConditions property of a thermal model
5-365
5 Functions — Alphabetical List
Geometric region type, specified as 'Edge', 'Face', or 'Vertex' for a 2-D model or 3-
D model, or 'Cell' for a 3-D model.
Data Types: char | string
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
the pdegplot function with the 'FaceLabels' (3-D) or 'EdgeLabels' (2-D) value set
to 'on'.
Data Types: double
Output Arguments
tica — Thermal initial condition for a particular region
GeometricThermalICs object | NodalThermalICs object
See Also
GeometricThermalICs | NodalThermalICs | thermalIC
Introduced in R2017a
5-366
findThermalProperties
findThermalProperties
Package: pde
Syntax
tmpa = findThermalProperties(thermalmodel.MaterialProperties,
RegionType,RegionID)
Description
tmpa = findThermalProperties(thermalmodel.MaterialProperties,
RegionType,RegionID) returns thermal material properties tmpa assigned to the
specified region.
Examples
Find Thermal Conductivity, Mass Density, and Specific Heat for Faces of 2-D
Geometry
thermalmodel = createpde('thermal','transient');
geometryFromEdges(thermalmodel,@lshapeg);
pdegplot(thermalmodel,'FaceLabels','on')
ylim([-1.1,1.1])
axis equal
5-367
5 Functions — Alphabetical List
thermalProperties(thermalmodel,'ThermalConductivity',10,...
'MassDensity',1,...
'SpecificHeat',0.1,...
'Face',1);
5-368
findThermalProperties
thermalProperties(thermalmodel,'ThermalConductivity',20,...
'MassDensity',2,...
'SpecificHeat',0.2,...
'Face',2);
For face 1, specify the following thermal properties: thermal conductivity is 30 W/(m*C),
mass density is 3 kg/m^3, specific heat is 0.3 J/(kg*C).
thermalProperties(thermalmodel,'ThermalConductivity',30,...
'MassDensity',3,...
'SpecificHeat',0.3,...
'Face',3);
mpaFace1 = findThermalProperties(thermalmodel.MaterialProperties,'Face',1)
mpaFace1 =
ThermalMaterialAssignment with properties:
RegionType: 'face'
RegionID: 1
ThermalConductivity: 10
MassDensity: 1
SpecificHeat: 0.1000
mpa = findThermalProperties(thermalmodel.MaterialProperties,'Face',[2,3]);
mpaFace2 = mpa(1)
mpaFace2 =
ThermalMaterialAssignment with properties:
5-369
5 Functions — Alphabetical List
RegionType: 'face'
RegionID: 2
ThermalConductivity: 20
MassDensity: 2
SpecificHeat: 0.2000
mpaFace3 = mpa(2)
mpaFace3 =
ThermalMaterialAssignment with properties:
RegionType: 'face'
RegionID: 3
ThermalConductivity: 30
MassDensity: 3
SpecificHeat: 0.3000
Create a geometry that consists of three stacked cylinders and include the geometry in a
thermal model.
gm =
DiscreteGeometry with properties:
NumCells: 3
NumFaces: 7
NumEdges: 4
NumVertices: 4
thermalmodel = createpde('thermal');
thermalmodel.Geometry = gm;
pdegplot(thermalmodel,'CellLabels','on','FaceAlpha',0.5)
5-370
findThermalProperties
5-371
5 Functions — Alphabetical List
mpaCell1 =
ThermalMaterialAssignment with properties:
RegionType: 'cell'
RegionID: 1
ThermalConductivity: 10
MassDensity: []
SpecificHeat: []
mpa = findThermalProperties(thermalmodel.MaterialProperties,'Cell',2:3);
mpaCell2 = mpa(1)
mpaCell2 =
ThermalMaterialAssignment with properties:
RegionType: 'cell'
RegionID: 2
ThermalConductivity: 20
MassDensity: []
SpecificHeat: []
mpaCell3 = mpa(2)
mpaCell3 =
ThermalMaterialAssignment with properties:
RegionType: 'cell'
RegionID: 3
ThermalConductivity: 30
MassDensity: []
SpecificHeat: []
Input Arguments
thermalmodel.MaterialProperties — Material properties of the model
MaterialProperties property of a thermal model
5-372
findThermalProperties
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot, as shown in “Create Geometry and Remove Face Boundaries” on page 2-13 or
“STL File Import” on page 2-47.
Example: findThermalProperties(thermalmodel.MaterialProperties,'Face',
1:3)
Data Types: double
Output Arguments
tmpa — Material properties assignment
ThermalMaterialAssignment object
See Also
ThermalMaterialAssignment | thermalProperties
Introduced in R2017a
5-373
5 Functions — Alphabetical List
generateMesh
Package: pde
Syntax
generateMesh(model)
generateMesh(model,Name,Value)
mesh = generateMesh( ___ )
Description
generateMesh(model) creates a mesh and stores it in the model object. model must
contain geometry. To include 2-D geometry in a model, use geometryFromEdges. To
include 3-D geometry, use importGeometry or geometryFromMesh.
generateMesh can return slightly different meshes in different releases. For example,
the number of elements in the mesh can change. Avoid writing code that relies on
explicitly specified node and element IDs.
mesh = generateMesh( ___ ) also returns the mesh to the MATLAB workspace, using
any of the previous syntaxes.
Examples
5-374
generateMesh
model = createpde(1);
geometryFromEdges(model,@lshapeg);
generateMesh(model);
pdeplot(model)
5-375
5 Functions — Alphabetical List
model = createpde(1);
importGeometry(model,'BracketTwoHoles.stl');
generateMesh(model)
ans =
FEMesh with properties:
pdeplot3D(model)
5-376
generateMesh
Create a mesh with target maximum element size 5 instead of the default 7.3485.
generateMesh(model,'Hmax',5)
ans =
FEMesh with properties:
5-377
5 Functions — Alphabetical List
Input Arguments
model — PDE model
PDEModel object
5-378
generateMesh
Mesh growth rate, specified as the comma-separated pair consisting of Hgrad and a
number number greater than or equal to 1 and less than or equal to 2.
Example: generateMesh(model,'Hgrad',1.3);
Data Types: double
Target maximum mesh edge length, specified as the comma-separated pair consisting of
Hmax and a positive real number.
generateMesh estimates the default value of Hmax from overall dimensions of the
geometry.
5-379
5 Functions — Alphabetical List
Small Hmax values let you create finer meshes, but mesh generation can take a very long
time in this case. You can interrupt mesh generation by using Ctrl+C. Note that
generateMesh can take additional time to respond to the interrupt.
Example: generateMesh(model,'Hmax',0.25);
Data Types: double
Target minimum mesh edge length, specified as the comma-separated pair consisting of
Hmin and a nonnegative real number.
generateMesh estimates the default value of Hmin from overall dimensions of the
geometry.
Example: generateMesh(model,'Hmin',0.05);
Data Types: double
Output Arguments
mesh — Mesh description
FEMesh object
Definitions
Element
An element is a basic unit in the finite-element method.
5-380
generateMesh
For 3-D problems, an element is a tetrahedron with either four or ten points. A four-point
(linear) tetrahedron has nodes only at its corners. A ten-point (quadratic) tetrahedron has
nodes at its corners and at the center point of each edge.
See Also
FEMesh | PDEModel | geometryFromEdges | importGeometry
Topics
“Solve Problems Using PDEModel Objects” on page 2-6
“Finite Element Method Basics” on page 1-27
“Mesh Data” on page 2-241
“Mesh Data as [p,e,t] Triples” on page 2-238
Introduced in R2015a
5-381
5 Functions — Alphabetical List
GeometricInitialConditions Properties
Initial conditions over a region or region boundary
Description
A GeometricInitialConditions object contains a description of the initial conditions
over a geometric region or boundary of the region. A PDEModel container has a vector of
GeometricInitialConditions objects in its
InitialConditions.InitialConditionAssignments property.
Set initial conditions for your model using the setInitialConditions function.
Properties
Properties
Region type, returned as 'face' for a 2-D region, or 'cell' for a 3-D region.
Data Types: char
RegionID — Region ID
vector of positive integers
Initial value, returned as a scalar, vector, or function handle. For details, see
setInitialConditions.
5-382
GeometricInitialConditions Properties
Initial derivative, returned as a scalar, vector, or function handle. For details, see
setInitialConditions.
Data Types: double | function_handle
Complex Number Support: Yes
See Also
NodalInitialConditions | findInitialConditions | setInitialConditions
Topics
“Set Initial Conditions” on page 2-161
“View, Edit, and Delete Initial Conditions” on page 2-164
“Solve Problems Using PDEModel Objects” on page 2-6
Introduced in R2016a
5-383
5 Functions — Alphabetical List
GeometricStructuralICs Properties
Initial displacement and velocity over a region
Description
A GeometricStructuralICs object contains a description of the initial displacement
and velocity over a geometric region for a transient structural model. A
StructuralModel container has a vector of GeometricStructuralICs objects in its
InitialConditions.StructuralICAssignments property.
To set initial conditions for your structural model, use the structuralIC function.
Properties
Properties
Geometric region type, returned as 'Face', 'Edge', or 'Vertex' for a 2-D model or 3-D
model, or 'Cell' for a 3-D model.
Data Types: char
Geometric region ID, returned as a vector of positive integers. Find the region IDs using
pdegplot, as shown in “Create Geometry and Remove Face Boundaries” on page 2-13 or
“STL File Import” on page 2-47.
Data Types: double
Initial displacement, returned as a numeric vector or function handle. For details, see
structuralIC.
5-384
GeometricStructuralICs Properties
Initial velocity, returned as a numeric vector or function handle. For details, see
structuralIC.
Data Types: double | function_handle
See Also
NodalStructuralICs Properties | findStructuralIC | structuralIC
Introduced in R2018a
5-385
5 Functions — Alphabetical List
GeometricThermalICs Properties
Initial temperature over a region or region boundary
Description
A GeometricThermalICs object contains a description of the initial temperature over a
geometric region or a boundary of the region. A ThermalModel container has a vector of
GeometricThermalICs objects in its InitialConditions.ThermalICAssignments
property.
Set initial conditions for your model using the thermalIC function.
Properties
Properties
Region type, returned as 'Vertex', 'Edge', or 'Face' for a 2-D or 3-D region, or
'Cell' for a 3-D region.
Data Types: char
RegionID — Region ID
vector of positive integers
Initial temperature, returned as a scalar, vector, or function handle. For details, see
thermalIC.
5-386
GeometricThermalICs Properties
See Also
NodalThermalICs | findThermalIC | thermalIC
Introduced in R2017a
5-387
5 Functions — Alphabetical List
NodalInitialConditions Properties
Initial conditions at mesh nodes
Description
A NodalInitialConditions object contains a description of the initial conditions at
mesh nodes. A PDEModel container has a vector of NodalInitialConditions objects
in its InitialConditions.InitialConditionAssignments property.
Set initial conditions for your model using the setInitialConditions function.
Properties
Properties
Initial value, returned as a scalar, vector, or function handle. For details, see
setInitialConditions.
Data Types: double | function_handle
Complex Number Support: Yes
Initial derivative, returned as a scalar, vector, or function handle. For details, see
setInitialConditions.
Data Types: double | function_handle
Complex Number Support: Yes
See Also
GeometricInitialConditions | findInitialConditions | setInitialConditions
5-388
NodalInitialConditions Properties
Topics
“Set Initial Conditions” on page 2-161
“View, Edit, and Delete Initial Conditions” on page 2-164
“Solve Problems Using PDEModel Objects” on page 2-6
Introduced in R2016b
5-389
5 Functions — Alphabetical List
NodalStructuralICs Properties
Initial displacement and velocity at mesh nodes
Description
A NodalStructuralICs object contains a description of the initial displacement and
velocity at mesh nodes. A StructuralModel container has a vector of
GeometricStructuralICs objects in its
InitialConditions.StructuralICAssignments property.
To set initial conditions for your structural model, use the structuralIC function.
Properties
Properties
Initial displacement, returned as a numeric vector or function handle. For details, see
structuralIC.
Data Types: double | function_handle
Initial velocity, returned as a numeric vector or function handle. For details, see
structuralIC.
Data Types: double | function_handle
See Also
GeometricStructuralICs Properties | findStructuralIC | structuralIC
5-390
NodalStructuralICs Properties
Introduced in R2018a
5-391
5 Functions — Alphabetical List
NodalThermalICs Properties
Initial temperature at mesh nodes
Description
A NodalThermalICs object contains a description of the initial temperatures at mesh
nodes. A ThermalModel container has a vector of NodalThermalICs objects in its
InitialConditions.ThermalICAssignments property.
Set initial conditions for your model using the thermalIC function.
Properties
Properties
Initial temperature, returned as a scalar, vector, or function handle. For details, see
thermalIC.
Data Types: double | function_handle
See Also
GeometricThermalICs | findThermalIC | thermalIC
Introduced in R2017a
5-392
geometryFromEdges
geometryFromEdges
Package: pde
Syntax
geometryFromEdges(model,g)
pg = geometryFromEdges(model,g)
Description
geometryFromEdges(model,g) adds the 2-D geometry described in g to the model
container.
Examples
model = createpde;
Define a circle in a rectangle, place these in one matrix, and create a set formula that
subtracts the circle from the rectangle.
R1 = [3,4,-1,1,1,-1,0.5,0.5,-0.75,-0.75]';
C1 = [1,0.5,-0.25,0.25]';
C1 = [C1;zeros(length(R1) - length(C1),1)];
5-393
5 Functions — Alphabetical List
gm = [R1,C1];
sf = 'R1-C1';
5-394
geometryFromEdges
Input Arguments
model — PDE model
PDEModel object
g — Geometry description
decomposed geometry matrix | name of a geometry function | handle to a geometry
function
Output Arguments
pg — Geometry object
AnalyticGeometry object
See Also
AnalyticGeometry | PDEModel
Topics
“Solve PDEs with Constant Boundary Conditions” on page 2-188
“Solve Problems Using PDEModel Objects” on page 2-6
“Geometry”
5-395
5 Functions — Alphabetical List
Introduced in R2015a
5-396
geometryFromMesh
geometryFromMesh
Package: pde
Syntax
geometryFromMesh(model,nodes,elements)
geometryFromMesh(model,nodes,elements,ElementIDToRegionID)
[G,mesh] = geometryFromMesh(model,nodes,elements)
Description
geometryFromMesh(model,nodes,elements) creates geometry within model. For
planar and volume triangulated meshes, this function also incorporates nodes in the
model.Mesh.Nodes property and elements in the model.Mesh.Elements property. To
replace the imported mesh with a mesh having a different target element size, use
generateMesh.
If elements represents a surface triangular mesh that bounds a closed volume, then
geometryFromMesh creates the geometry, but does not incorporate the mesh into the
corresponding properties of the model. To generate a mesh in this case, use
generateMesh.
geometryFromMesh(model,nodes,elements,ElementIDToRegionID) creates a
multidomain geometry. Here, ElementIDToRegionID specifies the subdomain IDs for
each element of the mesh.
Examples
5-397
5 Functions — Alphabetical List
Load a tetrahedral mesh into your workspace. The tetmesh file ships with your software.
Put the data in the correct shape for geometryFromMesh.
load tetmesh
nodes = X';
elements = tet';
Create a PDE model and import the mesh into the model.
model = createpde();
geometryFromMesh(model,nodes,elements);
pdegplot(model,'FaceLabels','on','FaceAlpha',0.5)
5-398
geometryFromMesh
Create a geometric block from the convex hull of a mesh grid of points.
5-399
5 Functions — Alphabetical List
z = z(:);
K = convhull(x,y,z);
nodes = [x';y';z'];
elements = K';
model = createpde();
geometryFromMesh(model,nodes,elements);
pdegplot(model,'FaceLabels','on','FaceAlpha',0.5)
5-400
geometryFromMesh
Create a 3-D geometry using the MATLAB alphaShape function. First, create an
alphaShape object of a block with a cylindrical hole. Then import the geometry into a PDE
model from the alphaShape boundary.
5-401
5 Functions — Alphabetical List
Create a unit disk. Remove all the mesh grid points that fall inside the unit disk, and
include the unit disk points.
t = (pi/24:pi/24:2*pi)';
x = cos(t);
y = sin(t);
circShp = alphaShape(x,y,2);
in = inShape(circShp,xg,yg);
xg = [xg(~in); cos(t)];
yg = [yg(~in); sin(t)];
Create 3-D copies of the remaining mesh grid points, with the z-coordinates ranging from
0 through 1. Combine the points into an alphaShape object.
zg = ones(numel(xg),1);
xg = repmat(xg,5,1);
yg = repmat(yg,5,1);
zg = zg*(0:.25:1);
zg = zg(:);
shp = alphaShape(xg,yg,zg);
[elements,nodes] = boundaryFacets(shp);
nodes = nodes';
elements = elements';
model = createpde();
geometryFromMesh(model,nodes,elements);
pdegplot(model,'FaceLabels','on','FaceAlpha',0.5)
5-402
geometryFromMesh
5-403
5 Functions — Alphabetical List
model = createpde;
geometryFromMesh(model,nodes,elements,ElementIdToRegionId);
pdegplot(model,'FaceLabels','on')
5-404
geometryFromMesh
load MultidomainMesh3D
model = createpde;
geometryFromMesh(model,nodes,elements,ElementIdToRegionId);
pdegplot(model,'CellLabels','on')
5-405
5 Functions — Alphabetical List
Input Arguments
model — PDE model
PDEModel object
5-406
geometryFromMesh
Mesh nodes, specified as a matrix of real numbers. The matrix size is 2-by-Nnodes for a 2-
D case and 3-by-Nnodes for a 3-D case. Nnodes is the number of nodes in the mesh.
• A mesh on the geometry surface has size 3-by-Nelements. Each column of elements
contains the indices of the triangle corner nodes for a surface element. In this case,
the resulting geometry does not contain a full mesh. Create the mesh using the
generateMesh function.
• Linear elements have size 4-by-Nelements. Each column of elements contains the
indices of the tetrahedral corner nodes for an element.
• Quadratic elements have size 10-by-Nelements. Each column of elements contains
the indices of the tetrahedral corner nodes and the tetrahedral edge midpoint nodes
for an element.
For details on node numbering for linear and quadratic elements, see “Mesh Data” on
page 2-241.
Data Types: double
Domain information for each mesh element, specified as a vector of positive integers.
Each element is an ID of a geometric region for an element of the mesh. The length of this
vector equals the number of elements in the mesh.
Data Types: double
5-407
5 Functions — Alphabetical List
Output Arguments
G — Geometry
handle to model.Geometry
See Also
DiscreteGeometry | alphaShape | generateMesh | importGeometry
Topics
“STL File Import” on page 2-47
“Solve Problems Using PDEModel Objects” on page 2-6
Introduced in R2015b
5-408
HeatSourceAssignment Properties
HeatSourceAssignment Properties
Heat source assignments
Description
A HeatSourceAssignment object contains a description of the heat sources for a
thermal model. A ThermalModel container has a vector of HeatSourceAssignment
objects in its HeatSources.HeatSourceAssignments property.
Create heat source assignments for your thermal model using the internalHeatSource
function.
Properties
Properties
Region type, returned as 'Face' for a 2-D region, or 'Cell' for a 3-D region.
Data Types: char
RegionID — Region ID
vector of positive integers
Heat source value, returned as a number or a function handle. A heat source with a
negative value is called a heat sink.
5-409
5 Functions — Alphabetical List
See Also
findHeatSource | internalHeatSource
Introduced in R2017a
5-410
hyperbolic
hyperbolic
(Not recommended) Solve hyperbolic PDE problem
∂ 2u
d - — ◊ ( c— u) + au = f
∂t2
∂2 u
d - — ◊ ( c ƒ — u ) + au = f
∂ t2
The variables c, a, f, and d can depend on position, time, and the solution u and its
gradient.
Syntax
u = hyperbolic(u0,ut0,tlist,model,c,a,f,d)
u = hyperbolic(u0,ut0,tlist,b,p,e,t,c,a,f,d)
u = hyperbolic(u0,ut0,tlist,Kc,Fc,B,ud,M)
u = hyperbolic( ___ ,rtol)
u = hyperbolic( ___ ,rtol,atol)
u = hyperbolic(u0,ut0,tlist,Kc,Fc,B,ud,M, ___ ,'DampingMatrix',D)
u = hyperbolic( ___ ,'Stats','off')
5-411
5 Functions — Alphabetical List
Description
u = hyperbolic(u0,ut0,tlist,model,c,a,f,d) produces the solution to the FEM
formulation of the scalar PDE problem
∂ 2u
d - — ◊ ( c— u) + au = f
∂t2
∂2 u
d - — ◊ ( c ƒ — u ) + au = f
∂ t2
with geometry, mesh, and boundary conditions specified in model, with initial value u0
and initial derivative with respect to time ut0. The variables c, a, f, and d in the equation
correspond to the function coefficients c, a, f, and d respectively.
u = hyperbolic( ___ ,'Stats','off') turns off the display of internal ODE solver
statistics during the solution process.
Examples
Hyperbolic Equation
5-412
hyperbolic
model = createpde;
geometryFromEdges(model,@squareg);
pdegplot(model,'EdgeLabels','on')
ylim([-1.1,1.1])
axis equal
5-413
5 Functions — Alphabetical List
for . (The Neumann boundary condition is the default condition, so the second
specification is redundant.)
applyBoundaryCondition(model,'dirichlet','Edge',[2,4],'u',0);
applyBoundaryCondition(model,'neumann','Edge',[1,3],'g',0);
u0 = 'atan(cos(pi/2*x))';
ut0 = '3*sin(pi*x).*exp(cos(pi*y))';
tlist = linspace(0,5,31);
c = 1;
a = 0;
f = 0;
d = 1;
generateMesh(model,'GeometricOrder','linear','Hmax',0.1);
u1 = hyperbolic(u0,ut0,tlist,model,c,a,f,d);
figure
pdeplot(model,'XYData',u1(:,1))
5-414
hyperbolic
figure
pdeplot(model,'XYData',u1(:,end))
5-415
5 Functions — Alphabetical List
For a version of this example with animation, see “Wave Equation on Square Domain”.
5-416
hyperbolic
on the square domain specified by squareg, using a geometry function to specify the
geometry, a boundary function to specify the boundary conditions, and using initmesh to
create the finite element mesh.
g = @squareg;
pdegplot(g,'EdgeLabels','on')
ylim([-1.1,1.1])
axis equal
5-417
5 Functions — Alphabetical List
for . (The Neumann boundary condition is the default condition, so the second
specification is redundant.)
b = @squareb3;
u0 = 'atan(cos(pi/2*x))';
ut0 = '3*sin(pi*x).*exp(cos(pi*y))';
tlist = linspace(0,5,31);
c = 1;
a = 0;
f = 0;
d = 1;
[p,e,t] = initmesh(g);
u = hyperbolic(u0,ut0,tlist,b,p,e,t,c,a,f,d);
figure
pdeplot(p,e,t,'XYData',u(:,1))
5-418
hyperbolic
figure
pdeplot(p,e,t,'XYData',u(:,end))
5-419
5 Functions — Alphabetical List
For a version of this example with animation, see “Wave Equation on Square Domain”.
model = createpde();
importGeometry(model,'BracketWithHole.stl');
figure
5-420
hyperbolic
pdegplot(model,'FaceLabels','on')
view(30,30)
title('Bracket with Face Labels')
figure
pdegplot(model,'FaceLabels','on')
view(-134,-32)
title('Bracket with Face Labels, Rear View')
5-421
5 Functions — Alphabetical List
c = 1;
a = 0;
f = 0.5;
d = 1;
generateMesh(model);
Create initial conditions and boundary conditions. The boundary condition for the rear
face is Dirichlet with value 0. All other faces have the default boundary condition. The
5-422
hyperbolic
initial condition is u(0) = 0, du/dt(0) = x/2. Give the initial condition on the
derivative by calculating the x-position of each node in xpts, and passing x/2.
applyBoundaryCondition(model,'Face',4,'u',0);
u0 = 0;
xpts = model.Mesh.Nodes(1,:);
ut0 = xpts(:)/2;
[Kc,Fc,B,ud] = assempde(model,c,a,f);
[~,M,~] = assema(model,0,d,f);
tlist = linspace(0,5,50);
u = hyperbolic(u0,ut0,tlist,Kc,Fc,B,ud,M);
View the solution at a few times. Scale all the plots to have the same color range by using
the caxis command.
umax = max(max(u));
umin = min(min(u));
subplot(2,2,1)
pdeplot3D(model,'ColorMapData',u(:,5))
caxis([umin umax])
title('Time 1/2')
subplot(2,2,2)
pdeplot3D(model,'ColorMapData',u(:,10))
caxis([umin umax])
title('Time 1')
subplot(2,2,3)
pdeplot3D(model,'ColorMapData',u(:,15))
caxis([umin umax])
title('Time 3/2')
subplot(2,2,4)
pdeplot3D(model,'ColorMapData',u(:,20))
5-423
5 Functions — Alphabetical List
caxis([umin umax])
title('Time 2')
The solution seems to have a frequency of one, because the plots at times 1/2 and 3/2
show maximum values, and those at times 1 and 2 show minimum values.
Solve a hyperbolic problem that includes damping. You must use the finite element matrix
form to use damping.
5-424
hyperbolic
model = createpde();
importGeometry(model,'BracketWithHole.stl');
figure
pdegplot(model,'FaceLabels','on')
view(30,30)
title('Bracket with Face Labels')
figure
pdegplot(model,'FaceLabels','on')
view(-134,-32)
title('Bracket with Face Labels, Rear View')
5-425
5 Functions — Alphabetical List
c = 1;
a = 0;
f = 0.5;
d = 1;
generateMesh(model);
Create initial conditions and boundary conditions. The boundary condition for the rear
face is Dirichlet with value 0. All other faces have the default boundary condition. The
5-426
hyperbolic
initial condition is u(0) = 0, du/dt(0) = x/2. Give the initial condition on the
derivative by calculating the x-position of each node in xpts, and passing x/2.
applyBoundaryCondition(model,'Face',4,'u',0);
u0 = 0;
xpts = model.Mesh.Nodes(1,:);
ut0 = xpts(:)/2;
[Kc,Fc,B,ud] = assempde(model,c,a,f);
[~,M,~] = assema(model,0,d,f);
Damping = 0.1*M;
tlist = linspace(0,5,50);
u = hyperbolic(u0,ut0,tlist,Kc,Fc,B,ud,M,'DampingMatrix',Damping);
Plot the maximum value at each time. The oscillations damp slightly as time increases.
plot(max(u))
xlabel('Time')
ylabel('Maximum value')
title('Maximum of Solution')
5-427
5 Functions — Alphabetical List
Input Arguments
u0 — Initial condition
vector | character vector | character array | string scalar | string vector
Initial condition, specified as a scalar, vector of nodal values, character vector, character
array, string scalar, or string vector. The initial condition is the value of the solution u at
the initial time, specified as a column vector of values at the nodes. The nodes are either
p in the [p,e,t] data structure, or are model.Mesh.Nodes. For details, see “Solve
PDEs with Initial Conditions” on page 2-168.
5-428
hyperbolic
char('x.^2 + 5*cos(x.*y)',...
'tanh(x.*y)./(1+z.^2)')
Example: x.^2+5*cos(y.*x)
Data Types: double | char | string
Complex Number Support: Yes
Initial derivative, specified as a vector, character vector, character array, string scalar, or
string vector. The initial gradient is the value of the derivative of the solution u at the
initial time, specified as a vector of values at the nodes. The nodes are either p in the
[p,e,t] data structure, or are model.Mesh.Nodes. See “Solve PDEs with Initial
Conditions” on page 2-168.
char('x.^2 + 5*cos(x.*y)',...
'tanh(x.*y)./(1+z.^2)')
For details, see “Solve PDEs with Initial Conditions” on page 2-168.
Example: p(1,:).^2+5*cos(p(2,:).*p(1,:))
Data Types: double | char | string
Complex Number Support: Yes
5-429
5 Functions — Alphabetical List
Solution times, specified as a real vector. The solver returns the solution to the PDE at the
solution times.
Example: 0:0.2:4
Data Types: double
c — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. c represents the c coefficient in the scalar
PDE
∂ 2u
d - — ◊ ( c— u) + au = f
∂t2
∂2 u
d - — ◊ ( c ƒ — u ) + au = f
∂ t2
You can specifyc in various ways, detailed in “c Coefficient for Systems” on page 2-131.
See also “Specify Scalar PDE Coefficients in Character Form” on page 2-76, “Specify 2-D
Scalar Coefficients in Function Form” on page 2-82, and “Specify 3-D PDE Coefficients in
Function Form” on page 2-85.
Example: 'cosh(x+y.^2)'
Data Types: double | char | string | function_handle
Complex Number Support: Yes
5-430
hyperbolic
a — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. a represents the a coefficient in the scalar
PDE
∂ 2u
d - — ◊ ( c— u) + au = f
∂t2
∂2 u
d - — ◊ ( c ƒ — u ) + au = f
∂ t2
f — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. f represents the f coefficient in the scalar
PDE
∂ 2u
d - — ◊ ( c— u) + au = f
∂t2
5-431
5 Functions — Alphabetical List
∂2 u
d - — ◊ ( c ƒ — u ) + au = f
∂ t2
You can specifyf in various ways, detailed in “f Coefficient for Systems” on page 2-104.
See also “Specify Scalar PDE Coefficients in Character Form” on page 2-76, “Specify 2-D
Scalar Coefficients in Function Form” on page 2-82, and “Specify 3-D PDE Coefficients in
Function Form” on page 2-85.
Example: char('sin(x)';'cos(y)';'tan(z)')
Data Types: double | char | string | function_handle
Complex Number Support: Yes
d — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. d represents the d coefficient in the scalar
PDE
∂ 2u
d - — ◊ ( c— u) + au = f
∂t2
∂2 u
d - — ◊ ( c ƒ — u ) + au = f
∂ t2
You can specifyd in various ways, detailed in “a or d Coefficient for Systems” on page 2-
154. See also “Specify Scalar PDE Coefficients in Character Form” on page 2-76, “Specify
2-D Scalar Coefficients in Function Form” on page 2-82, and “Specify 3-D PDE
Coefficients in Function Form” on page 2-85.
Example: 2*eye(3)
Data Types: double | char | string | function_handle
Complex Number Support: Yes
b — Boundary conditions
boundary matrix | boundary file
5-432
hyperbolic
Boundary conditions, specified as a boundary matrix or boundary file. Pass a boundary file
as a function handle or as a file name.
• A boundary matrix is generally an export from the PDE Modeler app. For details of the
structure of this matrix, see “Boundary Matrix for 2-D Geometry” on page 2-175.
• A boundary file is a file that you write in the syntax specified in “Boundary Conditions
by Writing Functions” on page 2-204.
p — Mesh points
matrix
Mesh points, specified as a 2-by-Np matrix of points, where Np is the number of points in
the mesh. For a description of the (p,e,t) matrices, see “Mesh Data” on page 2-241.
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
e — Mesh edges
matrix
Mesh edges, specified as a 7-by-Ne matrix of edges, where Ne is the number of edges in
the mesh. For a description of the (p,e,t) matrices, see “Mesh Data” on page 2-241.
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
t — Mesh triangles
matrix
5-433
5 Functions — Alphabetical List
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
Kc — Stiffness matrix
sparse matrix | full matrix
Stiffness matrix, specified as a sparse matrix or as a full matrix. See “Elliptic Equations”
on page 5-75. Typically, Kc is the output of assempde.
Fc — Load vector
vector
Load vector, specified as a vector. See “Elliptic Equations” on page 5-75. Typically, Fc is
the output of assempde.
B — Dirichlet nullspace
sparse matrix
Dirichlet nullspace, returned as a sparse matrix. See “Algorithms” on page 5-75. Typically,
B is the output of assempde.
ud — Dirichlet vector
vector
Dirichlet vector, returned as a vector. See “Algorithms” on page 5-75. Typically, ud is the
output of assempde.
M — Mass matrix
sparse matrix | full matrix
Mass matrix. specified as a sparse matrix or a full matrix. See “Elliptic Equations” on
page 5-75.
To obtain the input matrices for pdeeig, hyperbolic or parabolic, run both assema
and assempde:
[Kc,Fc,B,ud] = assempde(model,c,a,f);
[~,M,~] = assema(model,0,d,f);
5-434
hyperbolic
Note Create the M matrix using assema with d, not a, as the argument before f.
D — Damping matrix
matrix
Damping matrix, specified as a matrix. D has the same size as the stiffness matrix Kc or
the mass matrix M. When you include D, hyperbolic solves the following ODE for the
variable v:
d 2v dv
BT MB + BT DB + Kv = F
2 dt
dt
with initial condition u0 and initial derivative ut0. Then hyperbolic returns the solution
u = B*v + ud.
5-435
5 Functions — Alphabetical List
Output Arguments
u — PDE solution
matrix
PDE solution, returned as a matrix. The matrix is Np*N-by-T, where Np is the number of
nodes in the mesh, N is the number of equations in the PDE (N = 1 for a scalar PDE), and
T is the number of solution times, meaning the length of tlist. The solution matrix has
the following structure.
• The first Np elements of each column in u represent the solution of equation 1, then
next Np elements represent the solution of equation 2, etc. The solution u is the value
at the corresponding node in the mesh.
• Column i of u represents the solution at time tlist(i).
To plot the solution, use pdeplot for 2-D geometry, or see “Plot 3-D Solutions and Their
Gradients” on page 3-277.
Algorithms
Hyperbolic Equations
Partial Differential Equation Toolbox solves equations of the form
∂ 2u ∂u
m +d - —·( c—u ) + au = f
2 ∂t
∂t
When the d coefficient is 0, but m is not, the documentation calls this a hyperbolic
equation, whether or not it is mathematically of the hyperbolic form.
Using the same ideas as for the parabolic equation, hyperbolic implements the
numerical solution of
∂ 2u
m - — ◊ ( c—u ) + au = f
∂t 2
5-436
hyperbolic
for x in Ω, where x represents a 2-D or 3-D point, with the initial conditions
u ( x ,0 ) = u0 ( x )
∂u
( x ,0 ) = v0 ( x )
∂t
for all x in Ω, and usual boundary conditions. In particular, solutions of the equation utt -
cΔu = 0 are waves moving with speed c.
Using a given mesh of Ω, the method of lines yields the second order ODE system
d2U
M + KU = F
dt2
U i ( 0 ) = u0 ( xi ) " i
d
U i ( 0 ) = v0 ( xi ) " i
dt
after we eliminate the unknowns fixed by Dirichlet boundary conditions. As before, the
stiffness matrix K and the mass matrix M are assembled with the aid of the function
assempde from the problems
hyperbolic internally calls assema, assemb, and assempde to create finite element
matrices corresponding to the problem. It calls ode15s to solve the resulting system of
ordinary differential equations.
5-437
5 Functions — Alphabetical List
p4
p1
p2 p3
r s
f1 = 1 - r - s - t
f2 = r
f3 = s
f4 = t
For a quadratic tetrahedron, there are additional nodes at the edge midpoints.
5-438
hyperbolic
p4
p8
p9 p1 p10
p5 p7
p2 p3
p6
r s
2
f1 = 2 ( 1 - r - s - t) - (1 - r - s - t )
f2 = 2r 2 - r
f3 = 2s2 - s
f4 = 2t2 - t
f5 = 4 r ( 1 - r - s - t )
f6 = 4 rs
f7 = 4 s (1 - r - s - t )
f8 = 4t (1 - r - s - t )
f9 = 4 rt
f10 = 4 st
As in the 2-D case, a 3-D basis function ϕi takes the value 0 at all nodes j, except for node
i, where it takes the value 1.
Systems of PDEs
Partial Differential Equation Toolbox software can also handle systems of N partial
differential equations over the domain Ω. We have the elliptic system
5-439
5 Functions — Alphabetical List
-— ◊ ( c ƒ — u ) + au = f
∂u
d - — ◊ ( c ƒ — u ) + au = f
∂t
∂2 u
d - — ◊ ( c ƒ — u ) + au = f
∂ t2
-— ◊ ( c ƒ — u ) + au = l du
For 2-D systems, the notation — ◊ (c ƒ —u ) represents an N-by-1 matrix with an (i,1)-
component
N
Ê ∂ ∂ ∂ ∂ ∂ ∂ ∂ ∂ ˆ
 ÁË ∂x ci, j ,1,1 ∂x + ∂x ci, j ,1,2 ∂y + ∂y ci, j,2,1 ∂x + ∂y ci, j ,2,2 ∂y ˜¯u j
j =1
For 3-D systems, the notation — ◊ (c ƒ —u ) represents an N-by-1 matrix with an (i,1)-
component
N
Ê ∂ ∂ ∂ ∂ ∂ ∂ ˆ
 ÁË ∂x ci, j ,1,1 ∂x + ∂x ci, j ,1,2 ∂y + ∂x ci, j,1,3 ∂z ˜¯ u j
j =1
N
Ê ∂ ∂ ∂ ∂ ∂ ∂ ˆ
+  ÁË ∂y ci, j,2,1 ∂x + ∂y ci, j ,2,2 ∂y + ∂y ci, j,2,3 ∂z ˜¯ u j
j =1
N
Ê ∂ ∂ ∂ ∂ ∂ ∂ ˆ
+  ÁË ∂z ci, j ,3,1 ∂x + ∂z ci, j ,3,2 ∂y + ∂z ci, j,3,3 ∂z ˜¯ u j
j =1
The symbols a and d denote N-by-N matrices, and f denotes a column vector of length N.
5-440
hyperbolic
The elements cijkl, aij, dij, and fi of c, a, d, and f are stored row-wise in the MATLAB
matrices c, a, d, and f. The case of identity, diagonal, and symmetric matrices are
handled as special cases. For the tensor cijkl this applies both to the indices i and j, and to
the indices k and l.
Partial Differential Equation Toolbox software does not check the ellipticity of the
problem, and it is quite possible to define a system that is not elliptic in the mathematical
sense. The preceding procedure that describes the scalar case is applied to each
component of the system, yielding a symmetric positive definite system of equations
whenever the differential system possesses these characteristics.
The boundary conditions now in general are mixed, i.e., for each point on the boundary a
combination of Dirichlet and generalized Neumann conditions,
hu = r
n · ( c ƒ — u ) + qu = g + h ¢m
For 2-D systems, the notation n · ( c ƒ — u ) represents an N-by-1 matrix with (i,1)-
component
N
Ê ∂ ∂ ∂ ∂ ˆ
 ÁË cos(a )ci, j,1,1 ∂x + cos(a)ci, j ,1,2 ∂y + sin(a)ci, j ,2,1 ∂x + sin(a)ci, j,2,2 ∂y ˜¯u j
j =1
For 3-D systems, the notation n · ( c ƒ — u ) represents an N-by-1 matrix with (i,1)-
component
N
Ê ∂ ∂ ∂ ˆ
 ÁË cos(a )ci, j,1,1 ∂x + cos(a)ci, j ,1,2 ∂y + cos(a )ci, j ,1,3 ∂z ˜¯u j
j =1
N
Ê ∂ ∂ ∂ ˆ
+  ÁË cos(b )ci, j ,2,1 ∂x + cos(b )ci, j,2,2 ∂y + cos(b )ci, j ,2,3 ∂z ˜¯u j
j =1
N
Ê ∂ ∂ ∂ ˆ
+  ÁË cos(g )ci, j ,3,1 ∂x + cos(g )ci, j,3,2 ∂y + cos (g )ci, j ,3,3 ∂z ˜¯u j
j =1
5-441
5 Functions — Alphabetical List
There are M Dirichlet conditions and the h-matrix is M-by-N, M ≥ 0. The generalized
Neumann condition contains a source h ¢m , where the Lagrange multipliers μ are
computed such that the Dirichlet conditions become satisfied. In a structural mechanics
problem, this term is exactly the reaction force necessary to satisfy the kinematic
constraints described by the Dirichlet conditions.
The rest of this section details the treatment of the Dirichlet conditions and may be
skipped on a first reading.
hu = r (5-11)
When this number is increased, hu = r will be more accurately satisfied, but the potential
ill-conditioning of the modified equations will become more serious.
The second method is also applicable to general mixed conditions with nondiagonal h,
and is free of the ill-conditioning, but is more involved computationally. Assume that there
are Np nodes in the mesh. Then the number of unknowns is NpN = Nu. When Dirichlet
boundary conditions fix some of the unknowns, the linear system can be correspondingly
reduced. This is easily done by removing rows and columns when u values are given, but
here we must treat the case when some linear combinations of the components of u are
given, hu = r. These are collected into HU = R where H is an M-by-Nu matrix and R is an
M-vector.
5-442
hyperbolic
KU +H´ µ = F (5-12)
HU = R. (5-13)
The constraints can be solved for M of the U-variables, the remaining called V, an Nu – M
vector. The null space of H is spanned by the columns of B, and U = BV + ud makes U
satisfy the Dirichlet conditions. A permutation to block-diagonal form exploits the sparsity
of H to speed up the following computation to find B in a numerically stable way. µ can be
eliminated by premultiplying by B´ since, by the construction, HB = 0 or B´H´ = 0. The
reduced system becomes
See Also
solvepde
5-443
5 Functions — Alphabetical List
importGeometry
Package: pde
Syntax
importGeometry(model,geometryfile)
gd = importGeometry(model,geometryfile)
Description
importGeometry(model,geometryfile) creates a geometry container from the
specified STL geometry file, and includes the geometry in the model container.
Examples
5-444
importGeometry
Import a planar STL geometry into a PDE model. When importing a planar geometry,
importGeometry converts it to a 2-D geometry by mapping it to the X-Y plane.
5-445
5 Functions — Alphabetical List
ans =
DiscreteGeometry with properties:
NumCells: 0
NumFaces: 1
NumEdges: 5
NumVertices: 5
pdegplot(model,'EdgeLabels','on')
5-446
importGeometry
Input Arguments
model — PDE model
PDEModel object
Path to STL file, specified as a character vector or a string scalar ending with the file
extension .stl or .STL.
Example: '../geometries/Carburetor.stl'
Data Types: char | string
Output Arguments
gd — Geometry description
DiscreteGeometry object
Limitations
• importGeometry does not allow you to import a multidomain 3-D geometry unless all
of its subdomains are separate. In other words, the subdomains of the geometry
cannot have any common points. Because of this limitation, you cannot import nested
3-D geometries directly. As a workaround, you can import a mesh and then create a
multidomain geometry from the mesh by using the geometryFromMesh function.
Tips
• STL format approximates the boundary of a CAD geometry by a collection of triangles,
and importGeometry reconstructs the faces and edges from this data.
5-447
5 Functions — Alphabetical List
Reconstruction from STL data is not precise and can result in a loss of edges and,
therefore, the merging of adjacent faces. Typically, lost edges are the edges between
two adjacent faces meeting at a small angle, or smooth edges bounding blend
surfaces. Usually, the loss of such edges does not affect the analysis workflow.
See Also
DiscreteGeometry | PDEModel | geometryFromMesh | pdegplot
Topics
“STL File Import” on page 2-47
“Solve Problems Using PDEModel Objects” on page 2-6
Introduced in R2015a
5-448
initmesh
initmesh
Create initial 2-D mesh
Note This page describes the legacy workflow. New features might not be compatible
with the legacy workflow. For the corresponding step in the recommended workflow, see
generateMesh.
Syntax
[p,e,t] = initmesh(g)
[p,e,t] = initmesh(g,'PropertyName',PropertyValue,...)
Description
[p,e,t] = initmesh(g) returns a triangular mesh using the 2-D geometry
specification g. initmesh uses a Delaunay triangulation algorithm. The mesh size is
determined from the shape of the geometry and from name-value pair settings.
g describes the geometry of the PDE problem. g can be a Decomposed Geometry matrix,
the name of a Geometry file, or a function handle to a Geometry file. For details, see
“Geometry”.
In the Point matrix p, the first and second rows contain x- and y-coordinates of the points
in the mesh.
In the Edge matrix e, the first and second rows contain indices of the starting and ending
point, the third and fourth rows contain the starting and ending parameter values, the
fifth row contains the edge segment number, and the sixth and seventh row contain the
left- and right-hand side subdomain numbers.
In the Triangle matrix t, the first three rows contain indices to the corner points, given in
counter clockwise order, and the fourth row contains the subdomain number.
5-449
5 Functions — Alphabetical List
The Hmax property controls the size of the triangles on the mesh. initmesh creates a
mesh where triangle edge lengths are approximately Hmax or less.
The Hgrad property determines the mesh growth rate away from a small part of the
geometry. The default value is 1.3, i.e., a growth rate of 30%. Hgrad cannot be equal to
either of its bounds, 1 and 2.
Both the Box and Init property are related to the way the mesh algorithm works. By
turning on Box you can get a good idea of how the mesh generation algorithm works
within the bounding box. By turning on Init you can see the initial triangulation of the
boundaries. By using the command sequence
[p,e,t] = initmesh(dl,'hmax',inf,'init','on');
[uxy,tn,a2,a3] = tri2grid(p,t,zeros(size(p,2)),x,y);
n = t(4,tn);
you can determine the subdomain number n of the point xy. If the point is outside the
geometry, tn is NaN and the command n = t(4,tn) results in a failure.
5-450
initmesh
The Jiggle property is used to control whether jiggling of the mesh should be attempted
(see jigglemesh for details). Jiggling can be done until the minimum or the mean of the
quality of the triangles decreases. JiggleIter can be used to set an upper limit on the
number of iterations.
The MesherVersion property chooses the algorithm for mesh generation. The 'R2013a'
algorithm runs faster, and can triangulate more geometries than the 'preR2013a'
algorithm. Both algorithms use Delaunay triangulation.
Examples
Make a simple triangular mesh of the L-shaped membrane in the PDE Modeler app.
Before you do anything in the PDE Modeler app, set the Maximum edge size to inf in
the Mesh Parameters dialog box. You open the dialog box by selecting the Parameters
option from the Mesh menu. Also select the items Show Node Labels and Show
Triangle Labels in the Mesh menu. Then create the initial mesh by pressing the D
button. (This can also be done by selecting the Initialize Mesh option from the Mesh
menu.)
5-451
5 Functions — Alphabetical List
The corresponding mesh data structures can be exported to the main workspace by
selecting the Export Mesh option from the Mesh menu.
p
p =
-1 1 1 0 0 -1
-1 -1 1 1 0 0
e
e =
1 2 3 4 5 6
2 3 4 5 6 1
0 0 0 0 0 0
1 1 1 1 1 1
5-452
initmesh
1 2 3 4 5 6
1 1 1 1 1 1
0 0 0 0 0 0
t
t =
1 2 3 1
2 3 4 5
5 5 5 6
1 1 1 1
References
George, P. L., Automatic Mesh Generation — Application to Finite Element Methods,
Wiley, 1991.
See Also
decsg | jigglemesh | refinemesh
Topics
“Mesh Data” on page 2-241
5-453
5 Functions — Alphabetical List
internalHeatSource
Package: pde
Syntax
internalHeatSource(thermalmodel,heatSourceValue)
internalHeatSource(thermalmodel,heatSourceValue,RegionType,RegionID)
heatSource = internalHeatSource( ___ )
Description
internalHeatSource(thermalmodel,heatSourceValue) specifies an internal heat
source for the thermal model. This syntax declares that the entire geometry is a heat
source.
Note Use internalHeatSource for specifying internal heat generators, that is, for
specifying heat sources that belong to the geometry of the model. To specify a heat influx
from an external source, use the thermalBC function with the HeatFlux parameter.
internalHeatSource(thermalmodel,heatSourceValue,RegionType,RegionID)
specifies geometry regions of type RegionType with ID numbers in RegionID as heat
sources. Always specify heatSourceValue first, then specify RegionType and
RegionID.
Examples
5-454
internalHeatSource
Set thermal conductivity to 0.2, mass density to 2700e-9, and specific heat to 920.
thermalProperties(thermalmodel,'ThermalConductivity',0.2, ...
'MassDensity',2700e-9, ...
'SpecificHeat',920)
ans =
ThermalMaterialAssignment with properties:
RegionType: 'cell'
RegionID: 1
ThermalConductivity: 0.2000
MassDensity: 2.7000e-06
SpecificHeat: 920
Specify that the entire geometry generates heat at the rate 2e-4.
internalHeatSource(thermalmodel,2e-4)
ans =
HeatSourceAssignment with properties:
RegionType: 'cell'
RegionID: 1
HeatSource: 2.0000e-04
5-455
5 Functions — Alphabetical List
geometryFromEdges(thermalModel,dl);
Set thermal conductivity to 50, mass density to 2500, and specific heat to 600.
thermalProperties(thermalModel,'ThermalConductivity',50, ...
'MassDensity',2500, ...
'SpecificHeat',600);
internalHeatSource(thermalModel,25,'Face',1)
ans =
HeatSourceAssignment with properties:
RegionType: 'face'
RegionID: 1
HeatSource: 25
Use a function handle to specify an internal heat source that depends on coordinates.
Create a thermal model for transient analysis and include the geometry. The geometry is
a rod with a circular cross section. The 2-D model is a rectangular strip whose y-
dimension extends from the axis of symmetry to the outer surface, and whose x-dimension
extends over the actual length of the rod.
thermalmodel = createpde('thermal','transient');
g = decsg([3 4 -1.5 1.5 1.5 -1.5 0 0 .2 .2]');
geometryFromEdges(thermalmodel,g);
5-456
internalHeatSource
The heat is generated within the rod due to the radioactive decay. Therefore, the entire
geometry is an internal nonlinear heat source and can be represented by a function of the
y-coordinate, for example, .
q = @(location,state)2000*location.y;
internalHeatSource(thermalmodel,q)
ans =
HeatSourceAssignment with properties:
RegionType: 'face'
RegionID: 1
HeatSource: @(location,state)2000*location.y
Input Arguments
thermalmodel — Thermal model
ThermalModel object
Thermal model, specified as a ThermalModel object. The model contains the geometry,
mesh, thermal properties of the material, internal heat source, boundary conditions, and
initial conditions.
Example: thermalmodel = createpde('thermal','steadystate')
Geometric region type, specified as 'Face' for a 2-D model or 'Cell' for a 3-D model.
Example: internalHeatSource(thermalmodel,25,'Cell',1)
Data Types: char | string
5-457
5 Functions — Alphabetical List
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot, as shown in “Create Geometry and Remove Face Boundaries” on page 2-13 or
“STL File Import” on page 2-47.
Example: internalHeatSource(thermalmodel,25,'Cell',1:3)
Data Types: double
Heat source value, specified as a number or a function handle. Use a function handle to
specify the internal heat source that depends on space, time, or temperature. The
function must be of the form
heatSourceValue = heatSourceFun(location,state)
The solver passes location data as a structure array with the fields location.x,
location.y, and, for 3-D problems, location.z. The state data is a structure array
with the fields state.u, state.ux, state.uy, state.uz (for 3-D problems), and
state.time (for transient problems). The state.u field contains the solution vector.
The state.ux, state.uy, state.uz fields are estimates of the solution’s partial
derivatives at the corresponding points of the location structure. The state.time field
contains time at evaluation points.
Output Arguments
heatSource — Handle to heat source
object
See Also
thermalBC | thermalProperties
5-458
internalHeatSource
Introduced in R2017a
5-459
5 Functions — Alphabetical List
interpolateAcceleration
Package: pde
Interpolate acceleration at arbitrary spatial locations for all time steps for transient
structural model
Syntax
intrpAccel = interpolateAcceleration(structuralresults,xq,yq)
intrpAccel = interpolateAcceleration(structuralresults,xq,yq,zq)
intrpAccel = interpolateAcceleration(structuralresults,querypoints)
Description
intrpAccel = interpolateAcceleration(structuralresults,xq,yq) returns
the interpolated acceleration values at the 2-D points specified in xq and yq for all time-
steps.
intrpAccel = interpolateAcceleration(structuralresults,querypoints)
uses the points specified in querypoints.
Examples
structuralmodel = createpde('structural','transient-solid');
5-460
interpolateAcceleration
Create the geometry and include it in the model. Plot the geometry.
gm = multicuboid(0.06,0.005,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
Specify the Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3, ...
'MassDensity',7800);
5-461
5 Functions — Alphabetical List
structuralBC(structuralmodel,'Face',5,'Constraint','fixed');
Apply a sinusoidal displacement along the y-direction on the end opposite the fixed end of
the beam.
structuralBC(structuralmodel,'Face',3,'YDisplacement',1E-4,'Frequency',50);
Generate a mesh.
generateMesh(structuralmodel,'Hmax',0.01);
structuralIC(structuralmodel,'Displacement',[0;0;0],'Velocity',[0;0;0]);
tlist = 0:0.002:0.2;
structuralresults = solve(structuralmodel,tlist);
coordsMidSpan = [0;0;0.005];
intrpAccel = interpolateAcceleration(structuralresults,coordsMidSpan);
figure
plot(structuralresults.SolutionTimes,intrpAccel.ay)
title('Y-Acceleration of the Geometric Center of the Beam')
5-462
interpolateAcceleration
Input Arguments
structuralresults — Solution of dynamic structural analysis problem
TransientStructuralResults object
5-463
5 Functions — Alphabetical List
Query points, specified as a real matrix with either two rows for 2-D geometry or three
rows for 3-D geometry. interpolateAcceleration evaluates accelerations at the
5-464
interpolateAcceleration
Output Arguments
intrpAccel — Accelerations at query points
structure array
Accelerations at the query points, returned as a structure array with fields representing
spatial components of acceleration at the query points. For query points that are outside
the geometry, intrpAccel returns NaN.
See Also
StructuralModel | TransientStructuralResults | evaluatePrincipalStrain |
evaluatePrincipalStress | evaluateReaction | evaluateStrain |
evaluateStress | evaluateVonMisesStress | interpolateDisplacement |
interpolateStrain | interpolateStress | interpolateVelocity |
interpolateVonMisesStress
Introduced in R2018a
5-465
5 Functions — Alphabetical List
interpolateDisplacement
Package: pde
Syntax
intrpDisp = interpolateDisplacement(structuralresults,xq,yq)
intrpDisp = interpolateDisplacement(structuralresults,xq,yq,zq)
intrpDisp = interpolateDisplacement(structuralresults,querypoints)
Description
intrpDisp = interpolateDisplacement(structuralresults,xq,yq) returns
the interpolated displacement values at the 2-D points specified in xq and yq. For a
structural dynamic model, interpolateDisplacement returns the interpolated
displacement values for all time-steps.
intrpDisp = interpolateDisplacement(structuralresults,querypoints)
uses points specified in querypoints.
Examples
structuralmodel = createpde('structural','static-planestrain');
5-466
interpolateDisplacement
geometryFromEdges(structuralmodel,@squareg);
pdegplot(structuralmodel,'EdgeLabels','on')
axis equal
structuralProperties(structuralmodel,'PoissonsRatio',0.3, ...
'YoungsModulus',210E3);
structuralBC(structuralmodel,'XDisplacement',0.001,'Edge',1);
5-467
5 Functions — Alphabetical List
structuralBC(structuralmodel,'Constraint','fixed','Edge',3);
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel);
Create a grid and interpolate the x- and y-components of the displacement to the grid.
v = linspace(-1,1,21);
[X,Y] = meshgrid(v);
intrpDisp = interpolateDisplacement(structuralresults,X,Y);
Reshape the displacement components to the shape of the grid. Plot the displacement.
ux = reshape(intrpDisp.ux,size(X));
uy = reshape(intrpDisp.uy,size(Y));
quiver(X,Y,ux,uy)
5-468
interpolateDisplacement
Solve a static structural model representing a bimetallic cable under tension, and
interpolate the displacement on a cross-section of the cable.
structuralmodel = createpde('structural','static-solid');
Create the geometry and include it in the model. Plot the geometry.
5-469
5 Functions — Alphabetical List
gm = multicylinder([0.01,0.015],0.05);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','CellLabels','on','FaceAlpha',0.5)
Specify the Young's modulus and Poisson's ratio for each metal.
structuralProperties(structuralmodel,'Cell',1,'YoungsModulus',110E9, ...
'PoissonsRatio',0.28);
structuralProperties(structuralmodel,'Cell',2,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3);
structuralBC(structuralmodel,'Face',[1,4],'Constraint','fixed');
5-470
interpolateDisplacement
structuralBoundaryLoad(structuralmodel,'Face',[2,5],'SurfaceTraction',[0;0;100]);
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel)
structuralresults =
StaticStructuralResults with properties:
[X,Y] = meshgrid(linspace(-0.015,0.015,50));
Z = ones(size(X))*0.025;
intrpDisp = interpolateDisplacement(structuralresults,X,Y,Z);
surf(X,Y,reshape(intrpDisp.uz,size(X)))
5-471
5 Functions — Alphabetical List
Alternatively, you can specify the grid by using a matrix of query points.
querypoints = [X(:),Y(:),Z(:)]';
intrpDisp = interpolateDisplacement(structuralresults,querypoints);
surf(X,Y,reshape(intrpDisp.uz,size(X)))
5-472
interpolateDisplacement
structuralmodel = createpde('structural','transient-solid');
Create the geometry and include it in the model. Plot the geometry.
5-473
5 Functions — Alphabetical List
gm = multicuboid(0.06,0.005,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
Specify the Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3, ...
'MassDensity',7800);
structuralBC(structuralmodel,'Face',5,'Constraint','fixed');
5-474
interpolateDisplacement
Apply a sinusoidal displacement along the y-direction on the end opposite the fixed end of
the beam.
structuralBC(structuralmodel,'Face',3,'YDisplacement',1E-4,'Frequency',50);
Generate a mesh.
generateMesh(structuralmodel,'Hmax',0.01);
structuralIC(structuralmodel,'Displacement',[0;0;0],'Velocity',[0;0;0]);
tlist = 0:0.002:0.2;
structuralresults = solve(structuralmodel,tlist);
coordsMidSpan = [0;0;0.005];
intrpDisp = interpolateDisplacement(structuralresults,coordsMidSpan);
figure
plot(structuralresults.SolutionTimes,intrpDisp.uy)
title('y-Displacement of the Geometric Center of the Beam')
5-475
5 Functions — Alphabetical List
Input Arguments
structuralresults — Solution of structural analysis problem
StaticStructuralResults object | TransientStructuralResults object
5-476
interpolateDisplacement
5-477
5 Functions — Alphabetical List
Query points, specified as a real matrix with either two rows for 2-D geometry or three
rows for 3-D geometry. interpolateDisplacement evaluates the displacements at the
coordinate points querypoints(:,i), so each column of querypoints contains exactly
one 2-D or 3-D query point.
Example: For 2-D geometry, querypoints = [0.5,0.5,0.75,0.75; 1,2,0,0.5]
Data Types: double
Output Arguments
intrpDisp — Displacements at query points
structure array
Displacements at the query points, returned as a structure array with fields representing
spatial components of displacement at the query points. For query points that are outside
the geometry, intrpDisp returns NaN.
See Also
StaticStructuralResults | StructuralModel | TransientStructuralResults |
evaluatePrincipalStrain | evaluatePrincipalStress | evaluateReaction |
evaluateStrain | evaluateStress | evaluateVonMisesStress |
interpolateAcceleration | interpolateStrain | interpolateStress |
interpolateVelocity | interpolateVonMisesStress
Introduced in R2017b
5-478
interpolateSolution
interpolateSolution
Package: pde
Syntax
uintrp = interpolateSolution(results,xq,yq)
uintrp = interpolateSolution(results,xq,yq,zq)
uintrp = interpolateSolution(results,querypoints)
Description
uintrp = interpolateSolution(results,xq,yq) returns the interpolated values
of the solution to the scalar stationary equation specified in results at the 2-D points
specified in xq and yq.
uintrp = interpolateSolution( ___ ,iU), for any previous syntax, returns the
interpolated values of the solution to the system of stationary equations for equation
indices iU.
5-479
5 Functions — Alphabetical List
Examples
Interpolate the solution to a scalar problem along a line and plot the result.
Create the solution to the problem on the L-shaped membrane with zero
Dirichlet boundary conditions.
model = createpde;
geometryFromEdges(model,@lshapeg);
applyBoundaryCondition(model,'dirichlet','Edge',1:model.Geometry.NumEdges,'u',0);
specifyCoefficients(model,'m',0,...
'd',0,...
'c',1,...
'a',0,...
'f',1);
generateMesh(model,'Hmax',0.05);
results = solvepde(model);
Interpolate the solution along the straight line from (x,y) = (-1,-1) to (1,1). Plot
the interpolated solution.
xq = linspace(-1,1,101);
yq = xq;
uintrp = interpolateSolution(results,xq,yq);
plot(xq,uintrp)
xlabel('x')
ylabel('u(x)')
5-480
interpolateSolution
Calculate the mean exit time of a Brownian particle from a region that contains absorbing
(escape) boundaries and reflecting boundaries. Use the Poisson's equation with constant
coefficients and 3-D rectangular block geometry to model this problem.
model = createpde;
importGeometry(model,'Block.stl');
applyBoundaryCondition(model,'dirichlet','Face',[1,2,5],'u',0);
5-481
5 Functions — Alphabetical List
specifyCoefficients(model,'m',0,...
'd',0,...
'c',1,...
'a',0,...
'f',2);
generateMesh(model);
results = solvepde(model);
[X,Y,Z] = meshgrid(0:135,0:35,0:61);
uintrp = interpolateSolution(results,X,Y,Z);
uintrp = reshape(uintrp,size(X));
Create a contour slice plot for five fixed values of the y coordinate.
contourslice(X,Y,Z,uintrp,[],0:4:16,[])
colormap jet
xlabel('x')
ylabel('y')
zlabel('z')
xlim([0,100])
ylim([0,20])
zlim([0,50])
axis equal
view(-50,22)
colorbar
5-482
interpolateSolution
Solve a scalar stationary problem and interpolate the solution to a dense grid.
Create the solution to the problem on the L-shaped membrane with zero
Dirichlet boundary conditions.
model = createpde;
geometryFromEdges(model,@lshapeg);
applyBoundaryCondition(model,'dirichlet','Edge',1:model.Geometry.NumEdges,'u',0);
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',0,'f',1);
5-483
5 Functions — Alphabetical List
generateMesh(model,'Hmax',0.05);
results = solvepde(model);
v = linspace(-1,1,101);
[X,Y] = meshgrid(v);
querypoints = [X(:),Y(:)]';
uintrp = interpolateSolution(results,querypoints);
uintrp = reshape(uintrp,size(X));
mesh(X,Y,uintrp)
xlabel('x')
ylabel('y')
5-484
interpolateSolution
Create the solution to a two-component system and plot the two components along a
planar slice through the geometry.
Create a PDE model for two components. Import the geometry of a torus.
model = createpde(2);
importGeometry(model,'Torus.stl');
pdegplot(model,'FaceLabels','on');
5-485
5 Functions — Alphabetical List
gfun = @(region,state)[0,region.z-40];
applyBoundaryCondition(model,'neumann','Face',1,'g',gfun);
ufun = @(region,state)[region.x-40,0];
applyBoundaryCondition(model,'dirichlet','Face',1,'u',ufun);
specifyCoefficients(model,'m',0,...
'd',0,...
'c',[1;0;1;0;0;1;0;0;1;0;1;0;1;0;0;1;0;1;0;0;1],...
'a',0,...
'f',[1;1]);
5-486
interpolateSolution
generateMesh(model);
results = solvepde(model);
Interpolate the results on a plane that slices the torus for each of the two components.
[X,Z] = meshgrid(0:100);
Y = 15*ones(size(X));
uintrp = interpolateSolution(results,X,Y,Z,[1,2]);
sol1 = reshape(uintrp(:,1),size(X));
sol2 = reshape(uintrp(:,2),size(X));
figure
surf(X,Z,sol1)
title('Component 1')
5-487
5 Functions — Alphabetical List
figure
surf(X,Z,sol2)
title('Component 2')
5-488
interpolateSolution
model = createpde(1);
geometryFromEdges(model,@lshapeg);
applyBoundaryCondition(model,'dirichlet','Edge',1:model.Geometry.NumEdges,'u',0);
specifyCoefficients(model,'m',0,...
'd',1,...
5-489
5 Functions — Alphabetical List
'c',1,...
'a',0,...
'f',0);
r = [0,100];
generateMesh(model,'Hmax',1/50);
results = solvepdeeig(model,r);
5-490
interpolateSolution
Interpolate the eigenvector corresponding to the fifth eigenvalue to a coarse grid and plot
the result.
[xq,yq] = meshgrid(-1:0.1:1);
uintrp = interpolateSolution(results,xq,yq,5);
uintrp = reshape(uintrp,size(xq));
surf(xq,yq,uintrp)
5-491
5 Functions — Alphabetical List
Import slab geometry for a 3-D problem with three solution components. Plot the
geometry.
model = createpde(3);
importGeometry(model,'Plate10x10x1.stl');
pdegplot(model,'FaceLabels','on','FaceAlpha',0.5)
5-492
interpolateSolution
Set boundary conditions such that face 2 is fixed (zero deflection in any direction) and
face 5 has a load of 1e3 in the positive z-direction. This load causes the slab to bend
upward. Set the initial condition that the solution is zero, and its derivative with respect
to time is also zero.
applyBoundaryCondition(model,'dirichlet','Face',2,'u',[0,0,0]);
applyBoundaryCondition(model,'neumann','Face',5,'g',[0,0,1e3]);
setInitialConditions(model,0,0);
Create PDE coefficients for the equations of linear elasticity. Set the material properties
to be similar to those of steel. See 3-D Linear Elasticity Equations in Toolbox Form.
E = 200e9;
nu = 0.3;
5-493
5 Functions — Alphabetical List
specifyCoefficients(model,'m',1,...
'd',0,...
'c',elasticityC3D(E,nu),...
'a',0,...
'f',[0;0;0]);
generateMesh(model,'Hmax',1);
tlist = 0:1e-4:5e-3;
results = solvepde(model,tlist);
Interpolate the solution at fixed x- and z-coordinates in the centers of their ranges, 5 and
0.5 respectively. Interpolate for y from 0 through 10 in steps of 0.2. Obtain just
component 3, the z-component of the solution.
yy = 0:0.2:10;
zz = 0.5*ones(size(yy));
xx = 10*zz;
component = 3;
uintrp = interpolateSolution(results,xx,yy,zz,component,1:length(tlist));
The solution is a 51-by-1-by-51 array. Use squeeze to remove the singleton dimension.
Removing the singleton dimension transforms this array to a 51-by-51 matrix which
simplifies indexing into it.
uintrp = squeeze(uintrp);
[X,Y] = ndgrid(yy,tlist);
figure
surf(X,Y,uintrp)
xlabel('Y')
ylabel('Time')
title('Deflection at x = 5, z = 0.5')
zlim([0,14e-5])
5-494
interpolateSolution
Input Arguments
results — PDE solution
StationaryResults object (default) | TimeDependentResults object |
EigenResults object
5-495
5 Functions — Alphabetical List
interpolateSolution converts query points to column vectors xq(:), yq(:), and (if
present) zq(:). The returned solution is a column vector of the same size. To ensure that
the dimensions of the returned solution is consistent with the dimensions of the original
query points, use reshape. For example, use uintrp =
reshape(gradxuintrp,size(xq)).
Data Types: double
Query points, specified as a real matrix with either two rows for 2-D geometry, or three
rows for 3-D geometry. interpolateSolution evaluates the solution at the coordinate
points querypoints(:,i), so each column of querypoints contains exactly one 2-D or
3-D query point.
5-496
interpolateSolution
iU — Equation indices
vector of positive integers
Time or mode indices, specified as a vector of positive integers. Each entry in iT specifies
a time index for time-dependent solutions, or a mode index for eigenvalue solutions.
Example: iT = 1:5:21 specifies the time or mode for every fifth solution up to 21.
Data Types: double
Output Arguments
uintrp — Solution at query points
array
Solution at query points, returned as an array. For query points that are outside the
geometry, uintrp = NaN. For details about dimensions of the solution, see “Dimensions
of Solutions, Gradients, and Fluxes” on page 3-299.
See Also
PDEModel | StationaryResults | TimeDependentResults | evaluateGradient
Topics
“Plot 2-D Solutions and Their Gradients” on page 3-266
“Plot 3-D Solutions and Their Gradients” on page 3-277
“Dimensions of Solutions, Gradients, and Fluxes” on page 3-299
5-497
5 Functions — Alphabetical List
Introduced in R2015b
5-498
interpolateStrain
interpolateStrain
Package: pde
Syntax
intrpStrain = interpolateStrain(structuralresults,xq,yq)
intrpStrain = interpolateStrain(structuralresults,xq,yq,zq)
intrpStrain = interpolateStrain(structuralresults,querypoints)
Description
intrpStrain = interpolateStrain(structuralresults,xq,yq) returns the
interpolated strain values at the 2-D points specified in xq and yq. For a dynamic
structural model, interpolateStrain interpolates strain for all time-steps.
Examples
structuralmodel = createpde('structural','static-planestrain');
5-499
5 Functions — Alphabetical List
geometryFromEdges(structuralmodel,@squareg);
pdegplot(structuralmodel,'EdgeLabels','on')
axis equal
structuralProperties(structuralmodel,'PoissonsRatio',0.3, ...
'YoungsModulus',210E3);
structuralBC(structuralmodel,'XDisplacement',0.001,'Edge',1);
5-500
interpolateStrain
structuralBC(structuralmodel,'Constraint','fixed','Edge',3);
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel);
Create a grid and interpolate the x- and y-components of the normal strain to the grid.
v = linspace(-1,1,101);
[X,Y] = meshgrid(v);
intrpStrain = interpolateStrain(structuralresults,X,Y);
Reshape the x-component of the normal strain to the shape of the grid and plot it.
exx = reshape(intrpStrain.exx,size(X));
px = pcolor(X,Y,exx);
px.EdgeColor='none';
colorbar
5-501
5 Functions — Alphabetical List
Reshape the y-component of the normal strain to the shape of the grid and plot it.
eyy = reshape(intrpStrain.eyy,size(Y));
figure
py = pcolor(X,Y,eyy);
py.EdgeColor='none';
colorbar
5-502
interpolateStrain
Solve a static structural model representing a bimetallic cable under tension, and
interpolate strain on a cross-section of the cable.
structuralmodel = createpde('structural','static-solid');
Create the geometry and include it in the model. Plot the geometry.
5-503
5 Functions — Alphabetical List
gm = multicylinder([0.01,0.015],0.05);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','CellLabels','on','FaceAlpha',0.5)
Specify the Young's modulus and Poisson's ratio for each metal.
structuralProperties(structuralmodel,'Cell',1,'YoungsModulus',110E9, ...
'PoissonsRatio',0.28);
structuralProperties(structuralmodel,'Cell',2,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3);
structuralBC(structuralmodel,'Face',[1,4],'Constraint','fixed');
5-504
interpolateStrain
structuralBoundaryLoad(structuralmodel,'Face',[2,5],'SurfaceTraction',[0;0;100]);
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel)
structuralresults =
StaticStructuralResults with properties:
[X,Y] = meshgrid(linspace(-0.015,0.015,50));
Z = ones(size(X))*0.025;
intrpStrain = interpolateStrain(structuralresults,X,Y,Z);
surf(X,Y,reshape(intrpStrain.ezz,size(X)))
5-505
5 Functions — Alphabetical List
Alternatively, you can specify the grid by using a matrix of query points.
querypoints = [X(:),Y(:),Z(:)]';
intrpStrain = interpolateStrain(structuralresults,querypoints);
surf(X,Y,reshape(intrpStrain.ezz,size(X)))
5-506
interpolateStrain
Interpolate the strain at the geometric center of a beam under a harmonic excitation.
5-507
5 Functions — Alphabetical List
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
Specify the Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3, ...
'MassDensity',7800);
Apply a sinusoidal displacement along the y-direction on the end opposite the fixed end of
the beam.
5-508
interpolateStrain
structuralBC(structuralmodel,'Face',3,'YDisplacement',1E-4,'Frequency',50);
Generate a mesh.
generateMesh(structuralmodel,'Hmax',0.01);
structuralIC(structuralmodel,'Displacement',[0;0;0],'Velocity',[0;0;0]);
tlist = 0:0.002:0.2;
structuralresults = solve(structuralmodel,tlist);
coordsMidSpan = [0;0;0.005];
intrpStrain = interpolateStrain(structuralresults,coordsMidSpan);
figure
plot(structuralresults.SolutionTimes,intrpStrain.exx)
title('X-Direction Normal Strain at Beam Center')
5-509
5 Functions — Alphabetical List
Input Arguments
structuralresults — Solution of structural analysis problem
StaticStructuralResults object | TransientStructuralResults object
5-510
interpolateStrain
interpolateStrain converts query points to column vectors xq(:), yq(:), and (if
present) zq(:). The function returns strains as a structure array with fields of the same
size as these column vectors. To ensure that the dimensions of the returned solution are
consistent with the dimensions of the original query points, use the reshape function.
For example, use intrpStrain = reshape(intrpStrain.exx,size(xq)).
Data Types: double
Query points, specified as a real matrix with either two rows for 2-D geometry or three
rows for 3-D geometry. interpolateStrain evaluates the strains at the coordinate
points querypoints(:,i), so each column of querypoints contains exactly one 2-D or
3-D query point.
5-511
5 Functions — Alphabetical List
Output Arguments
intrpStrain — Strains at query points
structure array
Strains at the query points, returned as a structure array with fields representing spatial
components of strain at the query points. For query points that are outside the geometry,
intrpStrain returns NaN.
See Also
StaticStructuralResults | StructuralModel | evaluatePrincipalStrain |
evaluatePrincipalStress | evaluateReaction | interpolateDisplacement |
interpolateStress | interpolateVonMisesStress
Introduced in R2017b
5-512
interpolateStress
interpolateStress
Package: pde
Syntax
intrpStress = interpolateStress(structuralresults,xq,yq)
intrpStress = interpolateStress(structuralresults,xq,yq,zq)
intrpStress = interpolateStress(structuralresults,querypoints)
Description
intrpStress = interpolateStress(structuralresults,xq,yq) returns the
interpolated stress values at the 2-D points specified in xq and yq. For a dynamic
structural model, interpolateStress interpolates stress for all time-steps.
Examples
structuralmodel = createpde('structural','static-planestrain');
5-513
5 Functions — Alphabetical List
geometryFromEdges(structuralmodel,@squareg);
pdegplot(structuralmodel,'EdgeLabels','on')
axis equal
structuralProperties(structuralmodel,'PoissonsRatio',0.3, ...
'YoungsModulus',210E3);
structuralBC(structuralmodel,'XDisplacement',0.001,'Edge',1);
5-514
interpolateStress
structuralBC(structuralmodel,'Constraint','fixed','Edge',3);
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel);
Create a grid and interpolate the x- and y-components of the normal stress to the grid.
v = linspace(-1,1,151);
[X,Y] = meshgrid(v);
intrpStress = interpolateStress(structuralresults,X,Y);
Reshape the x-component of the normal stress to the shape of the grid and plot it.
sxx = reshape(intrpStress.sxx,size(X));
px = pcolor(X,Y,sxx);
px.EdgeColor='none';
colorbar
5-515
5 Functions — Alphabetical List
Reshape the y-component of the normal stress to the shape of the grid and plot it.
syy = reshape(intrpStress.syy,size(Y));
figure
py = pcolor(X,Y,syy);
py.EdgeColor='none';
colorbar
5-516
interpolateStress
Solve a static structural model representing a bimetallic cable under tension, and
interpolate stress on a cross-section of the cable.
structuralmodel = createpde('structural','static-solid');
Create the geometry and include it in the model. Plot the geometry.
5-517
5 Functions — Alphabetical List
gm = multicylinder([0.01,0.015],0.05);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','CellLabels','on','FaceAlpha',0.5)
Specify the Young's modulus and Poisson's ratio for each metal.
structuralProperties(structuralmodel,'Cell',1,'YoungsModulus',110E9, ...
'PoissonsRatio',0.28);
structuralProperties(structuralmodel,'Cell',2,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3);
structuralBC(structuralmodel,'Face',[1,4],'Constraint','fixed');
5-518
interpolateStress
structuralBoundaryLoad(structuralmodel,'Face',[2,5],'SurfaceTraction',[0;0;100]);
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel)
structuralresults =
StaticStructuralResults with properties:
[X,Y] = meshgrid(linspace(-0.015,0.015,50));
Z = ones(size(X))*0.025;
intrpStress = interpolateStress(structuralresults,X,Y,Z);
surf(X,Y,reshape(intrpStress.szz,size(X)))
5-519
5 Functions — Alphabetical List
Alternatively, you can specify the grid by using a matrix of query points.
querypoints = [X(:),Y(:),Z(:)]';
intrpStress = interpolateStress(structuralresults,querypoints);
surf(X,Y,reshape(intrpStress.szz,size(X)))
5-520
interpolateStress
Interpolate the stress at the geometric center of a beam under a harmonic excitation.
5-521
5 Functions — Alphabetical List
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
Specify the Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3, ...
'MassDensity',7800);
Apply a sinusoidal displacement along the y-direction on the end opposite the fixed end of
the beam.
5-522
interpolateStress
structuralBC(structuralmodel,'Face',3,'YDisplacement',1E-4,'Frequency',50);
Generate a mesh.
generateMesh(structuralmodel,'Hmax',0.01);
structuralIC(structuralmodel,'Displacement',[0;0;0],'Velocity',[0;0;0]);
tlist = 0:0.002:0.2;
structuralresults = solve(structuralmodel,tlist);
coordsMidSpan = [0;0;0.005];
intrpStress = interpolateStress(structuralresults,coordsMidSpan);
figure
plot(structuralresults.SolutionTimes,intrpStress.sxx)
title('X-Direction Normal Stress at Beam Center')
5-523
5 Functions — Alphabetical List
Input Arguments
structuralresults — Solution of structural analysis problem
StaticStructuralResults object | TransientStructuralResults object
5-524
interpolateStress
interpolateStress converts the query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns stresses as a structure array with fields of the same size as
these column vectors. To ensure that the dimensions of the returned solution are
consistent with the dimensions of the original query points, use the reshape function.
For example, use intrpStress = reshape(intrpStress.sxx,size(xq)).
Data Types: double
Query points, specified as a real matrix with either two rows for 2-D geometry or three
rows for 3-D geometry. interpolateStress evaluates stresses at the coordinate points
querypoints(:,i), so each column of querypoints contains exactly one 2-D or 3-D
query point.
5-525
5 Functions — Alphabetical List
Output Arguments
intrpStress — Stresses at query points
structure array
Stresses at the query points, returned as a structure array with fields representing spatial
components of stress at the query points. For query points that are outside the geometry,
intrpStress returns NaN.
See Also
StaticStructuralResults | StructuralModel | evaluatePrincipalStrain |
evaluatePrincipalStress | evaluateReaction | interpolateDisplacement |
interpolateStrain | interpolateVonMisesStress
Introduced in R2017b
5-526
interpolateTemperature
interpolateTemperature
Package: pde
Syntax
Tintrp = interpolateTemperature(thermalresults,xq,yq)
Tintrp = interpolateTemperature(thermalresults,xq,yq,zq)
Tintrp = interpolateTemperature(thermalresults,querypoints)
Tintrp = interpolateTemperature( ___ ,iT)
Description
Tintrp = interpolateTemperature(thermalresults,xq,yq) returns the
interpolated temperature values at the 2-D points specified in xq and yq. This syntax is
valid for both the steady-state and transient thermal models.
Examples
5-527
5 Functions — Alphabetical List
thermalmodel = createpde('thermal');
R1 = [3,4,-1,1,1,-1,1,1,-1,-1]';
g = decsg(R1, 'R1', ('R1')');
geometryFromEdges(thermalmodel,g);
pdegplot(thermalmodel,'EdgeLabels','on')
xlim([-1.5,1.5])
axis equal
Assuming that this is an iron plate, assign a thermal conductivity of 79.5 W/(m*K).
Because this is a steady-state model, you do not need to assign mass density or specific
heat values.
5-528
interpolateTemperature
thermalProperties(thermalmodel,'ThermalConductivity',79.5,'Face',1);
Apply a constant temperature of 300 K to the bottom of the plate (edge 3). Also, assume
that the top of the plate (edge 1) is insulated, and apply convection on the two sides of the
plate (edges 2 and 4).
thermalBC(thermalmodel,'Edge',3,'Temperature',300);
thermalBC(thermalmodel,'Edge',1,'HeatFlux',0);
thermalBC(thermalmodel,'Edge',[2,4],...
'ConvectionCoefficient',25,...
'AmbientTemperature',50);
generateMesh(thermalmodel);
results = solve(thermalmodel)
results =
SteadyStateThermalResults with properties:
The solver finds the values of temperatures and temperature gradients at the nodal
locations. To access these values, use results.Temperature, results.XGradients,
and so on. For example, plot the temperatures at nodal locations.
figure;
pdeplot(thermalmodel,'XYData',results.Temperature,...
'Contour','on','ColorMap','hot');
5-529
5 Functions — Alphabetical List
Interpolate the resulting temperatures to a grid covering the central portion of the
geometry, for x and y from -0.5 to 0.5.
v = linspace(-0.5,0.5,11);
[X,Y] = meshgrid(v);
Tintrp = interpolateTemperature(results,X,Y);
Tintrp = reshape(Tintrp,size(X));
figure
contourf(X,Y,Tintrp)
5-530
interpolateTemperature
colormap(hot)
colorbar
Alternatively, you can specify the grid by using a matrix of query points.
querypoints = [X(:),Y(:)]';
Tintrp = interpolateTemperature(results,querypoints);
5-531
5 Functions — Alphabetical List
thermalmodel = createpde('thermal');
importGeometry(thermalmodel,'Block.stl');
pdegplot(thermalmodel,'FaceLabels','on','FaceAlpha',0.5)
title('Copper block, cm')
axis equal
Assuming that this is a copper block, the thermal conductivity of the block is
approximately 4 W/(cm*K).
thermalProperties(thermalmodel,'ThermalConductivity',4);
5-532
interpolateTemperature
Apply a constant temperature of 373 K to the left side of the block (edge 1) and a constant
temperature of 573 K at the right side of the block.
thermalBC(thermalmodel,'Face',1,'Temperature',373);
thermalBC(thermalmodel,'Face',3,'Temperature',573);
thermalBC(thermalmodel,'Face',4,'HeatFlux',-20);
generateMesh(thermalmodel);
thermalresults = solve(thermalmodel)
thermalresults =
SteadyStateThermalResults with properties:
The solver finds the values of temperatures and temperature gradients at the nodal
locations. To access these values, use results.Temperature, results.XGradients,
and so on. For example, plot temperatures at nodal locations.
figure;
pdeplot3D(thermalmodel,'ColorMapData',thermalresults.Temperature)
5-533
5 Functions — Alphabetical List
[X,Y,Z] = meshgrid(1:16:100,1:6:20,1:7:50);
Tintrp = interpolateTemperature(thermalresults,X,Y,Z);
figure
Tintrp = reshape(Tintrp,size(X));
contourslice(X,Y,Z,Tintrp,[],1:6:20,[])
5-534
interpolateTemperature
xlabel('x')
ylabel('y')
zlabel('z')
xlim([1,100])
ylim([1,20])
zlim([1,50])
axis equal
view(-50,22)
colorbar
Alternatively, you can specify the grid by using a matrix of query points.
querypoints = [X(:),Y(:),Z(:)]';
Tintrp = interpolateTemperature(thermalresults,querypoints);
5-535
5 Functions — Alphabetical List
Create a contour slice plot for four fixed values of the z coordinate.
figure
Tintrp = reshape(Tintrp,size(X));
contourslice(X,Y,Z,Tintrp,[],[],1:7:50)
xlabel('x')
ylabel('y')
zlabel('z')
xlim([1,100])
ylim([1,20])
zlim([1,50])
axis equal
view(-50,22)
colorbar
5-536
interpolateTemperature
Solve a 2-D transient heat transfer problem on a square domain and compute
temperatures at the convective boundary.
thermalmodel = createpde('thermal','transient');
5-537
5 Functions — Alphabetical List
g = @squareg;
geometryFromEdges(thermalmodel,g);
pdegplot(thermalmodel,'EdgeLabels','on')
xlim([-1.2,1.2])
ylim([-1.2,1.2])
axis equal
5-538
interpolateTemperature
thermalProperties(thermalmodel,'ThermalConductivity',100,...
'MassDensity',7800,...
'SpecificHeat',500);
Apply insulated boundary conditions on three edges and the free convection boundary
condition on the right edge.
thermalBC(thermalmodel,'Edge',[1,3,4],'HeatFlux',0);
thermalBC(thermalmodel,'Edge',2,...
'ConvectionCoefficient',5000,...
'AmbientTemperature',25);
Set the initial conditions: uniform room temperature across domain and higher
temperature on the left edge.
thermalIC(thermalmodel,25);
thermalIC(thermalmodel,100,'Edge',4);
Generate a mesh and solve the problem using 0:1000:200000 as a vector of times.
generateMesh(thermalmodel);
tlist = 0:1000:200000;
thermalresults = solve(thermalmodel,tlist)
thermalresults =
TransientThermalResults with properties:
Define a line at convection boundary and compute temperature gradients across that line.
X = -1:0.1:1;
Y = ones(size(X));
Tintrp = interpolateTemperature(thermalresults,X,Y,1:length(tlist));
Plot the interpolated temperature Tintrp along the x axis for the following values from
the time interval tlist.
5-539
5 Functions — Alphabetical List
figure
t = [51:50:201];
for i = t
p(i) = plot(X,Tintrp(:,i),'DisplayName', strcat('t=', num2str(tlist(i))));
hold on
end
legend(p(t))
xlabel('x')
ylabel('Tintrp')
5-540
interpolateTemperature
Input Arguments
thermalresults — Solution of thermal problem
SteadyStateThermalResults object | TransientThermalResults object
5-541
5 Functions — Alphabetical List
Query points, specified as a real matrix with either two rows for 2-D geometry, or three
rows for 3-D geometry. interpolateTemperature evaluates temperatures at the
coordinate points querypoints(:,i), so each column of querypoints contains exactly
one 2-D or 3-D query point.
Example: For 2-D geometry, querypoints = [0.5,0.5,0.75,0.75; 1,2,0,0.5]
Data Types: double
iT — Time indices
vector of positive integers
Time indices, specified as a vector of positive integers. Each entry in iT specifies a time
index.
Example: iT = 1:5:21 specifies every fifth time-step up to 21.
Data Types: double
Output Arguments
Tintrp — Temperatures at query points
array
Temperatures at query points, returned as an array. For query points that are outside the
geometry, Tintrp = NaN.
See Also
SteadyStateThermalResults | ThermalModel | TransientThermalResults |
evaluateHeatFlux | evaluateHeatRate | evaluateTemperatureGradient
Topics
“Dimensions of Solutions, Gradients, and Fluxes” on page 3-299
5-542
interpolateTemperature
Introduced in R2017a
5-543
5 Functions — Alphabetical List
interpolateVelocity
Package: pde
Interpolate velocity at arbitrary spatial locations for all time steps for transient structural
model
Syntax
intrpVel = interpolateVelocity(structuralresults,xq,yq)
intrpVel = interpolateVelocity(structuralresults,xq,yq,zq)
intrpVel = interpolateVelocity(structuralresults,querypoints)
Description
intrpVel = interpolateVelocity(structuralresults,xq,yq) returns the
interpolated velocity values at the 2-D points specified in xq and yq for all time-steps.
Examples
structuralmodel = createpde('structural','transient-solid');
Create the geometry and include it in the model. Plot the geometry.
5-544
interpolateVelocity
gm = multicuboid(0.06,0.005,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
Specify the Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3, ...
'MassDensity',7800);
structuralBC(structuralmodel,'Face',5,'Constraint','fixed');
5-545
5 Functions — Alphabetical List
Apply a sinusoidal displacement along the y-direction on the end opposite the fixed end of
the beam.
structuralBC(structuralmodel,'Face',3,'YDisplacement',1E-4,'Frequency',50);
Generate a mesh.
generateMesh(structuralmodel,'Hmax',0.01);
structuralIC(structuralmodel,'Displacement',[0;0;0],'Velocity',[0;0;0]);
tlist = 0:0.002:0.2;
structuralresults = solve(structuralmodel,tlist);
coordsMidSpan = [0;0;0.005];
intrpVel = interpolateVelocity(structuralresults,coordsMidSpan);
figure
plot(structuralresults.SolutionTimes,intrpVel.vy)
title('Y-Velocity of the Geometric Center of the Beam')
5-546
interpolateVelocity
Input Arguments
structuralresults — Solution of dynamic structural analysis problem
TransientStructuralResults object
5-547
5 Functions — Alphabetical List
interpolateVelocity converts query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns velocities as a structure array with fields of the same size as
these column vectors. To ensure that the dimensions of the returned solution are
consistent with the dimensions of the original query points, use the reshape function.
For example, use intrpVel = reshape(intrpVel.ux,size(xq)).
Data Types: double
Query points, specified as a real matrix with either two rows for 2-D geometry or three
rows for 3-D geometry. interpolateVelocity evaluates velocities at the coordinate
points querypoints(:,i), so each column of querypoints contains exactly one 2-D or
3-D query point.
5-548
interpolateVelocity
Output Arguments
intrpVel — Velocities at query points
structure array
Velocities at the query points, returned as a structure array with fields representing
spatial components of velocity at the query points. For query points that are outside the
geometry, intrpVel returns NaN.
See Also
StructuralModel | TransientStructuralResults | evaluatePrincipalStrain |
evaluatePrincipalStress | evaluateReaction | evaluateStrain |
evaluateStress | evaluateVonMisesStress | interpolateAcceleration |
interpolateDisplacement | interpolateStrain | interpolateStress |
interpolateVonMisesStress
Introduced in R2018a
5-549
5 Functions — Alphabetical List
interpolateVonMisesStress
Package: pde
Syntax
intrpVMStress = interpolateVonMisesStress(structuralresults,xq,yq)
intrpVMStress = interpolateVonMisesStress(structuralresults,xq,yq,
zq)
intrpVMStress = interpolateVonMisesStress(structuralresults,
querypoints)
Description
intrpVMStress = interpolateVonMisesStress(structuralresults,xq,yq)
returns the interpolated von Mises stress values at the 2-D points specified in xq and yq.
For a dynamic structural model, interpolateVonMisesStress interpolates von Mises
stress for all time-steps.
intrpVMStress = interpolateVonMisesStress(structuralresults,xq,yq,
zq) uses the 3-D points specified in xq, yq, and zq.
intrpVMStress = interpolateVonMisesStress(structuralresults,
querypoints) uses the points specified in querypoints.
Examples
structuralmodel = createpde('structural','static-planestrain');
5-550
interpolateVonMisesStress
geometryFromEdges(structuralmodel,@squareg);
pdegplot(structuralmodel,'EdgeLabels','on')
axis equal
structuralProperties(structuralmodel,'PoissonsRatio',0.3, ...
'YoungsModulus',210E3);
structuralBC(structuralmodel,'XDisplacement',0.001,'Edge',1);
5-551
5 Functions — Alphabetical List
structuralBC(structuralmodel,'Constraint','fixed','Edge',3);
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel);
Create a grid and interpolate the von Mises stress to the grid.
v = linspace(-1,1,151);
[X,Y] = meshgrid(v);
intrpVMStress = interpolateVonMisesStress(structuralresults,X,Y);
Reshape the von Mises stress to the shape of the grid and plot it.
VMStress = reshape(intrpVMStress,size(X));
p = pcolor(X,Y,VMStress);
p.EdgeColor='none';
colorbar
5-552
interpolateVonMisesStress
Interpolate Von Mises Stress for 3-D Static Structural Analysis Problem
Solve a static structural model representing a bimetallic cable under tension, and
interpolate the von Mises stress on a cross-section of the cable.
structuralmodel = createpde('structural','static-solid');
Create the geometry and include it in the model. Plot the geometry.
5-553
5 Functions — Alphabetical List
gm = multicylinder([0.01,0.015],0.05);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','CellLabels','on','FaceAlpha',0.5)
Specify the Young's modulus and Poisson's ratio for each metal.
structuralProperties(structuralmodel,'Cell',1,'YoungsModulus',110E9, ...
'PoissonsRatio',0.28);
structuralProperties(structuralmodel,'Cell',2,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3);
structuralBC(structuralmodel,'Face',[1,4],'Constraint','fixed');
5-554
interpolateVonMisesStress
structuralBoundaryLoad(structuralmodel,'Face',[2,5],'SurfaceTraction',[0;0;100]);
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel)
structuralresults =
StaticStructuralResults with properties:
[X,Y] = meshgrid(linspace(-0.015,0.015,50));
Z = ones(size(X))*0.025;
IntrpVMStress = interpolateVonMisesStress(structuralresults,X,Y,Z);
surf(X,Y,reshape(IntrpVMStress,size(X)))
5-555
5 Functions — Alphabetical List
Alternatively, you can specify the grid by using a matrix of query points.
querypoints = [X(:),Y(:),Z(:)]';
IntrpVMStress = interpolateVonMisesStress(structuralresults,querypoints);
surf(X,Y,reshape(IntrpVMStress,size(X)))
5-556
interpolateVonMisesStress
Interpolate the von Mises stress at the geometric center of a beam under a harmonic
excitation.
structuralmodel = createpde('structural','transient-solid');
Create the geometry and include it in the model. Plot the geometry.
5-557
5 Functions — Alphabetical List
gm = multicuboid(0.06,0.005,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
Specify the Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3, ...
'MassDensity',7800);
structuralBC(structuralmodel,'Face',5,'Constraint','fixed');
5-558
interpolateVonMisesStress
Apply a sinusoidal displacement along the y-direction on the end opposite the fixed end of
the beam.
structuralBC(structuralmodel,'Face',3,'YDisplacement',1E-4,'Frequency',50);
Generate a mesh.
generateMesh(structuralmodel,'Hmax',0.01);
structuralIC(structuralmodel,'Displacement',[0;0;0],'Velocity',[0;0;0]);
tlist = 0:0.002:0.2;
structuralresults = solve(structuralmodel,tlist);
Interpolate the von Mises stress at the geometric center of the beam.
coordsMidSpan = [0;0;0.005];
intrpStress = interpolateStress(structuralresults,coordsMidSpan);
Plot the von Mises stress at the geometric center of the beam.
figure
plot(structuralresults.SolutionTimes,intrpStress.sxx)
title('von Mises Stress at Beam Center')
5-559
5 Functions — Alphabetical List
Input Arguments
structuralresults — Solution of structural analysis problem
StaticStructuralResults object | TransientStructuralResults object
5-560
interpolateVonMisesStress
Query points, specified as a real matrix with either two rows for 2-D geometry or three
rows for 3-D geometry. interpolateVonMisesStress evaluates the von Mises stress at
5-561
5 Functions — Alphabetical List
Output Arguments
intrpVMStress — von Mises stress at query points
column vector
For query points that are outside the geometry, intrpVMStress = NaN.
See Also
StaticStructuralResults | StructuralModel | evaluatePrincipalStrain |
evaluatePrincipalStress | evaluateReaction | interpolateDisplacement |
interpolateStrain | interpolateStress
Introduced in R2017b
5-562
jigglemesh
jigglemesh
(Not recommended) Jiggle internal points of triangular mesh
Note This page describes the legacy workflow. New features might not be compatible
with the legacy workflow. For the corresponding step in the recommended workflow, see
generateMesh.
Syntax
p1 = jigglemesh(p,e,t)
p1 = jigglemesh(p,e,t,'PropertyName',PropertyValue,...)
Description
p1 = jigglemesh(p,e,t) jiggles the triangular mesh by adjusting the node point
positions. The quality of the mesh normally increases.
Each mesh point that is not located on an edge segment is moved toward the center of
mass of the polygon formed by the adjacent triangles. This process is repeated according
to the settings of the Opt and Iter variables:
• When Opt is set to 'off' this process is repeated Iter times (default: 1).
• When Opt is set to 'mean' the process is repeated until the mean triangle quality
does not significantly increase, or until the bound Iter is reached (default: 20).
5-563
5 Functions — Alphabetical List
• When Opt is set to 'minimum' the process is repeated until the minimum triangle
quality does not significantly increase, or until the bound Iter is reached (default:
20).
Examples
Mesh Jiggling
Create a triangular mesh of the L-shaped membrane, first without jiggling, and then jiggle
the mesh.
[p,e,t] = initmesh('lshapeg','jiggle','off');
q = pdetriq(p,t);
pdeplot(p,e,t,'XYData',q,'ColorBar','on','XYStyle','flat')
5-564
jigglemesh
p1 = jigglemesh(p,e,t,'opt','mean','iter',inf);
q = pdetriq(p1,t);
pdeplot(p1,e,t,'XYData',q,'ColorBar','on','XYStyle','flat')
5-565
5 Functions — Alphabetical List
See Also
initmesh | pdetriq
Topics
“Mesh Data” on page 2-241
5-566
meshQuality
meshQuality
Package: pde
Syntax
Q = meshQuality(mesh)
Q = meshQuality(mesh,elemIDs)
Q = meshQuality( ___ ,'aspect-ratio')
Description
Q = meshQuality(mesh) returns a row vector of numbers from 0 through 1
representing shape quality of all elements of the mesh. Here, 1 corresponds to the
optimal shape of the element.
Examples
model = createpde;
5-567
5 Functions — Alphabetical List
mesh =
FEMesh with properties:
5-568
meshQuality
MinElementSize: 17.5000
MeshGradation: 1.5000
GeometricOrder: 'quadratic'
pdemesh(model)
Evaluate the shape quality of all mesh elements. Display the first five values.
Q = meshQuality(mesh);
Q(1:5)
ans = 1×5
5-569
5 Functions — Alphabetical List
Find the elements with the quality values less than 0.2.
pdemesh(mesh,'FaceAlpha',0.5)
hold on
pdemesh(mesh.Nodes,mesh.Elements(:,elemIDs),'FaceColor','blue','EdgeColor','blue')
5-570
meshQuality
figure
hist(Q)
xlabel('Element Shape Quality','fontweight','b')
ylabel('Number of Elements','fontweight','b')
Qworst = min(Q)
Qworst = 0.1691
elemIDs = find(Q==Qworst)
5-571
5 Functions — Alphabetical List
elemIDs = 1×2
10 136
model = createpde;
importGeometry(model,'PlateSquareHolePlanar.stl');
pdegplot(model)
5-572
meshQuality
mesh = generateMesh(model,'Hmax',20)
mesh =
FEMesh with properties:
5-573
5 Functions — Alphabetical List
pdemesh(model)
Find the IDs of the elements within a box enclosing the center of the plate.
elemIDs = findElements(mesh,'box',[25,75],[80,120]);
Q = meshQuality(mesh,elemIDs)
Q = 1×12
5-574
meshQuality
Find the elements with the quality values less than 0.4.
elemIDs04 = elemIDs(Q < 0.4)
elemIDs04 = 1×4
9 19 69 83
Highlight these elements in green on the mesh plot. Zoom in to see the details.
pdemesh(mesh,'ElementLabels','on')
hold on
pdemesh(mesh.Nodes,mesh.Elements(:,elemIDs04),'EdgeColor','green')
zoom(10)
5-575
5 Functions — Alphabetical List
Determine the shape quality of mesh elements by using the ratios of minimal to maximal
dimensions.
model = createpde(1);
geometryFromEdges(model,@lshapeg);
mesh = generateMesh(model);
pdeplot(model)
5-576
meshQuality
Evaluate the shape quality of mesh elements by using the minimal to maximal dimensions
ratio. Display the first five values.
Q = meshQuality(mesh,'aspect-ratio');
Q(1:5)
ans =
Evaluate the shape quality of mesh elements by using the default setting. Display the first
five values.
5-577
5 Functions — Alphabetical List
Q = meshQuality(mesh);
Q(1:5)
ans =
Input Arguments
mesh — Mesh object
Mesh property of a PDEModel object | output of generateMesh
Mesh object, specified as the Mesh property of a PDEModel object or as the output of
generateMesh.
Example: model.Mesh
Output Arguments
Q — Shape quality of mesh elements
row vector of numbers from 0 through 1
Shape quality of mesh elements, returned as a row vector of numbers from 0 through 1.
The value 0 corresponds to a deflated element with zero area or volume. The value 1
corresponds to an element of optimal shape.
Example: [0.9150 0.7787 0.9417 0.2744 0.9843 0.9181]
Data Types: double
5-578
meshQuality
References
[1] Knupp, Patrick M. "Matrix Norms & the Condition Number: A General Framework to
Improve Mesh Quality via Node-Movement." In Proceedings, 8th International
Meshing Roundtable. Lake Tahoe, CA, October 1999: 13-22.
See Also
FEMesh Properties | area | findElements | findNodes | volume
Topics
“Finite Element Method Basics” on page 1-27
Introduced in R2018a
5-579
5 Functions — Alphabetical List
meshToPet
Package: pde
Note This page describes the legacy workflow. New features might not be compatible
with the [p,e,t] representation of FEMesh data.
Syntax
[p,e,t] = meshToPet(mesh)
Description
[p,e,t] = meshToPet(mesh) extracts the legacy [p,e,t] mesh representation from
a FEMesh object.
Examples
This example shows how to convert a mesh in object form to [p,e,t] form.
Create a 2-D PDE geometry and incorporate it into a model object. View the geometry.
model = createpde(1);
R1 = [3,4,-1,1,1,-1,-.4,-.4,.4,.4]';
C1 = [1,.5,0,.2]';
% Pad C1 with zeros to enable concatenation with R1
C1 = [C1;zeros(length(R1)-length(C1),1)];
geom = [R1,C1];
ns = (char('R1','C1'))';
sf = 'R1-C1';
5-580
meshToPet
gd = decsg(geom,sf,ns);
geometryFromEdges(model,gd);
pdegplot(model,'EdgeLabels','on')
xlim([-1.1 1.1])
axis equal
generateMesh(model);
pdemesh(model)
axis equal
5-581
5 Functions — Alphabetical List
[p,e,t] = meshToPet(model.Mesh);
size(p)
ans = 1×2
2 956
size(e)
5-582
meshToPet
ans = 1×2
7 160
size(t)
ans = 1×2
7 438
Input Arguments
mesh — Mesh object
Mesh property of a PDEModel object | output of generateMesh
Mesh object, specified as the Mesh property of a PDEModel object or as the output of
generateMesh.
Example: model.Mesh
Output Arguments
p — Mesh points
2-by-Np matrix | 3-by-Np matrix
Mesh points, returned as a 2-by-Np matrix (2-D geometry) or a 3-by-Np matrix (3-D
geometry). Np is the number of points (nodes) in the mesh. Column k of p consists of the
x-coordinate of point k in p(1,k), the y-coordinate of point k in p(2,k), and, for 3-D, the
z-coordinate of point k in p(3,k). For details, see “Mesh Data” on page 2-241.
e — Mesh edges
7-by-Ne matrix | mesh associativity object
Mesh edges, returned as a 7-by-Ne matrix (2-D), or a mesh associativity object (3-D). Ne is
the number of edges in the mesh. An edge is a pair of points in p containing a boundary
between subdomains, or containing an outer boundary. For details, see “Mesh Data” on
page 2-241.
5-583
5 Functions — Alphabetical List
t — Mesh elements
4-by-Nt matrix | 7-by-Nt matrix | 5-by-Nt matrix | 11-by-Nt matrix
Mesh elements, returned as a 4-by-Nt matrix (2-D with linear elements), a 7-by-Nt matrix
(2-D with quadratic elements), a 5-by-Nt matrix (3-D with linear elements), or an 11-by-Nt
matrix (3-D with quadratic elements). Nt is the number of triangles or tetrahedra in the
mesh.
The t(i,k), with i ranging from 1 through end - 1, contain indices to the corner
points and possibly edge centers of element k. For details, see “Mesh Data” on page 2-
241. The last row, t(end,k), contains the subdomain number of the element.
Tips
• Use meshToPet to obtain the p and t data for interpolation using pdeInterpolant.
See Also
FEMesh | generateMesh
Topics
“Mesh Data” on page 2-241
Introduced in R2015a
5-584
multicuboid
multicuboid
Create geometry formed by several cubic cells
Syntax
gm = multicuboid(W,D,H)
gm = multicuboid(W,D,H,Name,Value)
Description
gm = multicuboid(W,D,H) creates a geometry by combining several cubic cells.
When creating each cuboid, multicuboid uses the following coordinate system.
5-585
5 Functions — Alphabetical List
Examples
Create a geometry that consists of three nested cuboids of the same height and include
this geometry in a PDE model.
Create the geometry by using the multicuboid function. The resulting geometry
consists of three cells.
gm = multicuboid([2 3 5],[4 6 10],3)
gm =
DiscreteGeometry with properties:
NumCells: 3
NumFaces: 18
NumEdges: 36
NumVertices: 24
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
5-586
multicuboid
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
pdegplot(model,'CellLabels','on','FaceAlpha',0.5)
5-587
5 Functions — Alphabetical List
Stacked Cuboids
Create a geometry that consists of four stacked cuboids and include this geometry in a
PDE model.
Create the geometry by using the multicuboid function with the ZOffset argument.
The resulting geometry consists of four cells stacked on top of each other.
gm = multicuboid(5,10,[1 2 3 4],'ZOffset',[0 1 3 6])
gm =
DiscreteGeometry with properties:
5-588
multicuboid
NumCells: 4
NumFaces: 21
NumEdges: 36
NumVertices: 20
model = createpde
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
pdegplot(model,'CellLabels','on','FaceAlpha',0.5)
5-589
5 Functions — Alphabetical List
Single Cuboid
Create a geometry that consists of a single cuboid and include this geometry in a PDE
model.
Use the multicuboid function to create a single cuboid. The resulting geometry consists
of one cell.
gm = multicuboid(5,10,7)
gm =
DiscreteGeometry with properties:
5-590
multicuboid
NumCells: 1
NumFaces: 6
NumEdges: 12
NumVertices: 8
model = createpde
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
pdegplot(model,'CellLabels','on')
5-591
5 Functions — Alphabetical List
Hollow Cube
Create a hollow cube by using the multicuboid function with the Void argument. The
resulting geometry consists of one cell.
gm =
DiscreteGeometry with properties:
5-592
multicuboid
NumCells: 1
NumFaces: 10
NumEdges: 24
NumVertices: 16
model = createpde
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
pdegplot(model,'CellLabels','on','FaceAlpha',0.5)
5-593
5 Functions — Alphabetical List
Input Arguments
W — Cell width
positive real number | vector of positive real numbers
Cell width, specified as a positive real number or a vector of positive real numbers. If W is
a vector, then W(i) specifies the width of the ith cell.
Width W, depth D, and height H can be scalars or vectors of the same length. For a
combination of scalar and vector inputs, multicuboid replicates the scalar arguments
into vectors of the same length.
5-594
multicuboid
Note All cells in the geometry either must have the same height, or must have both the
same width and the same depth.
D — Cell depth
positive real number | vector of positive real numbers
Cell depth, specified as a positive real number or a vector of positive real numbers. If D is
a vector, then D(i) specifies the depth of the ith cell.
Width W, depth D, and height H can be scalars or vectors of the same length. For a
combination of scalar and vector inputs, multicuboid replicates the scalar arguments
into vectors of the same length.
Note All cells in the geometry either must have the same height, or must have both the
same width and the same depth.
H — Cell height
positive real number | vector of positive real numbers
Cell height, specified as a positive real number or a vector of positive real numbers. If H is
a vector, then H(i) specifies the height of the ith cell.
Width W, depth D, and height H can be scalars or vectors of the same length. For a
combination of scalar and vector inputs, multicuboid replicates the scalar arguments
into vectors of the same length.
Note All cells in the geometry either must have the same height, or must have both the
same width and the same depth.
5-595
5 Functions — Alphabetical List
Z offset for each cell, specified as a vector of real numbers. ZOffset(i) specifies the Z
offset of the ith cell. This vector must have the same length as the width vector W, depth
vector D, or height vector H.
Note The ZOffset argument is valid only if the width and depth are constant for all cells
in the geometry.
Empty cell indicator, specified as a vector of logical true or false values. This vector
must have the same length as the width vector W, depth vector D, or the height vector H.
The value true corresponds to an empty cell. By default, multicuboid assumes that all
cells are not empty.
Example: gm = multicuboid([1 2],[1 2],[3 3],'Void',[true,false])
Data Types: double
Output Arguments
gm — Geometry object
DiscreteGeometry object
5-596
multicuboid
Limitations
• multicuboid lets you create only geometries consisting of stacked or nested cuboids.
For nested cuboids, the height must be the same for all cells in the geometry. For
stacked cuboids, the width and depth must be the same for all cells in the geometry.
Use the ZOffset argument to stack the cells on top of each other without overlapping
them.
• multicuboid does not let you create nested cuboids of the same width and depth.
The call multicuboid(w,d,[h1,h2,...]) is not supported.
See Also
DiscreteGeometry | multicylinder | multisphere
Introduced in R2017a
5-597
5 Functions — Alphabetical List
multicylinder
Create geometry formed by several cylindrical cells
Syntax
gm = multicylinder(R,H)
gm = multicylinder(R,H,Name,Value)
Description
gm = multicylinder(R,H) creates a geometry by combining several cylindrical cells.
When creating each cylinder, multicylinder uses the following coordinate system.
5-598
multicylinder
Examples
Create a geometry that consists of three nested cylinders of the same height and include
this geometry in a PDE model.
Create the geometry by using the multicylinder function. The resulting geometry
consists of three cells.
gm = multicylinder([5 10 15],2)
gm =
DiscreteGeometry with properties:
NumCells: 3
NumFaces: 9
NumEdges: 6
NumVertices: 6
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
model =
PDEModel with properties:
5-599
5 Functions — Alphabetical List
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
5-600
multicylinder
Stacked Cylinders
Create a geometry that consists of three stacked cylinders and include this geometry in a
PDE model.
Create the geometry by using the multicylinder function with the ZOffset argument.
The resulting geometry consists of four cells stacked on top of each other.
gm =
DiscreteGeometry with properties:
NumCells: 4
NumFaces: 9
NumEdges: 5
NumVertices: 5
model = createpde
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
5-601
5 Functions — Alphabetical List
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
pdegplot(model,'CellLabels','on','FaceAlpha',0.5)
5-602
multicylinder
Single Cylinder
Create a geometry that consists of a single cylinder and include this geometry in a PDE
model.
Use the multicylinder function to create a single cylinder. The resulting geometry
consists of one cell.
gm = multicylinder(5,10)
gm =
DiscreteGeometry with properties:
NumCells: 1
NumFaces: 3
NumEdges: 2
NumVertices: 2
model = createpde
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
5-603
5 Functions — Alphabetical List
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
pdegplot(model,'CellLabels','on')
5-604
multicylinder
Hollow Cylinder
Create a hollow cylinder by using the multicylinder function with the Void argument.
The resulting geometry consists of one cell.
gm = multicylinder([9 10],10,'Void',[true,false])
gm =
DiscreteGeometry with properties:
NumCells: 1
NumFaces: 4
NumEdges: 4
NumVertices: 4
model = createpde
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
5-605
5 Functions — Alphabetical List
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
pdegplot(model,'CellLabels','on','FaceAlpha',0.5)
5-606
multicylinder
Input Arguments
R — Cell radius
positive real number | vector of positive real numbers
Cell radius, specified as a positive real number or a vector of positive real numbers. If R is
a vector, then R(i) specifies the radius of the ith cell.
Radius R and height H can be scalars or vectors of the same length. For a combination of
scalar and vector inputs, multicylinder replicates the scalar arguments into vectors of
the same length.
Note Either radius or height must be the same for all cells in the geometry.
H — Cell height
positive real number | vector of positive real numbers
Cell height, specified as a positive real number or a vector of positive real numbers. If H is
a vector, then H(i) specifies the height of the ith cell.
Radius R and height H can be scalars or vectors of the same length. For a combination of
scalar and vector inputs, multicylinder replicates the scalar arguments into vectors of
the same length.
Note Either radius or height must be the same for all cells in the geometry.
5-607
5 Functions — Alphabetical List
Z-offset for each cell, specified as a vector of real numbers. ZOffset(i) specifies the Z-
offset of the ith cell. This vector must have the same length as the radius vector R or
height vector H.
Note The ZOffset argument is valid only if the radius is the same for all cells in the
geometry.
Empty cell indicator, specified as a vector of logical true or false values. This vector
must have the same length as the radius vector R or the height vector H.
The value true corresponds to an empty cell. By default, multicylinder assumes that
all cells are not empty.
Example: gm = multicylinder([1 2],1,'Void',[true,false])
Data Types: double
Output Arguments
gm — Geometry object
DiscreteGeometry object
Tip A cylinder has one cell, three faces, and two edges. Also, since every edge has a start
and an end vertex, a cylinder has vertices. Both edges are circles, their start and end
vertices coincide. Thus, a cylinder has two vertices - one for each edge.
5-608
multicylinder
Limitations
• multicylinder lets you create only geometries consisting of stacked or nested
cylinders. For nested cylinders, the height must be the same for all cells in the
geometry. For stacked cylinders, the radius must be the same for all cells in the
geometry. Use the ZOffset argument to stack the cells on top of each over without
overlapping them.
• multicylinder does not let you create nested cylinders of the same radius. The call
multicylinder(r,[h1,h2,...]) is not supported.
See Also
DiscreteGeometry | multicuboid | multisphere
Introduced in R2017a
5-609
5 Functions — Alphabetical List
multisphere
Create geometry formed by several spherical cells
Syntax
gm = multisphere(R)
gm = multisphere(R,'Void',eci)
Description
gm = multisphere(R) creates a geometry by combining several spherical cells.
When creating each sphere, multisphere uses the following coordinate system.
5-610
multisphere
Examples
Nested Spheres
Create a geometry that consists of three nested spheres and include this geometry in a
PDE model.
Create the geometry by using the multisphere function. The resulting geometry
consists of three cells.
gm = multisphere([5 10 15])
gm =
DiscreteGeometry with properties:
NumCells: 3
NumFaces: 3
NumEdges: 0
NumVertices: 0
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
model =
PDEModel with properties:
5-611
5 Functions — Alphabetical List
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
5-612
multisphere
Single Sphere
Create a geometry that consists of a single sphere and include this geometry in a PDE
model.
Use the multisphere function to create a single sphere. The resulting geometry consists
of one cell.
gm = multisphere(5)
gm =
DiscreteGeometry with properties:
NumCells: 1
NumFaces: 1
NumEdges: 0
NumVertices: 0
model = createpde
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
5-613
5 Functions — Alphabetical List
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
pdegplot(model,'CellLabels','on')
5-614
multisphere
Hollow Sphere
Create a hollow sphere by using the multisphere function with the Void argument. The
resulting geometry consists of one cell.
gm = multisphere([9 10],'Void',[true,false])
gm =
DiscreteGeometry with properties:
NumCells: 1
NumFaces: 2
NumEdges: 0
NumVertices: 0
model = createpde
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
5-615
5 Functions — Alphabetical List
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
Input Arguments
R — Cell radius
positive real number | vector of positive real numbers
Cell radius, specified as a positive real number or a vector of positive real numbers. If R is
a vector, then R(i) specifies the radius of the ith cell.
Example: gm = multisphere([1,2,3])
Empty cell indicator, specified as a vector of logical true and false values. This vector
must have the same length as the radius vector R.
The value true corresponds to an empty cell. By default, multisphere assumes that all
cells are not empty.
Example: gm = multisphere([1,2,3],'Void',[false,true,false])
Output Arguments
gm — Geometry object
DiscreteGeometry object
See Also
DiscreteGeometry | multicuboid | multicylinder
5-616
multisphere
Topics
“Heat Conduction in Multidomain Geometry with Nonuniform Heat Flux”
Introduced in R2017a
5-617
5 Functions — Alphabetical List
parabolic
(Not recommended) Solve parabolic PDE problem
∂u
d - — ◊ ( c— u ) + au = f
∂t
∂u
d - — ◊ ( c ƒ — u ) + au = f
∂t
The variables c, a, f, and d can depend on position, time, and the solution u and its
gradient.
Syntax
u = parabolic(u0,tlist,model,c,a,f,d)
u = parabolic(u0,tlist,b,p,e,t,c,a,f,d)
u = parabolic(u0,tlist,Kc,Fc,B,ud,M)
u = parabolic( ___ ,rtol)
u = parabolic( ___ ,rtol,atol)
u = parabolic( ___ ,'Stats','off')
Description
u = parabolic(u0,tlist,model,c,a,f,d) produces the solution to the FEM
formulation of the scalar PDE problem
5-618
parabolic
∂u
d - — ◊ ( c— u ) + au = f
∂t
∂u
d - — ◊ ( c ƒ — u ) + au = f
∂t
with geometry, mesh, and boundary conditions specified in model, and with initial value
u0. The variables c, a, f, and d in the equation correspond to the function coefficients c, a,
f, and d respectively.
u = parabolic( ___ ,rtol) and u = parabolic( ___ ,rtol,atol), for any of the
previous input arguments, modify the solution process by passing to the ODE solver a
relative tolerance rtol, and optionally an absolute tolerance atol.
Examples
Parabolic Equation
5-619
5 Functions — Alphabetical List
model = createpde;
geometryFromEdges(model,@squareg);
pdegplot(model,'EdgeLabels','on')
ylim([-1.1,1.1])
axis equal
applyBoundaryCondition(model,'dirichlet','Edge',1:model.Geometry.NumEdges,'u',0);
generateMesh(model,'Hmax',0.02,'GeometricOrder','linear');
5-620
parabolic
Plot the initial condition, the solution at the final time, and two intermediate solutions.
figure
subplot(2,2,1)
pdeplot(model,'XYData',u(:,1));
axis equal
title('t = 0')
subplot(2,2,2)
pdeplot(model,'XYData',u(:,5))
axis equal
title('t = 0.02')
subplot(2,2,3)
pdeplot(model,'XYData',u(:,11))
axis equal
title('t = 0.05')
5-621
5 Functions — Alphabetical List
subplot(2,2,4)
pdeplot(model,'XYData',u(:,end))
axis equal
title('t = 0.1')
5-622
parabolic
on the square domain specified by squareg, using a geometry function to specify the
geometry, a boundary function to specify the boundary conditions, and using initmesh to
create the finite element mesh.
g = @squareg;
pdegplot(g,'EdgeLabels','on')
ylim([-1.1,1.1])
axis equal
Set Dirichlet boundary conditions on all edges. The squareb1 function specifies
these boundary conditions.
5-623
5 Functions — Alphabetical List
b = @squareb1;
[p,e,t] = initmesh(g,'Hmax',0.02);
u0 = zeros(size(p,2),1);
ix = find(sqrt(p(1,:).^2 + p(2,:).^2) <= 0.4);
u0(ix) = ones(size(ix));
tlist = linspace(0,0.1,21);
c = 1;
a = 0;
f = 0;
d = 1;
u = parabolic(u0,tlist,b,p,e,t,c,a,f,d);
Plot the initial condition, the solution at the final time, and two intermediate solutions.
figure
subplot(2,2,1)
pdeplot(p,e,t,'XYData',u(:,1));
axis equal
title('t = 0')
subplot(2,2,2)
pdeplot(p,e,t,'XYData',u(:,5))
axis equal
5-624
parabolic
title('t = 0.02')
subplot(2,2,3)
pdeplot(p,e,t,'XYData',u(:,11))
axis equal
title('t = 0.05')
subplot(2,2,4)
pdeplot(p,e,t,'XYData',u(:,end))
axis equal
title('t = 0.1')
5-625
5 Functions — Alphabetical List
Create finite element matrices that encode a parabolic problem, and solve the problem.
model = createpde(1);
importGeometry(model,'Block.stl');
handl = pdegplot(model,'FaceLabels','on');
view(-42,24)
handl(1).FaceAlpha = 0.5;
5-626
parabolic
Faces 1, 4, and 6 of the slab are kept at 0 degrees. The other faces are insulated. Include
the boundary condition on faces 1, 4, and 6. You do not need to include the boundary
condition on the other faces because the default condition is insulated.
applyBoundaryCondition(model,'dirichlet','Face',[1,4,6],'u',0);
generateMesh(model);
p = model.Mesh.Nodes;
x = p(1,:);
y = p(2,:);
z = p(3,:);
u0 = x.*y.*z*1e-3;
Suppose the thermal conductivity of the block leads to a coefficient value of 1. The
values of the other coefficients in this problem are , , and .
d = 1;
c = 1;
a = 0;
f = 0;
[Kc,Fc,B,ud] = assempde(model,c,a,f);
[~,M,~] = assema(model,0,d,f);
Solve the problem at time steps of 1 for times ranging from 0 to 40.
tlist = linspace(0,40,41);
u = parabolic(u0,tlist,Kc,Fc,B,ud,M);
35 successful steps
0 failed attempts
5-627
5 Functions — Alphabetical List
72 function evaluations
1 partial derivatives
11 LU decompositions
71 solutions of linear systems
Plot the solution on the outside of the block at times 0, 10, 25, and 40. Ensure that the
coloring is the same for all plots.
umin = min(min(u));
umax = max(max(u));
subplot(2,2,1)
pdeplot3D(model,'ColorMapData',u(:,1))
colorbar off
view(125,22)
title 't = 0'
caxis([umin umax]);
subplot(2,2,2)
pdeplot3D(model,'ColorMapData',u(:,11))
colorbar off
view(125,22)
title 't = 10'
caxis([umin umax]);
subplot(2,2,3)
pdeplot3D(model,'ColorMapData',u(:,26))
colorbar off
view(125,22)
title 't = 25'
caxis([umin umax]);
subplot(2,2,4)
pdeplot3D(model,'ColorMapData',u(:,41))
colorbar off
view(125,22)
title 't = 40'
caxis([umin umax]);
5-628
parabolic
Input Arguments
u0 — Initial condition
vector | character vector | character array | string scalar | string vector
Initial condition, specified as a scalar, vector of nodal values, character vector, character
array, string scalar, or string vector. The initial condition is the value of the solution u at
the initial time, specified as a column vector of values at the nodes. The nodes are either
p in the [p,e,t] data structure, or are model.Mesh.Nodes. For details, see “Solve
PDEs with Initial Conditions” on page 2-168.
5-629
5 Functions — Alphabetical List
Example: x.^2+5*cos(y.*x)
Data Types: double | char | string
Complex Number Support: Yes
Solution times, specified as a real vector. The solver returns the solution to the PDE at the
solution times.
Example: 0:0.2:4
Data Types: double
c — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. c represents the c coefficient in the scalar
PDE
∂u
d - — ◊ ( c— u ) + au = f
∂t
5-630
parabolic
∂u
d - — ◊ ( c ƒ — u ) + au = f
∂t
You can specifyc in various ways, detailed in “c Coefficient for Systems” on page 2-131.
See also “Specify Scalar PDE Coefficients in Character Form” on page 2-76, “Specify 2-D
Scalar Coefficients in Function Form” on page 2-82, and “Specify 3-D PDE Coefficients in
Function Form” on page 2-85.
Example: 'cosh(x+y.^2)'
Data Types: double | char | string | function_handle
Complex Number Support: Yes
a — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. a represents the a coefficient in the scalar
PDE
∂u
d - — ◊ ( c— u ) + au = f
∂t
∂u
d - — ◊ ( c ƒ — u ) + au = f
∂t
You can specifya in various ways, detailed in “a or d Coefficient for Systems” on page 2-
154. See also “Specify Scalar PDE Coefficients in Character Form” on page 2-76, “Specify
2-D Scalar Coefficients in Function Form” on page 2-82, and “Specify 3-D PDE
Coefficients in Function Form” on page 2-85.
Example: 2*eye(3)
Data Types: double | char | string | function_handle
Complex Number Support: Yes
5-631
5 Functions — Alphabetical List
f — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. f represents the f coefficient in the scalar
PDE
∂u
d - — ◊ ( c— u ) + au = f
∂t
∂u
d - — ◊ ( c ƒ — u ) + au = f
∂t
You can specifyf in various ways, detailed in “f Coefficient for Systems” on page 2-104.
See also “Specify Scalar PDE Coefficients in Character Form” on page 2-76, “Specify 2-D
Scalar Coefficients in Function Form” on page 2-82, and “Specify 3-D PDE Coefficients in
Function Form” on page 2-85.
Example: char('sin(x)';'cos(y)';'tan(z)')
Data Types: double | char | string | function_handle
Complex Number Support: Yes
d — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. d represents the d coefficient in the scalar
PDE
∂u
d - — ◊ ( c— u ) + au = f
∂t
∂u
d - — ◊ ( c ƒ — u ) + au = f
∂t
5-632
parabolic
You can specifyd in various ways, detailed in “a or d Coefficient for Systems” on page 2-
154. See also “Specify Scalar PDE Coefficients in Character Form” on page 2-76, “Specify
2-D Scalar Coefficients in Function Form” on page 2-82, and “Specify 3-D PDE
Coefficients in Function Form” on page 2-85.
Example: 2*eye(3)
Data Types: double | char | string | function_handle
Complex Number Support: Yes
b — Boundary conditions
boundary matrix | boundary file
Boundary conditions, specified as a boundary matrix or boundary file. Pass a boundary file
as a function handle or as a file name.
• A boundary matrix is generally an export from the PDE Modeler app. For details of the
structure of this matrix, see “Boundary Matrix for 2-D Geometry” on page 2-175.
• A boundary file is a file that you write in the syntax specified in “Boundary Conditions
by Writing Functions” on page 2-204.
p — Mesh points
matrix
Mesh points, specified as a 2-by-Np matrix of points, where Np is the number of points in
the mesh. For a description of the (p,e,t) matrices, see “Mesh Data” on page 2-241.
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
e — Mesh edges
matrix
Mesh edges, specified as a 7-by-Ne matrix of edges, where Ne is the number of edges in
the mesh. For a description of the (p,e,t) matrices, see “Mesh Data” on page 2-241.
5-633
5 Functions — Alphabetical List
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
t — Mesh triangles
matrix
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
Kc — Stiffness matrix
sparse matrix | full matrix
Stiffness matrix, specified as a sparse matrix or as a full matrix. See “Elliptic Equations”
on page 5-75. Typically, Kc is the output of assempde.
Fc — Load vector
vector
Load vector, specified as a vector. See “Elliptic Equations” on page 5-75. Typically, Fc is
the output of assempde.
B — Dirichlet nullspace
sparse matrix
Dirichlet nullspace, returned as a sparse matrix. See “Algorithms” on page 5-75. Typically,
B is the output of assempde.
ud — Dirichlet vector
vector
Dirichlet vector, returned as a vector. See “Algorithms” on page 5-75. Typically, ud is the
output of assempde.
5-634
parabolic
M — Mass matrix
sparse matrix | full matrix
Mass matrix. specified as a sparse matrix or a full matrix. See “Elliptic Equations” on
page 5-75.
To obtain the input matrices for pdeeig, hyperbolic or parabolic, run both assema
and assempde:
[Kc,Fc,B,ud] = assempde(model,c,a,f);
[~,M,~] = assema(model,0,d,f);
Note Create the M matrix using assema with d, not a, as the argument before f.
Output Arguments
u — PDE solution
matrix
PDE solution, returned as a matrix. The matrix is Np*N-by-T, where Np is the number of
nodes in the mesh, N is the number of equations in the PDE (N = 1 for a scalar PDE), and
5-635
5 Functions — Alphabetical List
T is the number of solution times, meaning the length of tlist. The solution matrix has
the following structure.
• The first Np elements of each column in u represent the solution of equation 1, then
next Np elements represent the solution of equation 2, etc. The solution u is the value
at the corresponding node in the mesh.
• Column i of u represents the solution at time tlist(i).
To plot the solution, use pdeplot for 2-D geometry, or see “Plot 3-D Solutions and Their
Gradients” on page 3-277.
Algorithms
∂ 2u ∂u
m +d - —·( c—u ) + au = f
2 ∂t
∂t
When the m coefficient is 0, but d is not, the documentation refers to the equation as
parabolic, whether or not it is mathematically in parabolic form.
∂u
d - — ◊ ( c— u ) + au = f in W
∂t
5-636
parabolic
where x represents a 2-D or 3-D point and there are boundary conditions of the same kind
as for the elliptic equation on ∂Ω.
∂u
rC - — · ( k— u) + h ( u - u• ) = f
∂t
in the presence of distributed heat loss to the surroundings. ρ is the density, C is the
thermal capacity, k is the thermal conductivity, h is the film coefficient, u∞ is the ambient
temperature, and f is the heat source.
For time-independent coefficients, the steady-state solution of the equation is the solution
to the standard elliptic equation
–∇ · (c∇u) + au = f. (5-16)
Assuming a mesh on Ω and t ≥ 0, expand the solution to the PDE (as a function of x) in
the Finite Element Method basis:
Plugging the expansion into the PDE, multiplying with a test function ϕj, integrating over
Ω, and applying Green's formula and the boundary conditions yield
dUi ( t )
Â Ú df jfi dt
dx +  ÊÁ Ú ( —f j ◊ (c—fi ) + af jfi ) dx + Ú qf jfi ds ˆ˜ Ui (t)
i W i ËW ∂W ¯
= Ú f f j dx + Ú gf j ds "j
W ∂W
In matrix notation, we have to solve the linear, large and sparse ODE system
dU
M + KU = F
dt
5-637
5 Functions — Alphabetical List
yields the solution to the PDE at each node xi and time t. Note that K and F are the
stiffness matrix and the right-hand side of the elliptic problem
–∇ · (c∇u) + au = f in Ω (5-18)
with the original boundary conditions, while M is just the mass matrix of the problem
–∇ · (0∇u) + du = 0 in Ω. (5-19)
When the Dirichlet conditions are time dependent, F contains contributions from time
derivatives of h and r. These derivatives are evaluated by finite differences of the user-
specified data.
The ODE system is ill conditioned. Explicit time integrators are forced by stability
requirements to very short time steps while implicit solvers can be expensive since they
solve an elliptic problem at every time step. The numerical integration of the ODE system
is performed by the MATLAB ODE Suite functions, which are efficient for this class of
problems. The time step is controlled to satisfy a tolerance on the error, and factorizations
of coefficient matrices are performed only when necessary. When coefficients are time
dependent, the necessity of reevaluating and refactorizing the matrices each time step
may still make the solution time consuming, although parabolic reevaluates only that
which varies with time. In certain cases a time-dependent Dirichlet matrix h(t) may cause
the error control to fail, even if the problem is mathematically sound and the solution u(t)
is smooth. This can happen because the ODE integrator looks only at the reduced solution
v with u = Bv + ud. As h changes, the pivoting scheme employed for numerical stability
may change the elimination order from one step to the next. This means that B, v, and ud
all change discontinuously, although u itself does not.
See Also
solvepde
Topics
“PDE Problem Setup”
5-638
pdeadgsc
pdeadgsc
(Not recommended) Select triangles using relative tolerance criterion
Syntax
bt = pdeadgsc(p,t,c,a,f,u,errf,tol)
Description
bt = pdeadgsc(p,t,c,a,f,u,errf,tol) returns indices of triangles to be refined in
bt. Used from adaptmesh to select the triangles to be further refined. The geometry of
the PDE problem is given by the mesh data p and t. For more details, see “Mesh Data” on
page 2-241.
Triangles are selected using the criterion errf>tol*scale, where scale is calculated
as follows:
Let cmax, amax, fmax, and umax be the maximum of c, a, f, and u, respectively. Let l be
the side of the smallest axis-aligned square that contains the geometry.
5-639
5 Functions — Alphabetical List
See Also
generateMesh
5-640
pdeadworst
pdeadworst
(Not recommended) Select triangles relative to worst value
Syntax
bt = pdeadworst(p,t,c,a,f,u,errf,wlevel)
Description
bt = pdeadworst(p,t,c,a,f,u,errf,wlevel) returns indices of triangles to be
refined in bt. Used from adaptmesh to select the triangles to be further refined.
The geometry of the PDE problem is given by the mesh data p and t. For details, see
“Mesh Data” on page 2-241.
wlevel is the error level relative to the worst error. wlevel must be between 0 and 1.
See Also
generateMesh
5-641
5 Functions — Alphabetical List
pdearcl
Interpolation between parametric representation and arc length
Syntax
pp = pdearcl(p,xy,s,s0,s1)
Description
pp = pdearcl(p,xy,s,s0,s1) returns parameter values for a parametrized curve
corresponding to a given set of arc length values.
p is a monotone row vector of parameter values and xy is a matrix with two rows giving
the corresponding points on the curve.
The first point of the curve is given the arc length value s0 and the last point the value
s1.
On return, pp contains parameter values corresponding to the arc length values specified
in s.
The arc length values s, s0, and s1 can be an affine transformation of the arc length.
5-642
pdecgrad
pdecgrad
(Not recommended) Flux of PDE solution
Syntax
[cgxu,cgyu] = pdecgrad(p,t,c,u)
[cgxu,cgyu] = pdecgrad(p,t,c,u,time)
[cgxu,cgyu] = pdecgrad(p,t,c,u,time,sdl)
Description
[cgxu,cgyu] = pdecgrad(p,t,c,u) returns the flux, c ƒ — u , evaluated at the
center of each triangle.
N ∂u j ∂u j
 cij11 ∂x
+ cij 12
∂y
j =1
N ∂u j ∂u j
 cij 21 ∂x
+ cij 22
∂y
j =1
There is one column for each triangle in t in both cgxu and cgyu.
The gradient computed by pdegrad is actually the same everywhere in the triangle
interior because pdegrad uses only linear basis functions. The boundaries of triangles
5-643
5 Functions — Alphabetical List
are a special case: here the derivatives might be discontinuous. However, the flux c ƒ — u
can vary inside a triangle because the coefficient c can vary.
The geometry of the PDE problem is given by the mesh data p and t. Details on the mesh
data representation can be found in the entry on initmesh.
The coefficient c of the PDE problem can be given in a variety of ways. See “PDE
Coefficients”.
The scalar optional argument time is used for parabolic and hyperbolic problems, if c
depends on t, the time.
The optional argument sdl restricts the computation to the subdomains in the list sdl.
See Also
evaluateCGradient | evaluateGradient
5-644
pdecirc
pdecirc
Package: pde
Syntax
pdecirc(xc,yc,R)
pdecirc(xc,yc,R,label)
Description
pdecirc(xc,yc,R) draws a circle with the center at (xc,yc) and the radius R. The
pdecirc command opens the PDE Modeler app with the specified circle already drawn in
it. If the app is already open, pdecirc adds the specified circle to the app window
without deleting any existing shapes.
pdecirc updates the state of the geometry description matrix inside the PDE Modeler
app to include the circle. You can export the geometry description matrix from the PDE
Modeler app to the MATLAB Workspace by selecting DrawExport Geometry
Description, Set Formula, Labels.... For details on the format of the geometry
description matrix, see decsg.
Examples
Open the PDE Modeler app window containing a circle with the center at (0,0) and the
radius 1.
pdecirc(0,0,1)
5-645
5 Functions — Alphabetical List
Call the pdecirc command again to draw a circle with the center at (0,0.25) and the
radius 0.5. The pdecirc command adds the second circle to the app window without
deleting the first.
pdecirc(0,0.25,0.5)
5-646
pdecirc
5-647
5 Functions — Alphabetical List
Open the PDE Modeler app window containing a circle with the center at (0,0) and the
radius 1. Assign the name circle1 to this circle.
pdecirc(0,0,1,'circle1')
5-648
pdecirc
5-649
5 Functions — Alphabetical List
Input Arguments
xc — x-coordinate of center
real number
yc — y-coordinate of center
real number
R — Radius
positive number
label — Name
character vector | string scalar
Tips
pdecirc opens the PDE Modeler app and draws a circle. If, instead, you want to draw
circles in a MATLAB figure window, choose one of these approaches:
t = linspace(0,2*pi);
plot(cos(t),sin(t))
• Use the rectangle function with the Curvature name-value pair set to [1 1].
• Use the Image Processing Toolbox™ viscircles function.
5-650
pdecirc
See Also
PDE Modeler | pdeellip | pdepoly | pderect
5-651
5 Functions — Alphabetical List
pdecont
Shorthand command for contour plot
Note This page describes the legacy workflow. New features might not be compatible
with the legacy workflow.
Syntax
pdecont(p,t,u)
pdecont(p,t,u,n)
pdecont(p,t,u,v)
h = pdecont(p,t,u)
h = pdecont(p,t,u,n)
h = pdecont(p,t,u,v)
Description
pdecont(p,t,u) draws 10 level curves of the PDE node or triangle data u. h =
pdecont(p,t,u) additionally returns handles to the drawn axes objects.
The geometry of the PDE problem is given by the mesh data p and t. For details on the
mesh data representation, see “Mesh Data” on page 2-241.
5-652
pdecont
pdeplot(p,[],t,'XYData',u,'XYStyle','off','Contour',...
'on','Levels',n,'ColorBar','off');
If you want to have more control over your contour plot, use pdeplot instead of
pdecont.
Examples
Plot the contours of the solution to the equation over the geometry defined by
the L-shaped membrane. Use Dirichlet boundary conditions on .
[p,e,t] = initmesh('lshapeg');
[p,e,t] = refinemesh('lshapeg',p,e,t);
u = assempde('lshapeb',p,e,t,1,0,1);
pdecont(p,t,u)
5-653
5 Functions — Alphabetical List
See Also
pdemesh | pdeplot | pdesurf
5-654
pdeeig
pdeeig
(Not recommended) Solve eigenvalue PDE problem
Syntax
[v,l] = pdeeig(model,c,a,d,r)
[v,l] = pdeeig(b,p,e,t,c,a,d,r)
[v,l] = pdeeig(Kc,B,M,r)
Description
[v,l] = pdeeig(model,c,a,d,r) produces the solution to the FEM formulation of
the scalar PDE eigenvalue problem
-— ◊ ( c—u) + au = l du on W
-— ◊ (c ƒ —u) + au = l du on W
with geometry, boundary conditions, and mesh specified in model, a PDEModel object.
See “Solve Problems Using Legacy PDEModel Objects” on page 2-3.
The eigenvalue PDE problem is a homogeneous problem, i.e., only boundary conditions
where g = 0 and r = 0 can be used. The nonhomogeneous part is removed automatically.
Kc ui = λB´MBui
5-655
5 Functions — Alphabetical List
u = Bui
Examples
Compute the eigenvalues that are less than 100, and compute the corresponding
eigenmodes for on the geometry of the L-shaped membrane.
model = createpde;
geometryFromEdges(model,@lshapeg);
applyBoundaryCondition(model,'edge',1:model.Geometry.NumEdges,'u',0);
generateMesh(model,'GeometricOrder','linear','Hmax',0.02);
c = 1;
a = 0;
d = 1;
r = [-Inf 100];
[v,l] = pdeeig(model,c,a,d,r);
5-656
pdeeig
ans = 9.6506
Display the first eigenmode, and compare it to the built-in membrane plot.
pdeplot(model,'XYData',v(:,1),'ZData',v(:,1))
5-657
5 Functions — Alphabetical List
figure
membrane(1,20,9,9) % the MATLAB function
5-658
pdeeig
ans = 92.5248
figure
pdeplot(model,'XYData',v(:,16),'ZData',v(:,16)) % sixteenth eigenmode
5-659
5 Functions — Alphabetical List
Compute the eigenvalues that are less than 100, and compute the corresponding
eigenmodes for on the geometry of the L-shaped membrane, using the legacy
syntax.
Use the geometry in lshapeg. For more information about this syntax, see “Parametrized
Function for 2-D Geometry Creation” on page 2-17.
g = @lshapeg;
pdegplot(g,'EdgeLabels','on')
5-660
pdeeig
axis equal
ylim([-1.1,1.1])
Set zero Dirichlet boundary conditions using the lshapeb function. For more information
about this syntax, see “Boundary Conditions by Writing Functions” on page 2-204.
b = @lshapeb;
c = 1;
a = 0;
d = 1;
r = [-Inf 100];
5-661
5 Functions — Alphabetical List
5-662
pdeeig
l(1)
ans = 9.6481
Import a simple 3-D geometry and find eigenvalues and eigenvectors from the associated
finite element matrices.
model = createpde();
importGeometry(model,'BracketWithHole.stl');
figure
pdegplot(model,'FaceLabels','on')
view(30,30)
title('Bracket with Face Labels')
5-663
5 Functions — Alphabetical List
figure
pdegplot(model,'FaceLabels','on')
view(-134,-32)
title('Bracket with Face Labels, Rear View')
5-664
pdeeig
Set coefficients c = 1, a = 0, and d = 1. Collect eigenvalues that are less than 100.
c = 1;
a = 0;
d = 1;
r = [-Inf 100];
5-665
5 Functions — Alphabetical List
[v,l] = pdeeig(Kc,B,M,r);
l([1,2])
ans = 2×1
0.0000
42.8670
pdeplot3D(model,'ColorMapData',v(:,2))
5-666
pdeeig
Input Arguments
model — PDE model
PDEModel object
c — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
5-667
5 Functions — Alphabetical List
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. c represents the c coefficient in the scalar
PDE
-— ◊ ( c—u) + au = l du on W
-— ◊ (c ƒ —u) + au = l du on W
There are a wide variety of ways of specifying c, detailed in “c Coefficient for Systems” on
page 2-131. See also “Specify Scalar PDE Coefficients in Character Form” on page 2-76,
“Specify 2-D Scalar Coefficients in Function Form” on page 2-82, and “Specify 3-D PDE
Coefficients in Function Form” on page 2-85.
Example: 'cosh(x+y.^2)'
Data Types: double | char | string | function_handle
Complex Number Support: Yes
a — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. a represents the a coefficient in the scalar
PDE
-— ◊ ( c—u) + au = l du on W
-— ◊ (c ƒ —u) + au = l du on W
5-668
pdeeig
d — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. d represents the d coefficient in the scalar
PDE
-— ◊ ( c—u) + au = l du on W
-— ◊ (c ƒ —u) + au = l du on W
r — Eigenvalue range
two-element real vector
Eigenvalue range, specified as a two-element real vector. Real parts of eigenvalues λ fall
in the range r(1) ≤ λ ≤ r(2). r(1) can be -Inf. The algorithm returns all eigenvalues
in this interval in the l output, up to a maximum of 99 eigenvalues.
Example: [-Inf,100]
Data Types: double
b — Boundary conditions
boundary matrix | boundary file
Boundary conditions, specified as a boundary matrix or boundary file. Pass a boundary file
as a function handle or as a file name.
5-669
5 Functions — Alphabetical List
• A boundary matrix is generally an export from the PDE Modeler app. For details of the
structure of this matrix, see “Boundary Matrix for 2-D Geometry” on page 2-175.
• A boundary file is a file that you write in the syntax specified in “Boundary Conditions
by Writing Functions” on page 2-204.
p — Mesh points
matrix
Mesh points, specified as a 2-by-Np matrix of points, where Np is the number of points in
the mesh. For a description of the (p,e,t) matrices, see “Mesh Data” on page 2-241.
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
e — Mesh edges
matrix
Mesh edges, specified as a 7-by-Ne matrix of edges, where Ne is the number of edges in
the mesh. For a description of the (p,e,t) matrices, see “Mesh Data” on page 2-241.
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
t — Mesh triangles
matrix
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
5-670
pdeeig
Kc — Stiffness matrix
sparse matrix | full matrix
Stiffness matrix, specified as a sparse matrix or as a full matrix. See “Elliptic Equations”
on page 5-75. Typically, Kc is the output of assempde.
B — Dirichlet nullspace
sparse matrix
Dirichlet nullspace, returned as a sparse matrix. See “Algorithms” on page 5-75. Typically,
B is the output of assempde.
M — Mass matrix
sparse matrix | full matrix
Mass matrix. specified as a sparse matrix or a full matrix. See “Elliptic Equations” on
page 5-75.
To obtain the input matrices for pdeeig, hyperbolic or parabolic, run both assema
and assempde:
[Kc,Fc,B,ud] = assempde(model,c,a,f);
[~,M,~] = assema(model,0,d,f);
Note Create the M matrix using assema with d, not a, as the argument before f.
Output Arguments
v — Eigenvectors
matrix
5-671
5 Functions — Alphabetical List
Then v has size Np*N-by-ev. Each column of v corresponds to the eigenvectors of one
eigenvalue. In each column, the first Np elements correspond to the eigenvector of
equation 1 evaluated at the mesh nodes, the next Np elements correspond to equation 2,
etc.
l — Eigenvalues
vector
Eigenvalues, returned as a vector. The real parts of l are in the interval r. The real parts
of l are monotone increasing.
Limitations
In the standard case c and d are positive in the entire region. All eigenvalues are positive,
and 0 is a good choice for a lower bound of the interval. The cases where either c or d is
zero are discussed next.
• If d = 0 in a subregion, the mass matrix M becomes singular. This does not cause any
trouble, provided that c > 0 everywhere. The pencil (K,M) has a set of infinite
eigenvalues.
• If c = 0 in a subregion, the stiffness matrix K becomes singular, and the pencil (K,M)
has many zero eigenvalues. With an interval containing zero, pdeeig goes on for a
very long time to find all the zero eigenvalues. Choose a positive lower bound away
from zero but below the smallest nonzero eigenvalue.
• If there is a region where both c = 0 and d = 0, we get a singular pencil. The whole
eigenvalue problem is undetermined, and any value is equally plausible as an
eigenvalue.
5-672
pdeeig
Some of the awkward cases are detected by pdeeig. If the shifted matrix is singular,
another shift is attempted. If the matrix with the new shift is still singular a good guess is
that the entire pencil (K,M) is singular.
If you try any problem not belonging to the standard case, you must use your knowledge
of the original physical problem to interpret the results from the computation.
Tips
• The equation coefficients cannot depend on the solution u or its gradient.
Algorithms
Eigenvalue Equations
Partial Differential Equation Toolbox software handles the following basic eigenvalue
problem:
-— ◊ ( c—u ) + au = l du
The numerical solution is found by discretizing the equation and solving the resulting
algebraic eigenvalue problem. Let us first consider the discretization. Expand u in the
FEM basis, multiply with a basis element, and integrate on the domain Ω. This yields the
generalized eigenvalue equation
KU = λMU (5-20)
M i, j = Ú d(x )f j (x)fi(x) dx
W
The matrices K and M are produced by calling assema for the equations
5-673
5 Functions — Alphabetical List
In the most common case, when the function d(x) is positive, the mass matrix M is
positive definite symmetric. Likewise, when c(x) is positive and we have Dirichlet
boundary conditions, the stiffness matrix K is also positive definite.
The generalized eigenvalue problem, KU = λMU, is now solved by the Arnoldi algorithm
applied to a shifted and inverted matrix with restarts until all eigenvalues in the user-
specified interval have been found.
Let us describe how this is done in more detail. You may want to look at the examples
“Eigenvalues and Eigenmodes of the L-Shaped Membrane” on page 3-233 or
“Eigenvalues and Eigenmodes of a Square” on page 3-244, where actual runs are
reported.
First a shift µ is determined close to where we want to find the eigenvalues. When both K
and M are positive definite, it is natural to take µ = 0, and get the smallest eigenvalues; in
other cases take any point in the interval [lb,ub] where eigenvalues are sought. Subtract
µM from the eigenvalue equation and get (K - µM)U = (λ - µ)MU. Then multiply with the
inverse of this shifted matrix and get
1 -1
U = ( K - m M ) MU
l-m
This is a standard eigenvalue problem AU = θU, with the matrix A = (K – µM)-1M and
eigenvalues
1
qi =
li - m
The Arnoldi algorithm computes an orthonormal basis V where the shifted and inverted
operator A is represented by a Hessenberg matrix H,
(The subscripts mean that Vj and Ej have j columns and Hj,j has j rows and columns. When
no subscripts are used we deal with vectors and matrices of size n.)
5-674
pdeeig
Some of the eigenvalues of this Hessenberg matrix Hj,j eventually give good
approximations to the eigenvalues of the original pencil (K,M) when the basis grows in
dimension j, and less and less of the eigenvector is hidden in the residual matrix Ej.
The basis V is built one column vj at a time. The first vector v1 is chosen at random, as n
normally distributed random numbers. In step j, the first j vectors are already computed
and form the n ×j matrix Vj. The next vector vj+1 is computed by first letting A operate on
the newest vector vj, and then making the result orthogonal to all the previous vectors.
AV j = V j H j , j + v j +1 h j +1, j eTj
where Hj,j is a j×j Hessenberg matrix with the vectors hj as columns. The second term on
the right-hand side has nonzeros only in the last column; the earlier normalization factors
show up in the subdiagonal of Hj,j.
The eigensolution of the small Hessenberg matrix H gives approximations to some of the
eigenvalues and eigenvectors of the large matrix operator Aj,j in the following way.
Compute eigenvalues θi and eigenvectors si of Hj,j,
H j, j si = siqi , i = 1,..., j
This residual has to be small in norm for θi to be a good eigenvalue approximation. The
norm of the residual is
ri = h j +1, j s j ,i
the product of the last subdiagonal element of the Hessenberg matrix and the last
element of its eigenvector. It seldom happens that hj+1,j gets particularly small, but after
sufficiently many steps j there are always some eigenvectors si with small last elements.
The long vector Vj+1 is of unit norm.
5-675
5 Functions — Alphabetical List
It is not necessary to actually compute the eigenvector approximation yi to get the norm
of the residual; we only need to examine the short vectors si, and flag those with tiny last
components as converged. In a typical case n may be 2000, while j seldom exceeds 50, so
all computations that involve only matrices and vectors of size j are much cheaper than
those involving vectors of length n.
This eigenvalue computation and test for convergence is done every few steps j, until all
approximations to eigenvalues inside the interval [lb,ub] are flagged as converged. When
n is much larger than j, this is done very often, for smaller n more seldom. When all
eigenvalues inside the interval have converged, or when j has reached a prescribed
maximum, the converged eigenvectors, or more appropriately Schur vectors, are
computed and put in the front of the basis V.
After this, the Arnoldi algorithm is restarted with a random vector, if all approximations
inside the interval are flagged as converged, or else with the best unconverged
approximate eigenvector yi. In each step j of this second Arnoldi run, the vector is made
orthogonal to all vectors in V including the converged Schur vectors from the previous
runs. This way, the algorithm is applied to a projected matrix, and picks up a second copy
of any double eigenvalue there may be in the interval. If anything in the interval
converges during this second run, a third is attempted and so on, until no more
approximate eigenvalues θi show up inside. Then the algorithm signals convergence. If
there are still unconverged approximate eigenvalues after a prescribed maximum number
of steps, the algorithm signals nonconvergence and reports all solutions it has found.
This is a heuristic strategy that has worked well on both symmetric, nonsymmetric, and
even defective eigenvalue problems. There is a tiny theoretical chance of missing an
eigenvalue, if all the random starting vectors happen to be orthogonal to its eigenvector.
Normally, the algorithm restarts p times, if the maximum multiplicity of an eigenvalue is
p. At each restart a new random starting direction is introduced.
The shifted and inverted matrix A = (K – µM)–1M is needed only to operate on a vector vj
in the Arnoldi algorithm. This is done by computing an LU factorization,
using the sparse MATLAB command lu (P and Q are permutations that make the
triangular factors L and U sparse and the factorization numerically stable). This
factorization needs to be done only once, in the beginning, then x = Avj is computed as,
x = QU–1L–1PMvj (5-24)
5-676
pdeeig
with one sparse matrix vector multiplication, a permutation, sparse forward- and back-
substitutions, and a final renumbering.
See Also
solvepdeeig
5-677
5 Functions — Alphabetical List
pdeellip
Package: pde
Syntax
pdeellip(xc,yc,a,b,phi)
pdeellip(xc,yc,a,b,phi,label)
Description
pdeellip(xc,yc,a,b,phi) draws an ellipse with the center at (xc,yc), the semiaxes a
and b, and the rotation phi (in radians). The pdeellip command opens the PDE Modeler
app with the specified ellipse drawn in it. If the app is already open, pdeellip adds the
specified ellipse to the app window without deleting any existing shapes.
pdeellip updates the state of the geometry description matrix inside the PDE Modeler
app to include the ellipse. You can export the geometry description matrix from the PDE
Modeler app to the MATLAB Workspace by selecting DrawExport Geometry
Description, Set Formula, Labels.... For details on the format of the geometry
description matrix, see decsg.
Examples
Open the PDE Modeler app window containing an ellipse with the center at (0,0) and the
semiaxes 1 and 0.3. Rotate the ellipse by counterclockwise.
5-678
pdeellip
pdeellip(0,0,1,0.3,pi/4)
Call the pdeellip command again to draw an ellipse with the same center and semiaxes,
but rotate it by counterclockwise. The pdeellip command adds the second ellipse
to the app window without deleting the first.
pdeellip(0,0,1,0.3,pi/2)
5-679
5 Functions — Alphabetical List
5-680
pdeellip
Open the PDE Modeler app window containing an ellipse with the center at (0,0) and the
semiaxes 1 and 0.3. Rotate the ellipse by counterclockwise. Assign the name
ellipse1 to this ellipse.
pdeellip(0,0,1,0.3,pi/4,'ellipse1')
5-681
5 Functions — Alphabetical List
5-682
pdeellip
Input Arguments
xc — x-coordinate of center
real number
yc — y-coordinate of center
real number
a — Semiaxis
positive number
b — Semiaxis
positive number
phi — Rotation
real number
Rotation of the ellipse, specified as a real number. The rotation value is measured in
radians.
Data Types: double
label — Name
character vector | string scalar
5-683
5 Functions — Alphabetical List
See Also
PDE Modeler | pdecirc | pdepoly | pderect
5-684
pdeent
pdeent
Indices of triangles neighboring given set of triangles
Note This page describes the legacy workflow. New features might not be compatible
with the legacy workflow. For the corresponding step in the recommended workflow, see
generateMesh.
Syntax
ntl = pdeent(t,tl)
Description
Given triangle data t and a list of triangle indices tl, ntl contains indices of the
triangles in tl and their immediate neighbors, i.e., those whose intersection with tl is
nonempty.
See Also
generateMesh
5-685
5 Functions — Alphabetical List
pdegplot
Plot PDE geometry
Syntax
pdegplot(g)
pdegplot(g,Name,Value)
h = pdegplot( ___ )
Description
pdegplot(g) plots the geometry of a PDE problem, as described in g.
h = pdegplot( ___ ) returns handles to the graphics, using any of the previous
syntaxes.
Examples
g = [2 1 1 1 1 1 1 1 1 4 4;
-1 -0.6 -0.5 -0.4 -0.5 0.4 0.5 0.6 0.5 -1 0.17;
1 -0.5 -0.4 -0.5 -0.6 0.5 0.6 0.5 0.4 0.17 1;
0 -0.25 -0.35 -0.25 -0.15 -0.25 -0.35 -0.25 -0.15 0 -0.74;
0 -0.35 -0.25 -0.15 -0.25 -0.35 -0.25 -0.15 -0.25 -0.74 0;
0 0 0 0 0 0 0 0 0 1 1;
1 1 1 1 1 1 1 1 1 0 0;
0 -0.5 -0.5 -0.5 -0.5 0.5 0.5 0.5 0.5 0 0;
0 -0.25 -0.25 -0.25 -0.25 -0.25 -0.25 -0.25 -0.25 0 0;
5-686
pdegplot
View the vertex labels, edge labels, and the face label. Add space at the top of the plot to
see the top edge clearly.
pdegplot(g,'VertexLabels','on','EdgeLabels','on','FaceLabels','on')
ylim([-.8,.1])
5-687
5 Functions — Alphabetical List
Import a 3-D geometry file. Plot the geometry and turn on face labels. To see the labels on
all faces of the geometry, set the transparency to 0.5.
model = createpde;
importGeometry(model,'BracketWithHole.stl');
pdegplot(model,'FaceLabels','on','FaceAlpha',0.5)
5-688
pdegplot
Import a 3-D geometry file. Plot the geometry and turn on cell labels.
model = createpde;
importGeometry(model,'DampingMounts.stl');
pdegplot(model,'CellLabels','on')
5-689
5 Functions — Alphabetical List
Input Arguments
g — Geometry description
PDEModel object | output of decsg | decomposed geometry matrix | name of geometry
file | function handle to geometry file
• PDEModel object
• Output of decsg
5-690
pdegplot
The argument SubdomainLabels is not recommended. Use FaceLabels for both 2-D
and 3-D geometries instead.
Example: pdegplot(g,'FaceLabels','on')
Boundary edge labels for 2-D or 3-D geometry, specified as 'off' or 'on'.
Example: 'EdgeLabels','on'
Data Types: char | string
Boundary face labels for 2-D or 3-D geometry, specified as 'off' or 'on'.
5-691
5 Functions — Alphabetical List
Example: 'FaceLabels','on'
Data Types: char | string
Surface transparency for 3-D geometry, specified as the comma-separated pair consisting
of 'FaceAlpha' and a real number from 0 through 1. The default value 1 indicates no
transparency. The value 0 indicates complete transparency.
Example: 'FaceAlpha',0.5
Data Types: double
Output Arguments
h — Handles to graphics objects
vector
Alternative Functionality
App
If you create 2-D geometry in the PDE Modeler app, you can view the geometry from
Boundary Mode. To see the edge labels, select Boundary > Show Edge Labels. To see
the face labels, select PDE > Show Subdomain Labels.
5-692
pdegplot
See Also
PDE Modeler | decsg | importGeometry | wgeom
Topics
“Solve PDE with Coefficients in Functional Form” on page 2-87
“Create Geometry and Remove Face Boundaries” on page 2-13
“STL File Import” on page 2-47
“Three Ways to Create 2-D Geometry” on page 2-8
“Solve Problems Using PDEModel Objects” on page 2-6
5-693
5 Functions — Alphabetical List
pdegrad
(Not recommended) Gradient of PDE solution
Syntax
[ux,uy] = pdegrad(p,t,u)
[ux,uy] = pdegrad(p,t,u,sdl)
Description
[ux,uy] = pdegrad(p,t,u) returns the gradient of u evaluated at the center of each
triangle.
∂ ui
∂x
∂ ui
∂y
Although pdegrad returns the value of the gradient at the center of a triangle, the
gradient is actually the same everywhere in the triangle interior. This is because pdegrad
uses only linear basis functions. The boundaries of triangles are a special case: here the
derivatives might be discontinuous.
The geometry of the PDE problem is given by the mesh data p and t. For details on the
mesh data representation, see initmesh.
5-694
pdegrad
The optional argument sdl restricts the computation to the subdomains in the list sdl.
See Also
evaluateGradient
5-695
5 Functions — Alphabetical List
pdeInterpolant
Interpolant for nodal data to selected locations
Description
An interpolant allows you to evaluate a PDE solution at any point within the geometry.
Partial Differential Equation Toolbox solvers return solution values at the nodes, meaning
the mesh points. To evaluate an interpolated solution at other points within the geometry,
create a pdeInterpolant object, and then call the evaluate function.
Creation
Syntax
F = pdeInterpolant(p,t,u)
Description
F = pdeInterpolant(p,t,u) returns an interpolant F based on the data points p,
elements t, and data values at the points, u.
Use meshToPet to obtain the p and t data for interpolation using pdeInterpolant.
Input Arguments
p — Data point locations
matrix with two or three rows
5-696
pdeInterpolant
Data point locations, specified as a matrix with two or three rows. Each column of p is a
2-D or 3-D point. For details, see “Mesh Data” on page 2-241.
For 2-D problems, construct p using the initmesh function, or export from the Mesh
menu of the PDE Modeler app. For 2-D or 3-D geometry using a PDEModel object, obtain
p using the meshToPet function on model.Mesh. For example, [p,e,t] =
initmesh(g) or [p,e,t] = meshToPet(model.Mesh).
t — Triangulation elements
matrix
Triangulation elements, specified as a matrix. For details, see “Mesh Data” on page 2-241.
For 2-D problems, construct t using the initmesh function, or export from the Mesh
menu of the PDE Modeler app. For 2-D or 3-D geometry using a PDEModel object, obtain
t using the meshToPet function on model.Mesh. For example, [p,e,t] =
initmesh(g) or [p,e,t] = meshToPet(model.Mesh).
The dimensions of the matrix u depend on the problem. If np is the number of columns of
p, and N is the number of equations in the PDE system, then u has N*np rows. The first np
rows correspond to equation 1, the next np rows correspond to equation 2, etc. For
parabolic or hyperbolic problems, u has one column for each solution time; otherwise, u is
a column vector.
Object Functions
evaluate Interpolate data to selected locations
Examples
5-697
5 Functions — Alphabetical List
Create Interpolant
This example shows how to create a pdeInterpolant from the solution to a scalar PDE.
Solve the equation on the unit disk with zero Dirichlet conditions.
F = pdeInterpolant(p,t,u);
pOut = [0,1/2,1/2,0;
0,0,1/2,1/2];
uOut = evaluate(F,pOut)
uOut = 4×1
0.2485
0.1854
0.1230
0.1852
The values uOut(2) and uOut(4) are nearly equal, as they should be for symmetric
points in this symmetric problem.
See Also
evaluate | tri2grid
5-698
pdeInterpolant
Topics
“Mesh Data” on page 2-241
Introduced in R2014b
5-699
5 Functions — Alphabetical List
pdeintrp
(Not recommended) Interpolate from node data to triangle midpoint data
Syntax
ut = pdeintrp(p,t,un)
Description
ut = pdeintrp(p,t,un) gives linearly interpolated values at triangle midpoints from
the values at node points.
The geometry of the PDE problem is given by the mesh data p and t. For details on the
mesh data representation, see initmesh.
Let N be the dimension of the PDE system, np the number of node points, and nt the
number of triangles. The components of the node data are stored in un either as N
columns of length np or as an ordinary solution vector. The first np values of un describe
the first component, the following np values of un describe the second component, and so
on. The components of triangle data are stored in ut as N rows of length nt.
Caution
pdeprtni and pdeintrp are not inverse functions. The interpolation introduces some
averaging.
See Also
evaluateGradient | interpolateSolution | solvepde
5-700
pdeintrp
5-701
5 Functions — Alphabetical List
pdejmps
(Not recommended) Error estimates for adaptation
Syntax
errf = pdejmps(p,t,c,a,f,u,alfa,beta,m)
Description
errf = pdejmps(p,t,c,a,f,u,alfa,beta,m) calculates the error indication
function used for adaptation. The columns of errf correspond to triangles, and the rows
correspond to the different equations in the PDE system.
The formula for computing the error indicator E(K) for each triangle K is
1/2
Ê1 ˆ
E ( K ) = a h m ( f - au) K
+b Á
2
 ht2m [ nt ◊ ( c— uh )]2 ˜
Ë t Œ∂K ¯
where nt is the unit normal of edge t and the braced term is the jump in flux across the
element edge, where α and β are weight indices and m is an order parameter. The norm is
an L2 norm computed over the element K. The error indicator is stored in errf as column
vectors, one for each triangle in t. For more details, see the "Algorithms" section on the
adaptmesh page.
5-702
pdemesh
pdemesh
Plot PDE mesh
Syntax
pdemesh(model)
pdemesh(mesh)
pdemesh(nodes,elements)
pdemesh(model,u)
pdemesh( ___ ,Name,Value)
pdemesh(p,e,t)
pdemesh(p,e,t,u)
h = pdemesh( ___ )
Description
pdemesh(model) plots the mesh contained in a 2-D or 3-D model object of type
PDEModel.
pdemesh(mesh) plots the mesh defined as a Mesh property of a 2-D or 3-D model object
of type PDEModel.
pdemesh(model,u) plots solution data u as a 3-D plot. This syntax is valid only for 2-D
geometry.
pdemesh( ___ ,Name,Value) plots the mesh or solution data using any of the
arguments in the previous syntaxes and one or more Name,Value pair arguments.
pdemesh(p,e,t,u) plots PDE node or triangle data u using a mesh plot. The function
plots the node data if u is a column vector , and triangle data if u is a row vector.
5-703
5 Functions — Alphabetical List
If you want to have more control over your mesh plot, use pdeplot or pdeplot3D
instead of pdemesh.
h = pdemesh( ___ ) returns handles to the graphics, using any of the arguments of the
previous syntaxes.
Examples
Create a mesh plot and display the node and element labels of the mesh.
Create a PDE model. Include the geometry of the built-in function lshapeg. Mesh the
geometry.
model = createpde;
geometryFromEdges(model,@lshapeg);
mesh = generateMesh(model);
pdemesh(model)
5-704
pdemesh
pdemesh(mesh)
5-705
5 Functions — Alphabetical List
Another approach is to use the nodes and elements of the mesh as input arguments for
pdemesh.
pdemesh(mesh.Nodes,mesh.Elements)
5-706
pdemesh
pdemesh(model,'NodeLabels','on')
5-707
5 Functions — Alphabetical List
xlim([-0.4,0.4])
ylim([-0.4,0.4])
5-708
pdemesh
pdemesh(model,'ElementLabels','on')
xlim([-0.4,0.4])
ylim([-0.4,0.4])
5-709
5 Functions — Alphabetical List
applyBoundaryCondition(model,'dirichlet','Edge',1:model.Geometry.NumEdges,'u',0);
specifyCoefficients(model,'m',0,...
'd',0,...
'c',1,...
'a',0,...
'f',1);
generateMesh(model);
results = solvepde(model)
results =
StationaryResults with properties:
5-710
pdemesh
u = results.NodalSolution;
The pdemesh function ignores NodeLabels and ElementLabels when you plot solution
data as a 3-D plot.
5-711
5 Functions — Alphabetical List
5-712
pdemesh
model = createpde;
Include the geometry of the built-in function lshapeg. Plot the geometry.
geometryFromEdges(model,@lshapeg);
pdegplot(model,'FaceLabels','on','EdgeLabels','on')
5-713
5 Functions — Alphabetical List
Generate a mesh.
mesh = generateMesh(model,'Hmax',0.5);
5-714
pdemesh
[p,e,t] = initmesh('lshapeg');
[p,e,t] = refinemesh('lshapeg',p,e,t);
pdemesh(p,e,t)
Now solve Poisson's equation over the geometry defined by the L-shaped
membrane. Use Dirichlet boundary conditions on , and plot the result.
5-715
5 Functions — Alphabetical List
u = assempde('lshapeb',p,e,t,1,0,1);
pdemesh(p,e,t,u)
Input Arguments
model — PDE model
PDEModel object
5-716
pdemesh
u — PDE solution
vector | matrix
Mesh object, specified as the Mesh property of a PDEModel object or as the output of
generateMesh.
Example: model.Mesh
Nodal coordinates, specified as a 2-by-NumNodes matrix for a 2-D mesh and 3-by-
NumNodes matrix for a 3-D mesh. NumNodes is the number of nodes.
5-717
5 Functions — Alphabetical List
p — Mesh points
matrix
5-718
pdemesh
Mesh points, specified as a 2-by-Np matrix of points, where Np is the number of points in
the mesh. For a description of the (p,e,t) matrices, see “Mesh Data” on page 2-241.
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
e — Mesh edges
matrix
Mesh edges, specified as a 7-by-Ne matrix of edges, where Ne is the number of edges in
the mesh. For a description of the (p,e,t) matrices, see “Mesh Data” on page 2-241.
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
t — Mesh triangles
matrix
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
5-719
5 Functions — Alphabetical List
pdemesh ignores NodeLabels when you plot solution data as a 3-D plot.
Example: 'NodeLabels','on'
Data Types: char | string
pdemesh ignores ElementLabels when you plot solution data as a 3-D plot.
Example: 'ElementLabels','on'
Data Types: char | string
Surface transparency for 3-D geometry, specified as the comma-separated pair consisting
of 'FaceAlpha' and a real number from 0 through 1. The default value 1 indicates no
transparency. The value 0 indicates complete transparency.
Example: 'FaceAlpha',0.5
Data Types: double
Color of mesh edges, specified as a short or long color name or an RGB triplet. By default,
for 2-D meshes the edges within one face are blue (RGB triplet [0 0 1]) and the edges
between faces are red (RGB triplet [1 0 0]). For 3-D meshes, the default edge color is
black (RGB triplet [0 0 0]).
The short names and long names are character vectors that specify one of eight
predefined colors. The RGB triplet is a three-element row vector whose elements specify
5-720
pdemesh
the intensities of the red, green, and blue components of the color; the intensities must be
in the range [0 1]. The following table lists the predefined colors and their RGB triplet
equivalents.
Example: 'EdgeColor','green'
Data Types: double | char | string
Color of mesh faces for 3-D meshes, specified as a short or long color name or an RGB
triplet. The default face color is cyan (RGB triplet [0 1 1]). For details about available
colors, see “'EdgeColor'” on page 5-0 .
Example: 'FaceColor','green'
Data Types: double | char | string
Output Arguments
h — Handles to graphics objects
vector
5-721
5 Functions — Alphabetical List
See Also
pdegplot | pdeplot | pdeplot3D | pdesurf
Topics
“Mesh Data” on page 2-241
5-722
PDEModel
PDEModel
PDE model object
Description
A PDEModel object contains information about a PDE problem: the number of equations,
geometry, mesh, and boundary conditions.
Creation
Create a PDEModel object using createpde. Initially, the only nonempty property is
PDESystemSize. It is 1 for scalar problems.
Properties
PDESystemSize — Number of equations
1 (default) | positive integer
Number of equations, N, returned as a positive integer. See “Equations You Can Solve
Using PDE Toolbox” on page 1-6.
Example: 1
Data Types: double
5-723
5 Functions — Alphabetical List
• AnalyticGeometry object for 2-D geometry. You create this geometry using the
geometryFromEdges function.
• DiscreteGeometry object for 3-D geometry. You create this geometry using the
importGeometry function or the geometryFromMesh function.
Mesh for solution, returned as an FEMesh object. You create the mesh using the
generateMesh function.
In case of NodalInitialConditions, you use the results of previous analysis to set the
initial conditions or initial guess. The geometry and mesh of the previous analysis and
current model must be the same.
5-724
PDEModel
Algorithm options for the PDE solvers, returned as a PDESolverOptions object. The
properties of PDESolverOptions include absolute and relative tolerances for internal
ODE solvers, maximum solver iterations, and so on.
Object Functions
applyBoundaryCondition Add boundary condition to PDEModel container
generateMesh Create triangular or tetrahedral mesh
geometryFromEdges Create 2-D geometry
geometryFromMesh Create geometry from mesh
importGeometry Import geometry from STL data
setInitialConditions Give initial conditions or initial solution
specifyCoefficients Specify coefficients in a PDE model
solvepde Solve PDE specified in a PDEModel
solvepdeeig Solve PDE eigenvalue problem specified in a PDEModel
Examples
model = createpde()
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
5-725
5 Functions — Alphabetical List
Include a torus geometry, zero Dirichlet boundary conditions, coefficients for Poisson's
equation, and the default mesh.
importGeometry(model,'Torus.stl');
applyBoundaryCondition(model,'dirichlet','face',1,'u',0);
specifyCoefficients(model,'m',0,...
'd',0,...
'c',1,...
'a',0,...
'f',1);
generateMesh(model);
results = solvepde(model)
results =
StationaryResults with properties:
See Also
applyBoundaryCondition | createpde | generateMesh | geometryFromEdges |
geometryFromMesh | importGeometry | pdegplot | pdeplot | pdeplot3D |
setInitialConditions | specifyCoefficients
Topics
“Solve Problems Using PDEModel Objects” on page 2-6
Introduced in R2015a
5-726
pdenonlin
pdenonlin
(Not recommended) Solve nonlinear elliptic PDE problem
Syntax
u = pdenonlin(model,c,a,f)
u = pdenonlin(b,p,e,t,c,a,f)
u = pdenonlin( ___ ,Name,Value)
[u,res] = pdenonlin( ___ )
Description
u = pdenonlin(model,c,a,f) solves the nonlinear PDE
-— ◊ ( c—u ) + au = f
with geometry, boundary conditions, and finite element mesh in model, and coefficients c,
a, and f. In this context, “nonlinear” means some coefficient in c, a, or f depends on the
solution u or its gradient. If the PDE is a system of equations
(model.PDESystemSize > 1), then pdenonlin solves the system of equations
-— ◊ ( c ƒ — u ) + au = f
u = pdenonlin( ___ ,Name,Value), for any previous arguments, modifies the solution
process with Name, Value pairs.
[u,res] = pdenonlin( ___ ) also returns the norm of the Newton step residuals res.
5-727
5 Functions — Alphabetical List
Examples
Solve a minimal surface problem. Because this problem has a nonlinear c coefficient, use
pdenonlin to solve it.
Create a model and include circular geometry using the built-in circleg function.
model = createpde;
geometryFromEdges(model,@circleg);
a = 0;
f = 0;
c = '1./sqrt(1+ux.^2+uy.^2)';
boundaryfun = @(region,state)region.x.^2;
applyBoundaryCondition(model,'edge',1:model.Geometry.NumEdges,...
'u',boundaryfun,'Vectorized','on');
generateMesh(model,'GeometricOrder','linear','Hmax',0.1);
u = pdenonlin(model,c,a,f);
pdeplot(model,'XYData',u,'ZData',u)
5-728
pdenonlin
Solve the minimal surface problem using the legacy approach for creating boundary
conditions and geometry.
Create the geometry using the built-in circleg function. Plot the geometry to see the
edge labels.
g = @circleg;
pdegplot(g,'EdgeLabels','on')
axis equal
5-729
5 Functions — Alphabetical List
Create Dirichlet boundary conditions with value .Create the following file and save it on
your Matlab™ path. For details of this approach, see “Boundary Conditions by Writing
Functions” on page 2-204.
for k = 1:ne
x1 = p(1,e(1,k)); % x at first point in segment
5-730
pdenonlin
a = 0;
f = 0;
c = '1./sqrt(1+ux.^2+uy.^2)';
b = @pdex2bound;
[p,e,t] = initmesh(g,'Hmax',0.1);
u = pdenonlin(b,p,e,t,c,a,f);
pdeplot(p,e,t,'XYData',u,'ZData',u)
5-731
5 Functions — Alphabetical List
Import the geometry from the BracketWithHole.stl file. Plot the geometry and face
labels.
model = createpde();
importGeometry(model,'BracketWithHole.stl');
figure
pdegplot(model,'FaceLabels','on')
5-732
pdenonlin
view(30,30)
title('Bracket with Face Labels')
figure
pdegplot(model,'FaceLabels','on')
view(-134,-32)
title('Bracket with Face Labels, Rear View')
5-733
5 Functions — Alphabetical List
Set a Dirichlet boundary condition with value 1000 on the back face, which is face 4. Set
the large faces 1 and 7, and also the circular face 11, to have Neumann boundary
conditions with value g = -10. Do not set boundary conditions on the other faces. Those
faces default to Neumann boundary conditions with value g = 0.
applyBoundaryCondition(model,'Face',4,'u',1000);
applyBoundaryCondition(model,'Face',[1,7,11],'g',-10);
Set the c coefficient to 1, f to 0.1, and a to the nonlinear value '0.1 + 0.001*u.^2'.
c = 1;
f = 0.1;
a = '0.1 + 0.001*u.^2';
5-734
pdenonlin
Generate the mesh and solve the PDE. Start from the initial guess u0 = 1000, which
matches the value you set on face 4. Turn on the Report option to observe the
convergence during the solution.
generateMesh(model);
u = pdenonlin(model,c,a,f,'U0',1000,'Report','on');
pdeplot3D(model,'ColorMapData',u)
5-735
5 Functions — Alphabetical List
Input Arguments
model — PDE model
PDEModel object
c — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
5-736
pdenonlin
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. c represents the c coefficient in the scalar
PDE
-— ◊ ( c—u ) + au = f
-— ◊ ( c ƒ — u ) + au = f
You can specifyc in various ways, detailed in “c Coefficient for Systems” on page 2-131.
See also “Specify Scalar PDE Coefficients in Character Form” on page 2-76, “Specify 2-D
Scalar Coefficients in Function Form” on page 2-82, and “Specify 3-D PDE Coefficients in
Function Form” on page 2-85.
Example: 'cosh(x+y.^2)'
Data Types: double | char | string | function_handle
Complex Number Support: Yes
a — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. a represents the a coefficient in the scalar
PDE
-— ◊ ( c—u ) + au = f
-— ◊ ( c ƒ — u ) + au = f
You can specifya in various ways, detailed in “a or d Coefficient for Systems” on page 2-
154. See also “Specify Scalar PDE Coefficients in Character Form” on page 2-76, “Specify
2-D Scalar Coefficients in Function Form” on page 2-82, and “Specify 3-D PDE
Coefficients in Function Form” on page 2-85.
Example: 2*eye(3)
Data Types: double | char | string | function_handle
5-737
5 Functions — Alphabetical List
f — PDE coefficient
scalar | matrix | character vector | character array | string scalar | string vector |
coefficient function
PDE coefficient, specified as a scalar, matrix, character vector, character array, string
scalar, string vector, or coefficient function. f represents the f coefficient in the scalar
PDE
-— ◊ ( c—u ) + au = f
-— ◊ ( c ƒ — u ) + au = f
You can specifyf in various ways, detailed in “f Coefficient for Systems” on page 2-104.
See also “Specify Scalar PDE Coefficients in Character Form” on page 2-76, “Specify 2-D
Scalar Coefficients in Function Form” on page 2-82, and “Specify 3-D PDE Coefficients in
Function Form” on page 2-85.
Example: char('sin(x)';'cos(y)';'tan(z)')
Data Types: double | char | string | function_handle
Complex Number Support: Yes
b — Boundary conditions
boundary matrix | boundary file
Boundary conditions, specified as a boundary matrix or boundary file. Pass a boundary file
as a function handle or as a file name.
• A boundary matrix is generally an export from the PDE Modeler app. For details of the
structure of this matrix, see “Boundary Matrix for 2-D Geometry” on page 2-175.
• A boundary file is a file that you write in the syntax specified in “Boundary Conditions
by Writing Functions” on page 2-204.
p — Mesh points
matrix
5-738
pdenonlin
Mesh points, specified as a 2-by-Np matrix of points, where Np is the number of points in
the mesh. For a description of the (p,e,t) matrices, see “Mesh Data” on page 2-241.
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
e — Mesh edges
matrix
Mesh edges, specified as a 7-by-Ne matrix of edges, where Ne is the number of edges in
the mesh. For a description of the (p,e,t) matrices, see “Mesh Data” on page 2-241.
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
t — Mesh triangles
matrix
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
5-739
5 Functions — Alphabetical List
• 'full' means numerical evaluation of the full Jacobian based on the sparse version of
the numjac function. 3-D geometry uses only 'full', any other specification yields
an error.
• 'fixed' specifies a fixed-point iteration matrix where the Jacobian is approximated
by the stiffness matrix. This is the 2-D geometry default.
• 'lumped' specifies a “lumped” approximation as described in “Nonlinear Equations”
on page 5-743. This approximation is based on the numerical differentiation of the
coefficients.
Example: u = pdenonlin(model,c,a,f,'Jacobian','full')
Data Types: char | string
• A scalar specifies a constant initial condition for either a scalar or PDE system.
• For scalar problems, use the same syntax as “Specify Scalar PDE Coefficients in
Character Form” on page 2-76.
• For systems of N equations, write a character array with N rows, where each row has
the syntax of “Specify Scalar PDE Coefficients in Character Form” on page 2-76.
• For systems of N equations, and a mesh with Np nodes, give a column vector with
N*Np components. The nodes are either model.Mesh.Nodes, or the p data from
initmesh or meshToPet. See “Mesh Data” on page 2-241.
The first Np elements contain the values of component 1, where the value of element k
corresponds to node p(k). The next Np points contain the values of component 2, etc.
It can be convenient to first represent the initial conditions u0 as an Np-by-N matrix,
where the first column contains entries for component 1, the second column contains
entries for component 2, etc. The final representation of the initial conditions is
u0(:).
Example: u = pdenonlin(model,c,a,f,'U0','x.^2-y.^2')
5-740
pdenonlin
Residual size at termination, specified as a positive scalar. pdenonlin iterates until the
residual size is less than 'Tol'.
Example: u = pdenonlin(model,c,a,f,'Tol',1e-6)
Data Types: double
Residual norm, specified as the p value for Lp norm, or as 'energy'. p can be any
positive real value, Inf, or -Inf. The p norm of a vector v is sum(abs(v)^p)^(1/p).
See norm.
5-741
5 Functions — Alphabetical List
Example: u = pdenonlin(model,c,a,f,'Norm',2)
Data Types: double | char | string
Output Arguments
u — PDE solution
vector
• If the PDE is scalar, meaning only one equation, then u is a column vector
representing the solution u at each node in the mesh. u(i) is the solution at the ith
column of model.Mesh.Nodes or the ith column of p.
• If the PDE is a system of N > 1 equations, then u is a column vector with N*Np
elements, where Np is the number of nodes in the mesh. The first Np elements of u
represent the solution of equation 1, then next Np elements represent the solution of
equation 2, etc.
To plot the solution, use pdeplot for 2-D geometry, or see “Plot 3-D Solutions and Their
Gradients” on page 3-277.
Norm of Newton step residuals, returned as a scalar. For information about the algorithm,
see “Nonlinear Equations” on page 5-743.
Tips
• If the Newton iteration does not converge, pdenonlin displays the error message Too
many iterations or Stepsize too small.
• If the initial guess produces matrices containing NaN or Inf elements, pdenonlin
displays the error message Unsuitable initial guess U0 (default: U0 =
0).
• If you have very small coefficients, or very small geometric dimensions, pdenonlin
can fail to converge, or can converge to an incorrect solution. If so, you can sometimes
5-742
pdenonlin
Algorithms
Nonlinear Equations
The basic idea is to use Gauss-Newton iterations to solve the nonlinear equations. Say you
are trying to solve the equation
In the FEM setting you solve the weak form of r(u) = 0. Set as usual
u(x) = ÂU jf j
where x represents a 2-D or 3-D point. Then multiply the equation by an arbitrary test
function ϕi, integrate on the domain Ω, and use Green's formula and the boundary
conditions to obtain
where the matrices K, M, Q and the vectors F and G are produced by assembling the
problem
5-743
5 Functions — Alphabetical List
Assume that you have a guess U(n) of the solution. If U(n) is close enough to the exact
solution, an improved approximation U(n+1) is obtained by solving the linearized problem
∂ r (U ( n) ) ( ( n +1)
U - U ( n ) ) = -ar (U ( n ) )
∂U
where a is a positive number. (It is not necessary that ρ(U) = 0 have a solution even if
ρ(u) = 0 has.) In this case, the Gauss-Newton iteration tends to be the minimizer of the
r (U ( n +1) ) < r ( U ( n) )
and
-1
Ê ∂ r (U ( n) ) ˆ
pn = Á ˜ r ( U ( n) )
Ë ∂U ¯
is called a descent direction for r (U) , where ◊ is the L2-norm. The iteration is
U ( n +1) = U ( n ) + a pn ,
where a ≤ 1 is chosen as large as possible such that the step has a reasonable descent.
The Gauss-Newton method is local, and convergence is assured only when U(0) is close
enough to the solution. In general, the first guess may be outside the region of
convergence. To improve convergence from bad initial guesses, a damping strategy is
implemented for choosing α, the Armijo-Goldstein line search. It chooses the largest
damping coefficient α out of the sequence 1, 1/2, 1/4, . . . such that the following
inequality holds:
a ( (n) )
r (U ( n) ) - r (U ( n) ) + a pn ≥ r U
2
5-744
pdenonlin
which guarantees a reduction of the residual norm by at least 1 – a /2. Each step of the
(
line-search algorithm requires an evaluation of the residual r U ( n) + a pn .)
An important point of this strategy is that when U(n) approaches the solution, then a →1
and thus the convergence rate increases. If there is a solution to ρ(U) = 0, the scheme
ultimately recovers the quadratic convergence rate of the standard Newton iteration.
Closely related to the preceding problem is the choice of the initial guess U(0). By default,
the solver sets U(0) and then assembles the FEM matrices K and F and computes
The damped Gauss-Newton iteration is then started with U(1), which should be a better
guess than U(0). If the boundary conditions do not depend on the solution u, then U(1)
satisfies them even if U(0) does not. Furthermore, if the equation is linear, then U(1) is the
exact FEM solution and the solver does not enter the Gauss-Newton loop.
In some situations you may already have a good approximation and the nonlinear solver
can be started with it, avoiding the slow convergence regime. This idea is used in the
adaptive mesh generator. It computes a solution U% on a mesh, evaluates the error, and
may refine certain triangles. The interpolant of U% is a very good starting guess for the
solution on the refined mesh.
∂ r ( U ( n) )
Jn =
∂U
r U ( n) + efi - r (U ( n ) )
( )
e
5-745
5 Functions — Alphabetical List
which implies the assembling of the FEM matrices for the triangles containing grid point
i. A very simple approximation to Jn, which gives a fixed point iteration, is also possible as
follows. Essentially, for a given U(n), compute the FEM matrices K and F and set
U(n+1) = K–1F . (5-29)
This is equivalent to approximating the Jacobian with the stiffness matrix. Indeed, since
ρ(U(n)) = KU(n) – F, putting Jn = K yields
U ( n +1) = U ( n ) - J n-1 r ( U ( n) ) = U ( n) - K -1 ( KU ( n) - F ) = K -1 F
In many cases the convergence rate is slow, but the cost of each iteration is cheap.
The Partial Differential Equation Toolbox nonlinear solver also provides for a compromise
between the two extremes. To compute the derivative of the mapping U→KU, proceed as
follows. The a term has been omitted for clarity, but appears again in the final result.
∂ ( KU ) i 1
∂U j
= lim
e Æ0 e
 ÊÁ Ú c (U + ef j ) —fl—fi dx (Ul + edl, j )
l ËW
- Ú c (U ) —fl—fi dxUl ˆ˜
W ¯
∂c
= Ú c (U ) —f j —fi dx + Â Ú fj —f — f dxUl
∂u l i
W l W
The second term is “lumped,” i.e., replaced by a diagonal matrix that contains the row
sums. Since Σjϕj = 1, the second term is approximated by
∂c
d i, j Â Ú — fl — fi dx Ul
l W
∂u
which is the ith component of K(c')U, where K(c') is the stiffness matrix associated with the
coefficient ∂c/∂u rather than c. The same reasoning can be applied to the derivative of the
mapping U→MU. The derivative of the mapping U→ –F is exactly
∂f
- Ú ∂u fif j dx
W
5-746
pdenonlin
which is the mass matrix associated with the coefficient ∂f/∂u. Thus the Jacobian of the
residual ρ(U) is approximated by
where the differentiation is with respect to u, K and M designate stiffness and mass
matrices, and their indices designate the coefficients with respect to which they are
assembled. At each Gauss-Newton iteration, the nonlinear solver assembles the matrices
corresponding to the equations
-— ◊ ( c—u) + ( a - f’)u = 0
-— ◊ ( c’— u) + a’u = 0
and then produces the approximate Jacobian. The differentiations of the coefficients are
done numerically.
In the general setting of elliptic systems, the boundary conditions are appended to the
stiffness matrix to form the full linear system:
% % = ÈK H ¢ ˘ ÈU ˘ È F˘ %
KU Í ˙Í ˙ = Í ˙ = F
ÎH 0 ˚ Î m ˚ Î R˚
where the coefficients of K% and F% may depend on the solution U% . The “lumped”
approach approximates the derivative mapping of the residual by
ÈJ H ¢˘
Í ˙
ÎH 0˚
The nonlinearities of the boundary conditions and the dependencies of the coefficients on
the derivatives of U% are not properly linearized by this scheme. When such nonlinearities
are strong, the scheme reduces to the fix-point iteration and may converge slowly or not
at all. When the boundary conditions are linear, they do not affect the convergence
properties of the iteration schemes. In the Neumann case they are invisible (H is an
empty matrix) and in the Dirichlet case they merely state that the residual is zero on the
corresponding boundary points.
5-747
5 Functions — Alphabetical List
See Also
solvepde
5-748
pdeplot
pdeplot
Plot solution or mesh for 2-D geometry
Syntax
pdeplot(model,'XYData',results.NodalSolution)
pdeplot(model,'XYData',results.Temperature,'ColorMap','hot')
pdeplot(
model,'XYData',results.VonMisesStress,'Deformation',results.Displace
ment)
pdeplot(model,'XYData',results.ModeShapes.ux)
pdeplot(model)
pdeplot(mesh)
pdeplot(nodes,elements)
pdeplot(p,e,t)
Description
pdeplot(model,'XYData',results.NodalSolution) plots the solution of a model
at nodal locations as a colored surface plot using the default 'jet' colormap.
pdeplot(
model,'XYData',results.VonMisesStress,'Deformation',results.Displace
ment) plots the von Mises stress and shows the deformed shape for a 2-D structural
analysis model.
5-749
5 Functions — Alphabetical List
pdeplot(mesh) plots the mesh defined as a Mesh property of a 2-D model object of type
PDEModel.
pdeplot( ___ ,Name,Value) plots the mesh, the data at the nodal locations, or both the
mesh and the data, depending on the Name,Value pair arguments. Use any arguments
from the previous syntaxes.
Specify at least one of the FlowData (vector field plot), XYData (colored surface plot), or
ZData (3-D height plot) name-value pairs. Otherwise, pdeplot plots the mesh with no
data. You can combine any number of plot types.
h = pdeplot( ___ ) returns a handle to a plot, using any of the previous syntaxes.
Examples
Create a PDE model. Include the geometry of the built-in function lshapeg. Mesh the
geometry and plot it.
model = createpde;
geometryFromEdges(model,@lshapeg);
mesh = generateMesh(model);
pdeplot(model)
5-750
pdeplot
pdeplot(mesh)
5-751
5 Functions — Alphabetical List
Another approach is to use the nodes and elements of the mesh as input arguments for
pdeplot.
pdeplot(mesh.Nodes,mesh.Elements)
5-752
pdeplot
Display the node labels. Use xlim and ylim to zoom in on particular nodes.
pdeplot(model,'NodeLabels','on')
xlim([-0.2,0.2])
ylim([-0.2,0.2])
5-753
5 Functions — Alphabetical List
pdeplot(model,'ElementLabels','on')
xlim([-0.2,0.2])
ylim([-0.2,0.2])
5-754
pdeplot
Solution Plots
Create a PDE model. Include the geometry of the built-in function lshapeg. Mesh the
geometry.
model = createpde;
geometryFromEdges(model,@lshapeg);
generateMesh(model);
5-755
5 Functions — Alphabetical List
applyBoundaryCondition(model,'dirichlet','Edge',1:model.Geometry.NumEdges,'u',0);
specifyCoefficients(model,'m',0, ...
'd',0, ...
'c',1, ...
'a',0, ...
'f',1);
results = solvepde(model)
results =
StationaryResults with properties:
u = results.NodalSolution;
pdeplot(model,'XYData',u)
5-756
pdeplot
pdeplot(model,'XYData',u,'ZData',u)
5-757
5 Functions — Alphabetical List
Create a PDE model. Include the geometry of the built-in function lshapeg. Mesh the
geometry.
model = createpde;
geometryFromEdges(model,@lshapeg);
generateMesh(model);
5-758
pdeplot
applyBoundaryCondition(model,'dirichlet','Edge',1:model.Geometry.NumEdges,'u',0);
specifyCoefficients(model,'m',0, ...
'd',0, ...
'c',1, ...
'a',0, ...
'f',1);
results = solvepde(model)
results =
StationaryResults with properties:
ux = results.XGradients;
uy = results.YGradients;
pdeplot(model,'FlowData',[ux,uy])
5-759
5 Functions — Alphabetical List
Composite Plot
Plot the solution of a 2-D PDE in 3-D with the 'jet' coloring and a mesh, and include a
quiver plot. Get handles to the axes objects.
Create a PDE model. Include the geometry of the built-in function lshapeg. Mesh the
geometry.
model = createpde;
geometryFromEdges(model,@lshapeg);
generateMesh(model);
5-760
pdeplot
applyBoundaryCondition(model,'dirichlet','Edge',1:model.Geometry.NumEdges,'u',0);
specifyCoefficients(model,'m',0, ...
'd',0, ...
'c',1, ...
'a',0, ...
'f',1);
results = solvepde(model)
results =
StationaryResults with properties:
u = results.NodalSolution;
ux = results.XGradients;
uy = results.YGradients;
Plot the solution in 3-D with the 'jet' coloring and a mesh, and include the gradient as a
quiver plot.
h = pdeplot(model,'XYData',u,'ZData',u, ...
'FaceAlpha',0.5, ...
'FlowData',[ux,uy], ...
'ColorMap','jet', ...
'Mesh','on')
5-761
5 Functions — Alphabetical List
h =
3x1 graphics array:
Patch
Quiver
ColorBar
5-762
pdeplot
thermalmodel = createpde('thermal','transient');
5-763
5 Functions — Alphabetical List
•
Thermal conductivity is .
•
Mass density is .
•
Specific heat is .
thermalProperties(thermalmodel,'ThermalConductivity',10, ...
'MassDensity',2, ...
'SpecificHeat',0.1, ...
'Face',1);
5-764
pdeplot
•
Thermal conductivity is .
•
Mass density is .
•
Specific heat is .
thermalProperties(thermalmodel,'ThermalConductivity',2, ...
'MassDensity',1, ...
'SpecificHeat',0.1, ...
'Face',2);
internalHeatSource(thermalmodel,4,'Face',2);
thermalBC(thermalmodel,'Temperature',0,'Edge',[1 2 7 8]);
thermalIC(thermalmodel,0);
generateMesh(thermalmodel);
The dynamics for this problem are very fast. The temperature reaches a steady state in
about 0.1 second. To capture the interesting part of the dynamics, set the solution time to
logspace(-2,-1,10). This command returns 10 logarithmically spaced solution times
between 0.01 and 0.1.
tlist = logspace(-2,-1,10);
thermalresults = solve(thermalmodel,tlist)
thermalresults =
TransientThermalResults with properties:
5-765
5 Functions — Alphabetical List
T = thermalresults.Temperature;
pdeplot(thermalmodel,'XYData',T(:,10),'Contour','on','ColorMap','hot')
5-766
pdeplot
Create the geometry and include it in the model. Plot the geometry.
geometryFromEdges(structuralmodel,@squareg);
pdegplot(structuralmodel,'EdgeLabels','on')
axis equal
5-767
5 Functions — Alphabetical List
structuralProperties(structuralmodel,'PoissonsRatio',0.3, ...
'YoungsModulus',210E3);
structuralBC(structuralmodel,'XDisplacement',0.001,'Edge',1);
structuralBC(structuralmodel,'Constraint','fixed','Edge',3);
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel);
Plot the deformed shape using the default scale factor. By default, pdeplot internally
determines the scale factor based on the dimensions of the geometry and the magnitude
of deformation.
pdeplot(structuralmodel,'XYData',structuralresults.VonMisesStress, ...
'Deformation',structuralresults.Displacement, ...
'ColorMap','jet')
5-768
pdeplot
pdeplot(structuralmodel,'XYData',structuralresults.VonMisesStress, ...
'Deformation',structuralresults.Displacement, ...
'DeformationScaleFactor',500,...
'ColorMap','jet')
5-769
5 Functions — Alphabetical List
pdeplot(structuralmodel,'XYData',structuralresults.VonMisesStress, ...
'ColorMap','jet')
5-770
pdeplot
Find the fundamental (lowest) mode of a 2-D cantilevered beam, assuming a prevalence of
the plane-stress condition.
Specify the following geometric and structural properties of the beam, along with a unit
plane-stress thickness.
length = 5;
height = 0.1;
E = 3E7;
5-771
5 Functions — Alphabetical List
nu = 0.3;
rho = 0.3/386;
structuralmodel = createpde('structural','modal-planestress');
gdm = [3;4;0;length;length;0;0;0;height;height];
g = decsg(gdm,'S1',('S1')');
geometryFromEdges(structuralmodel,g);
Define a maximum element size (five elements through the beam thickness).
hmax = height/5;
msh=generateMesh(structuralmodel,'Hmax',hmax);
structuralProperties(structuralmodel,'YoungsModulus',E, ...
'MassDensity',rho, ...
'PoissonsRatio',nu);
structuralBC(structuralmodel,'Edge',4,'Constraint','fixed');
Compute the analytical fundamental frequency (Hz) using the beam theory.
I = height^3/12;
analyticalOmega1 = 3.516*sqrt(E*I/(length^4*(rho*height)))/(2*pi)
analyticalOmega1 = 126.9498
Specify a frequency range that includes an analytically computed frequency and solve the
model.
modalresults = solve(structuralmodel,'FrequencyRange',[0,1e6])
modalresults =
ModalStructuralResults with properties:
The solver finds natural frequencies and modal displacement values at nodal locations. To
access these values, use modalresults.NaturalFrequencies and
modalresults.ModeShapes.
5-772
pdeplot
modalresults.NaturalFrequencies/(2*pi)
ans = 32×1
105 ×
0.0013
0.0079
0.0222
0.0433
0.0711
0.0983
0.1055
0.1462
0.1930
0.2455
⋮
modalresults.ModeShapes
pdeplot(structuralmodel,'XYData',modalresults.ModeShapes.uy(:,1))
title(['First Mode with Frequency ', ...
num2str(modalresults.NaturalFrequencies(1)/(2*pi)),' Hz'])
axis equal
5-773
5 Functions — Alphabetical List
Plot the p,e,t mesh. Display the solution using 2-D and 3-D colored plots.
Create the geometry, mesh, boundary conditions, PDE coefficients, and solution.
[p,e,t] = initmesh('lshapeg');
u = assempde('lshapeb',p,e,t,1,0,1);
5-774
pdeplot
pdeplot(p,e,t)
pdeplot(p,e,t,'XYData',u)
5-775
5 Functions — Alphabetical List
pdeplot(p,e,t,'XYData',u,'ZData',u)
5-776
pdeplot
Input Arguments
model — Model object
PDEModel object | ThermalModel object | StructuralModel object
5-777
5 Functions — Alphabetical List
Mesh object, specified as the Mesh property of a PDEModel object or as the output of
generateMesh.
Example: model.Mesh
p — Mesh points
matrix
Mesh points, specified as a 2-by-Np matrix of points, where Np is the number of points in
the mesh. For a description of the (p,e,t) matrices, see “Mesh Data” on page 2-241.
5-778
pdeplot
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
e — Mesh edges
matrix
Mesh edges, specified as a 7-by-Ne matrix of edges, where Ne is the number of edges in
the mesh. For a description of the (p,e,t) matrices, see “Mesh Data” on page 2-241.
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
t — Mesh triangles
matrix
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated
by initmesh or refinemesh.
Example: [p,e,t] = initmesh(gd)
Data Types: double
5-779
5 Functions — Alphabetical List
Tip Specify at least one of the FlowData (vector field plot), XYData (colored surface
plot), or ZData (3-D height plot) name-value pairs. Otherwise, pdeplot plots the mesh
with no data.
Data Plots
Colored surface plot data, specified as the comma-separated pair consisting of 'XYData'
and a vector. If you use a [p,e,t] representation, specify data for points in a vector of
length size(p,2), or specify data for triangles in a vector of length size(t,2).
• Typically, you set XYData to the solution u. The pdeplot function uses XYData for
coloring both 2-D and 3-D plots.
• pdeplot uses the colormap specified in the ColorMap name-value pair, using the
style specified in the XYStyle name-value pair.
• When the Contour name-value pair is 'on', pdeplot also plots level curves of
XYData.
• pdeplot plots the real part of complex data.
To plot the kth component of a solution to a PDE system, extract the relevant part of the
solution. For example, when using a PDEModel object, specify:
results = solvepde(model);
u = results.NodalSolution; % each column of u has one component of u
pdeplot(model,'XYData',u(:,k)) % data for column k
5-780
pdeplot
Example: 'XYData',u
Data Types: double
Data for the 3-D plot heights, specified as the comma-separated pair consisting of
'ZData' and a matrix. If you use a [p,e,t] representation, provide data for points in a
vector of length size(p,2) or data for triangles in a vector of length size(t,2).
• Typically, you set ZData to u, the solution. The XYData name-value pair sets the
coloring of the 3-D plot.
• The ZStyle name-value pair specifies whether the plot is continuous or discontinuous.
• pdeplot plots the real part of complex data.
To plot the kth component of a solution to a PDE system, extract the relevant part of the
solution. For example, when using a PDEModel object, specify:
results = solvepde(model);
u = results.NodalSolution; % each column of u has one component of u
pdeplot(model,'XYData',u(:,k),'ZData',u(:,k)) % data for column k
5-781
5 Functions — Alphabetical List
Example: 'ZData',u
Data Types: double
3-D plot style, specified as the comma-separated pair consisting of 'ZStyle' and one of
these values:
If you use ZStyle without specifying the ZData name-value pair, then pdeplot ignores
ZStyle.
Example: 'ZStyle','discontinuous'
Data Types: char | string
Data for the quiver plot on page 5-787, specified as the comma-separated pair consisting
of 'FlowData' and an M-by-2 matrix, where M is the number of mesh nodes. FlowData
contains the x and y values of the field at the mesh points.
results = solvepde(model);
gradx = results.XGradients;
grady = results.YGradients;
pdeplot(model,'FlowData',[gradx grady])
5-782
pdeplot
When you use ZData to represent a 2-D PDE solution as a 3-D plot and you also include a
quiver plot, the quiver plot appears in the z = 0 plane.
Indicator to show the quiver plot, specified as the comma-separated pair consisting of
'FlowStyle' and 'arrow' or 'off'. Here, 'arrow' displays the quiver plot on page 5-
787 specified by the FlowData name-value pair.
Example: 'FlowStyle','off'
Data Types: char | string
Indicator to convert the mesh data to x-y grid before plotting, specified as the comma-
separated pair consisting of 'XYGrid' and 'off' or 'on'.
Note This conversion can change the geometry and lessen the quality of the plot.
[~,tn,a2,a3] = tri2grid(p,t,u,x,y);
pdeplot(p,e,t,'XYGrid','on','GridParam',[tn;a2;a3],'XYData',u)
5-783
5 Functions — Alphabetical List
For details on the grid data and its x and y arguments, see tri2grid. The tri2grid
function does not work with PDEModel objects.
Example: 'GridParam',[tn;a2;a3]
Data Types: double
Mesh Plots
Data for plotting the deformed shape for a structural analysis model, specified as the
comma-separated pair consisting of 'Deformation' and the Displacement property of
the StaticStructuralResults object. This property is a structure array with the fields
containing displacement components at the nodal locations.
Example: 'Deformation',structuralresults.Displacement
Data Types: struct
5-784
pdeplot
Scaling factor for plotting the deformed shape, specified as the comma-separated pair
consisting of 'DeformationScaleFactor' and a real number. Use this argument with
the Deformation name-value pair. The default value is defined internally, based on the
dimensions of the geometry and the magnitude of the deformation.
Example: 'DeformationScaleFactor',100
Data Types: double
ColorMap — Colormap
'cool' (default) | ColorMap value or matrix of such values
Indicator to show the mesh, specified as the comma-separated pair consisting of 'Mesh'
and 'on' or 'off'. Specify 'on' to show the mesh in the plot.
Example: 'Mesh','on'
5-785
5 Functions — Alphabetical List
Surface transparency for 3-D geometry, specified as the comma-separated pair consisting
of 'FaceAlpha' and a real number from 0 through 1. The default value 1 indicates no
transparency. The value 0 indicates complete transparency.
Example: 'FaceAlpha',0.5
Data Types: double
Levels for contour plot, specified as the comma-separated pair consisting of 'Levels'
and a positive integer or a vector of level values.
5-786
pdeplot
Example: 'Levels',16
Data Types: double
Output Arguments
h — Handles to graphics objects
vector
Definitions
Quiver Plot
A quiver plot is a plot of a vector field. It is also called a flow plot.
Arrows show the direction of the field, with the lengths of the arrows showing the relative
sizes of the field strength. For details on quiver plots, see quiver.
See Also
PDEModel | pdeplot3D
Topics
“Plot 2-D Solutions and Their Gradients” on page 3-266
“Deflection of Piezoelectric Actuator” on page 3-13
“Mesh Data” on page 2-241
“Solve Problems Using PDEModel Objects” on page 2-6
5-787
5 Functions — Alphabetical List
pdeplot3D
Plot solution or surface mesh for 3-D geometry
Syntax
pdeplot3D(model,'ColorMapData',results.NodalSolution)
pdeplot3D(model,'ColorMapData',results.Temperature)
pdeplot3D(
model,'ColorMapData',results.VonMisesStress,'Deformation',results.Di
splacement)
pdeplot3D(model)
pdeplot3D(mesh)
pdeplot3D(nodes,elements)
Description
pdeplot3D(model,'ColorMapData',results.NodalSolution) plots the solution at
nodal locations as colors on the surface of the 3-D geometry specified in model.
pdeplot3D(
model,'ColorMapData',results.VonMisesStress,'Deformation',results.Di
splacement) plots the von Mises stress and shows the deformed shape for a 3-D
structural analysis model.
pdeplot3D(mesh) plots the mesh defined as a Mesh property of a 3-D model object of
type PDEModel.
5-788
pdeplot3D
pdeplot3D( ___ ,Name,Value) plots the surface mesh, the data at nodal locations, or
both the mesh and data, depending on the Name,Value pair arguments. Use any
arguments from the previous syntaxes.
h = pdeplot3D( ___ ) returns a handle to a plot, using any of the previous syntaxes.
Examples
Plot a PDE solution on the geometry surface. First, create a PDE model and import a 3-D
geometry file. Specify boundary conditions and coefficients. Mesh the geometry and solve
the problem.
model = createpde;
importGeometry(model,'Block.stl');
applyBoundaryCondition(model,'dirichlet','Face',[1:4],'u',0);
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',0,'f',2);
generateMesh(model);
results = solvepde(model)
results =
StationaryResults with properties:
u = results.NodalSolution;
pdeplot3D(model,'ColorMapData',u)
5-789
5 Functions — Alphabetical List
thermalmodel = createpde('thermal');
5-790
pdeplot3D
importGeometry(thermalmodel,'Block.stl');
pdegplot(thermalmodel,'FaceLabel','on','FaceAlpha',0.5)
axis equal
thermalProperties(thermalmodel,'ThermalConductivity',80);
Apply a constant temperature of to the left side of the block (face 1) and a
constant temperature of to the right side of the block (face 3). All other faces are
insulated by default.
5-791
5 Functions — Alphabetical List
thermalBC(thermalmodel,'Face',1,'Temperature',100);
thermalBC(thermalmodel,'Face',3,'Temperature',300);
generateMesh(thermalmodel);
thermalresults = solve(thermalmodel)
thermalresults =
SteadyStateThermalResults with properties:
The solver finds the temperatures and temperature gradients at the nodal locations. To
access these values, use thermalresults.Temperature,
thermalresults.XGradients, and so on. For example, plot temperatures at nodal
locations.
pdeplot3D(thermalmodel,'ColorMapData',thermalresults.Temperature)
5-792
pdeplot3D
For a 3-D steady-state thermal model, evaluate heat flux at the nodal locations and at the
points specified by x, y, and z coordinates.
thermalmodel = createpde('thermal');
5-793
5 Functions — Alphabetical List
importGeometry(thermalmodel,'Block.stl');
pdegplot(thermalmodel,'FaceLabels','on','FaceAlpha',0.5)
title('Copper block, cm')
axis equal
Assuming that this is a copper block, the thermal conductivity of the block is
approximately .
thermalProperties(thermalmodel,'ThermalConductivity',4);
Apply a constant temperature of 373 K to the left side of the block (face 1) and a constant
temperature of 573 K to the right side of the block (face 3).
5-794
pdeplot3D
thermalBC(thermalmodel,'Face',1,'Temperature',373);
thermalBC(thermalmodel,'Face',3,'Temperature',573);
thermalBC(thermalmodel,'Face',4,'HeatFlux',-20);
generateMesh(thermalmodel);
thermalresults = solve(thermalmodel)
thermalresults =
SteadyStateThermalResults with properties:
[qx,qy,qz] = evaluateHeatFlux(thermalresults);
figure
pdeplot3D(thermalmodel,'FlowData',[qx qy qz])
5-795
5 Functions — Alphabetical List
Create a grid specified by x, y, and z coordinates, and evaluate heat flux to the grid.
[X,Y,Z] = meshgrid(1:26:100,1:6:20,1:11:50);
[qx,qy,qz] = evaluateHeatFlux(thermalresults,X,Y,Z);
Reshape the qx, qy, and qz vectors, and plot the resulting heat flux.
qx = reshape(qx,size(X));
qy = reshape(qy,size(Y));
qz = reshape(qz,size(Z));
figure
quiver3(X,Y,Z,qx,qy,qz)
5-796
pdeplot3D
Alternatively, you can specify the grid by using a matrix of query points.
qx = reshape(qx,size(X));
qy = reshape(qy,size(Y));
qz = reshape(qz,size(Z));
figure
quiver3(X,Y,Z,qx,qy,qz)
5-797
5 Functions — Alphabetical List
structuralmodel = createpde('structural','static-solid');
importGeometry(structuralmodel,'SquareBeam.STL');
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
5-798
pdeplot3D
structuralProperties(structuralmodel,'PoissonsRatio',0.3, ...
'YoungsModulus',210E3);
structuralBC(structuralmodel,'Face',6,'Constraint','fixed');
structuralBoundaryLoad(structuralmodel,'Face',5,'SurfaceTraction',[0;0;-2]);
5-799
5 Functions — Alphabetical List
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel);
Plot the deformed shape with the von Mises stress using the default scale factor. By
default, pdeplot3D internally determines the scale factor based on the dimensions of the
geometry and the magnitude of deformation.
figure
pdeplot3D(structuralmodel,'ColorMapData',structuralresults.VonMisesStress, ...
'Deformation',structuralresults.Displacement)
5-800
pdeplot3D
'Deformation',structuralresults.Displacement, ...
'DeformationScaleFactor',500)
figure
pdeplot3D(structuralmodel,'ColorMapData',structuralresults.VonMisesStress)
5-801
5 Functions — Alphabetical List
Create the geometry and include it in the model. Plot the geometry.
gm = multicuboid(0.06,0.005,0.01);
structuralmodel.Geometry = gm;
5-802
pdeplot3D
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
Specify the Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3, ...
'MassDensity',7800);
Apply a sinusoidal displacement along the y-direction on the end opposite the fixed end of
the beam.
5-803
5 Functions — Alphabetical List
structuralBC(structuralmodel,'Face',3,'YDisplacement',1E-4,'Frequency',50);
Generate a mesh.
generateMesh(structuralmodel,'Hmax',0.01);
structuralIC(structuralmodel,'Displacement',[0;0;0],'Velocity',[0;0;0]);
tlist = 0:0.002:0.2;
structuralresults = solve(structuralmodel,tlist);
vmStress = evaluateVonMisesStress(structuralresults);
figure
pdeplot3D(structuralmodel,'ColorMapData',vmStress(:,end))
title('von Mises Stress in the Beam for the Last Time-Step')
5-804
pdeplot3D
model = createpde;
importGeometry(model,'Tetrahedron.stl');
mesh = generateMesh(model,'Hmax',20,'GeometricOrder','linear');
pdeplot3D(model)
5-805
5 Functions — Alphabetical List
pdeplot3D(mesh)
5-806
pdeplot3D
Another approach is to use the nodes and elements of the mesh as input arguments for
pdeplot3D.
pdeplot3D(mesh.Nodes,mesh.Elements)
5-807
5 Functions — Alphabetical List
pdeplot3D(model,'NodeLabels','on')
view(101,12)
5-808
pdeplot3D
pdeplot3D(model,'ElementLabels','on')
view(101,12)
5-809
5 Functions — Alphabetical List
Input Arguments
model — Model object
PDEModel object | ThermalModel object | StructuralModel object
5-810
pdeplot3D
Mesh object, specified as the Mesh property of a PDEModel object or as the output of
generateMesh.
Example: model.Mesh
5-811
5 Functions — Alphabetical List
5-812
pdeplot3D
Example: 'ColorMapData',results.NodalSolution(:,1)
Data Types: double
Data for the quiver plot on page 5-787, specified as the comma-separated pair consisting
of 'FlowData' and an M-by-3 matrix, where M is the number of mesh nodes. FlowData
contains the x, y, and z values of the field at the mesh points. Set FlowData as follows:
results = solvepde(model);
[cgradx,cgrady,cgradz] = evaluateCGradient(results);
pdeplot3D(model,'FlowData',[cgradx cgrady cgradz])
Indicator to show the mesh, specified as the comma-separated pair consisting of 'Mesh'
and 'on' or 'off'. Specify 'on' to show the mesh in the plot.
Example: 'Mesh','on'
Data Types: char | string
5-813
5 Functions — Alphabetical List
Example: 'ElementLabels','on'
Data Types: char | string
Surface transparency for 3-D geometry, specified as the comma-separated pair consisting
of 'FaceAlpha' and a real number from 0 through 1. The default value 1 indicates no
transparency. The value 0 indicates complete transparency.
Example: 'FaceAlpha',0.5
Data Types: double
Output Arguments
h — Handles to graphics objects
vector
See Also
PDEModel | pdeplot
Topics
“Plot 3-D Solutions and Their Gradients” on page 3-277
“Solve Problems Using PDEModel Objects” on page 2-6
Introduced in R2015a
5-814
pdepoly
pdepoly
Package: pde
Syntax
pdepoly(X,Y)
pdepoly(X,Y,label)
Description
pdepoly(X,Y) draws a polygon with the corner coordinates (vertices) defined by X and
Y. The pdepoly command opens the PDE Modeler app with the specified polygon drawn
in it. If the app is already open, pdepoly adds the specified polygon to the app window
without deleting any existing shapes.
pdepoly updates the state of the geometry description matrix inside the PDE Modeler
app to include the polygon. You can export the geometry description matrix from the PDE
Modeler app to the MATLAB Workspace by selecting DrawExport Geometry
Description, Set Formula, Labels.... For details on the format of the geometry
description matrix, see decsg.
Examples
Open the PDE Modeler app window containing a polygon representing the L-shaped
membrane geometry.
pdepoly([-1 0 0 1 1 -1],[0 0 1 1 -1 -1])
5-815
5 Functions — Alphabetical List
Call the pdepoly command again to draw the diamond-shaped region with corners in
(0.5,0), (1,-0.5), (0.5,-1), and (0,-0.5). The pdepoly command adds the
second polygon to the app window without deleting the first.
5-816
pdepoly
5-817
5 Functions — Alphabetical List
Open the PDE Modeler app window with a polygon representing the L-shaped membrane
geometry. Assign the name L-shaped-membrane to this polygon.
5-818
pdepoly
5-819
5 Functions — Alphabetical List
Input Arguments
X — x-coordinates of vertices
vector of real numbers
Y — y-coordinates of vertices
vector of real numbers
label — Name
character vector | string scalar
Tips
• pdepoly opens the PDE Modeler app and draws a polygon. If, instead, you want to
draw polygons in a MATLAB figure, use the plot function, for example:
x = [-1,-0.5,-0.5,0,1.5,-0.5,-1];
y = [-1,-1,-0.5,0,0.5,0.9,-1];
plot(x,y,'.-')
See Also
PDE Modeler | pdecirc | pdeellip | pderect
5-820
pdeprtni
pdeprtni
(Not recommended) Interpolate from triangle midpoint data to node data
Syntax
un = pdeprtni(p,t,ut)
Description
un = pdeprtni(p,t,ut) gives linearly interpolated values at node points from the
values at triangle midpoints.
The geometry of the PDE problem is given by the mesh data p and t. For details on the
mesh data representation, see initmesh.
Let N be the dimension of the PDE system, np the number of node points, and nt the
number of triangles. The components of triangle data in ut are stored as N rows of length
nt. The components of the node data are stored in un as N columns of length np.
Caution
pdeprtni and pdeintrp are not inverse functions. The interpolation introduces some
averaging.
See Also
interpolateSolution | solvepde
5-821
5 Functions — Alphabetical List
pderect
Package: pde
Syntax
pderect([xmin xmax ymin ymax])
pderect([xmin xmax ymin ymax], label)
Description
pderect([xmin xmax ymin ymax]) draws a rectangle with the corner coordinates
defined by [xmin xmax ymin ymax]. The pderect command opens the PDE Modeler
app with the specified rectangle drawn in it. If the app is already open, pderect adds the
specified rectangle to the app window without deleting any existing shapes.
pderect updates the state of the geometry description matrix inside the PDE Modeler
app to include the rectangle. You can export the geometry description matrix from the
PDE Modeler app to the MATLAB Workspace by selecting DrawExport Geometry
Description, Set Formula, Labels.... For details on the format of the geometry
description matrix, see decsg.
Examples
Open the PDE Modeler app window containing a rectangle with the corners at
(-1,-0.5), (-1,0.5), (1,0.5), and (1,-0.5).
5-822
pderect
Call the pderect command again to draw a square with the corners at (-0.25,-0.25),
(-0.25,0.25), (0.25,0.25), and (0.25,-0.25). The pderect command adds the
square to the app window without deleting the rectangle.
5-823
5 Functions — Alphabetical List
5-824
pderect
Open the PDE Modeler app window and draw a rectangle with the corners at (-1,-0.5),
(-1,0.5), (1,0.5), and (1,-0.5). Assign the name rectangle1 to this rectangle.
5-825
5 Functions — Alphabetical List
5-826
pderect
Input Arguments
[xmin xmax ymin ymax] — Corner coordinates
vector of real numbers
label — Name
character vector | string scalar
Tips
• pderect opens the PDE Modeler app and draws a rectangle. If, instead, you want to
draw rectangles in a MATLAB figure, use the rectangle function, for example,
rectangle('Position',[1,2,5,6]).
See Also
PDE Modeler | pdecirc | pdeellip | pdepoly
5-827
5 Functions — Alphabetical List
pdesdppdesdepdesdt
Indices of points/edges/triangles in set of subdomains
Note pdesdp and pdesdt are not recommended. Use findNodes and findElements
instead.
Syntax
c = pdesdp(p,e,t)
[i,c] = pdesdp(p,e,t)
c = pdesdp(p,e,t,sdl)
[i,c] = pdesdp(p,e,t,sdl)
i = pdesdt(t)
i = pdesdt(t,sdl)
i = pdesde(e)
i = pdesde(e,sdl)
Description
[i,c] = pdesdp(p,e,t,sdl) given mesh data p, e, and t and a list of subdomain
numbers sdl, the function returns all points belonging to those subdomains. A point can
belong to several subdomains, and the points belonging to the domains in sdl are divided
into two disjoint sets. i contains indices of the points that wholly belong to the
subdomains listed in sdl, and c lists points that also belongs to the other subdomains.
c = pdesdp(p,e,t,sdl) returns indices of points that belong to more than one of the
subdomains in sdl.
5-828
pdesdppdesdepdesdt
5-829
5 Functions — Alphabetical List
pdesmech
(Not recommended) Calculate structural mechanics tensor functions
Note pdesmech is not recommended. Use the PDE Modeler app instead.
Syntax
ux = pdesmech(p,t,c,u,'PropertyName',PropertyValue,...)
Description
ux = pdesmech(p,t,c,u,'PropertyName',PropertyValue,...) returns a tensor
expression evaluated at the center of each triangle. The tensor expressions are stresses
and strains for structural mechanics applications with plane stress or plane strain
conditions. pdesmech is intended to be used for postprocessing of a solution computed
using the structural mechanics application modes of the PDE Modeler app, after
exporting the solution, the mesh, and the PDE coefficients to the MATLAB workspace.
Poisson's ratio, nu, has to be supplied explicitly for calculations of shear stresses and
strains, and for the von Mises effective stress in plane strain mode.
5-830
pdesmech
•
∂u
'ux', which is
∂x
•
∂u
'uy', which is
∂y
•
∂v
'vx', which is
∂x
•
∂v
'vy', which is
∂y
• 'exx', the x-direction strain (εx)
• 'eyy', the y-direction strain (εy)
• 'exy', the shear strain (γxy)
• 'sxx', the x-direction stress (σx)
• 'syy', the y-direction stress (σy)
5-831
5 Functions — Alphabetical List
s 12 + s 22 - s1s 2
(
(s12 + s 22 )(v2 - v + 1) + s 1s 2 2v2 - 2v - 1 )
where v is Poisson’s ratio nu.
Examples
Assuming that a problem has been solved using the application mode Structural
Mechanics, Plane Stress, and that the solution u, the mesh data p and t, and the PDE
coefficient c all have been exported to the MATLAB workspace, the x-direction strain is
computed as
sx = pdesmech(p,t,c,u,'tensor','sxx');
To compute the von Mises effective stress for a plane strain problem with Poisson's ratio
equal to 0.3, type
mises = pdesmech(p,t,c,u,'tensor','vonmises',...
'application','pn','nu',0.3);
5-832
PDESolverOptions Properties
PDESolverOptions Properties
Algorithm options for PDE solvers
Description
A PDESolverOptions object contains options used by the solvers when solving a PDE
problem specified as PDEModel. A PDEModel object contains a PDESolverOptions
object in its SolverOptions property.
Properties
Properties
Absolute tolerance for internal ODE solver, returned as a positive real number. Absolute
tolerance is a threshold below which the value of the solution component is unimportant.
This property determines the accuracy when the solution approaches zero.
Example: model.SolverOptions.AbsoluteTolerance = 5.0000e-06
Data Types: double
Relative tolerance for internal ODE solver, returned as a positive real number. This
tolerance is a measure of the error relative to the size of each solution component.
Roughly, it controls the number of correct digits in all solution components, except those
smaller than thresholds imposed by AbsoluteTolerance. The default value corresponds
to 0.1% accuracy.
Example: model.SolverOptions.RelativeTolerance = 5.0000e-03
Data Types: double
5-833
5 Functions — Alphabetical List
Acceptable residual tolerance for internal nonlinear solver, returned as a positive real
number. The nonlinear solver iterates until the residual size is less than the value of
ResidualTolerance.
Example: model.SolverOptions.ResidualTolerance = 5.0000e-04
Data Types: double
Maximal number of Gauss-Newton iterations allowed for the nonlinear solver, returned as
a positive integer.
Example: model.SolverOptions.MaxIterations = 30
Data Types: double
Minimum damping of search direction for the nonlinear solver, returned as a positive real
number.
Example: model.SolverOptions.MinStep = 1.5259e-7
Data Types: double
Residual norm, returned as the p value for Lp norm, or as 'energy'. For the Lp-norm, p
can be any positive real value, Inf, or -Inf. The p norm of a vector v is
sum(abs(v)^p)^(1/p). See norm.
Example: model.SolverOptions.ResidualNorm = 'energy'
Data Types: double | char
5-834
PDESolverOptions Properties
Flag that controls the display of internal nonlinear and ODE solver statistics and
convergence report during the solution process, returned as 'off' or 'on'.
Example: model.SolverOptions.ReportStatistics = 'on'
Data Types: char
See Also
PDEModel | solvepde | solvepdeeig
Introduced in R2016a
5-835
5 Functions — Alphabetical List
pdesurf
Shorthand command for surface plot
Note This page describes the legacy workflow. Use it when you work with legacy code
and do not plan to convert it to use the recommended approach. Otherwise, use pdeplot.
Syntax
pdesurf(p,t,u)
Description
pdesurf(p,t,u) plots a 3-D surface of PDE node or triangle data. If u is a column
vector, node data is assumed, and continuous style and interpolated shading are used. If u
is a row vector, triangle data is assumed, and discontinuous style and flat shading are
used.
For node data, this command is just shorthand for the call
pdeplot(p,[],t,'XYData',u,'XYStyle','interp',...
'ZData',u,'ZStyle','continuous',...
'ColorBar','off');
pdeplot(p,[],t,'XYData',u,'XYStyle','flat',...
'ZData',u,'ZStyle','discontinuous',...
'ColorBar','off');
If you want to have more control over your surface plot, use pdeplot instead of
pdesurf.
5-836
pdesurf
Examples
Surface plot of the solution to the equation over the geometry defined by the L-
shaped membrane. Use Dirichlet boundary conditions on .
[p,e,t] = initmesh('lshapeg');
[p,e,t] = refinemesh('lshapeg',p,e,t);
u = assempde('lshapeb',p,e,t,1,0,1);
pdesurf(p,t,u)
5-837
5 Functions — Alphabetical List
See Also
pdecont | pdemesh | pdeplot
5-838
PDE Modeler
PDE Modeler
Solve partial differential equations in 2-D regions
Description
The PDE Modeler app provides an interactive interface for solving 2-D geometry
problems. Using the app, you can create complex geometries by drawing, overlapping,
and rotating basic shapes, such as circles, polygons and so on. The app also includes
preset modes for applications, such as electrostatics, magnetostatics, heat transfer, and
so on.
You can choose to export data to the MATLAB workspace from any step in the app and
continue your work outside the app.
Note The app does not support 3-D geometry problems and systems of more than two
PDEs.
5-839
5 Functions — Alphabetical List
Examples
• “Conductive Media DC” on page 3-123
• “Heat Transfer in Block with Cavity: PDE Modeler App” on page 3-178
• “L-Shaped Membrane with a Rounded Corner” on page 3-242
Programmatic Use
pdeModeler opens the PDE Modeler app or brings focus to the app if it is already open.
pdecirc(xc,yc,r) opens the PDE Modeler app and draws a circle with center in
(xc,yc) and radius r.
pdeellip(xc,yc,a,b,phi) opens the PDE Modeler app and draws an ellipse with
center in (xc,yc) and semiaxes a and b. The rotation of the ellipse (in radians) is phi.
pdepoly(x,y) opens the PDE Modeler app and draws a polygon with corner coordinates
defined by x and y.
pderect([xmin xmax ymin ymax]) opens the PDE Modeler app and draws a
rectangle with corner coordinates defined by [xmin xmax ymin ymax].
See Also
Functions
pdecirc | pdeellip | pdepoly | pderect
Objects
PDEModel
Topics
“Conductive Media DC” on page 3-123
“Heat Transfer in Block with Cavity: PDE Modeler App” on page 3-178
“L-Shaped Membrane with a Rounded Corner” on page 3-242
5-840
pdetrg
pdetrg
(Not recommended) Triangle geometry data
Syntax
[ar,a1,a2,a3] = pdetrg(p,t)
[ar,g1x,g1y,g2x,g2y,g3x,g3y] = pdetrg(p,t)
Description
[ar,a1,a2,a3] = pdetrg(p,t) returns the area of each triangle in ar and half of the
negative cotangent of each angle in a1, a2, and a3.
The triangular mesh of the PDE problem is given by the mesh data p and t. For details on
the mesh data representation, see initmesh.
5-841
5 Functions — Alphabetical List
pdetriq
(Not recommended) Triangle quality measure
Syntax
q = pdetriq(p,t)
Description
q = pdetriq(p,t) returns a triangle quality measure given mesh data.
The triangular mesh is given by the mesh data p, e, and t. For details on the mesh data
representation, see initmesh.
4a 3
q=
h12 + h22 + h32
where a is the area and h1, h2, and h3 the side lengths of the triangle.
References
Bank, Randolph E., PLTMG: A Software Package for Solving Elliptic Partial Differential
Equations, User's Guide 6.0, Society for Industrial and Applied Mathematics,
Philadelphia, PA, 1990.
5-842
pdetriq
See Also
Introduced before R2006a
5-843
5 Functions — Alphabetical List
poiasma
(Not recommended) Boundary point matrix contributions for fast solvers of Poisson's
equation
Note poiasma is not recommended. To solve Poisson's equations, use solvepde. For
details, see “Solve Problems Using PDEModel Objects”.
Syntax
K = poiasma(n1,n2,h1,h2)
K = poiasma(n1,n2)
K = poiasma(n)
Description
K = poiasma(n1,n2,h1,h2) assembles the contributions to the stiffness matrix from
boundary points. n1 and n2 are the numbers of points in the first and second directions,
and h1 and h2 are the mesh spacings. K is a sparse n1*n2-by-n1*n2 matrix. The point
numbering is the canonical numbering for a rectangular mesh.
K = poiasma(n) uses n1 = n2 = n.
See Also
Introduced before R2006a
5-844
poicalc
poicalc
Fast solver for Poisson's equation on rectangular grid
Note poicalc is not recommended. To solve Poisson's equations, use solvepde. For
details, see “Solve Problems Using PDEModel Objects”.
Syntax
u = poicalc(f,h1,h2,n1,n2)
u = poicalc(f,h1,h2)
u = poicalc(f)
Description
u = poicalc(f,h1,h2,n1,n2) calculates the solution of Poisson's equation for the
interior points of an evenly spaced rectangular grid. The columns of u contain the
solutions corresponding to the columns of the right-hand side f. h1 and h2 are the
spacings in the first and second direction, and n1 and n2 are the number of points.
The number of rows in f must be n1*n2. If n1 and n2 are not given, the square root of
the number of rows of f is assumed. If h1 and h2 are not given, they are assumed to be
equal.
The ordering of the rows in u and f is the canonical ordering of interior points, as
returned by poiindex.
The solution is obtained by sine transforms in the first direction and tridiagonal matrix
solution in the second direction. n1 should be 1 less than a power of 2 for best
performance.
5-845
5 Functions — Alphabetical List
See Also
Introduced before R2006a
5-846
poiindex
poiindex
(Not recommended) Indices of points in canonical ordering for rectangular grid
Note poiindex is not recommended. To solve Poisson's equations, use solvepde. For
details, see “Solve Problems Using PDEModel Objects”.
Syntax
[n1,n2,h1,h2,i,c,ii,cc] = poiindex(p,e,t,sd)
Description
[n1,n2,h1,h2,i,c,ii,cc] = poiindex(p,e,t,sd) identifies a given grid p, e, t in
the subdomain sd as an evenly spaced rectangular grid. If the grid is not rectangular, n1
is 0 on return. Otherwise n1 and n2 are the number of points in the first and second
directions, h1 and h2 are the spacings. i and ii are of length (n1-2)*(n2-2) and
contain indices of interior points. i contains indices of the original mesh, whereas ii
contains indices of the canonical ordering. c and cc are of length n1*n2-
(n1-2)*(n2-2) and contain indices of border points. ii and cc are increasing.
In the canonical ordering, points are numbered from left to right and then from bottom to
top. Thus if n1 = 3 and n2 = 5, then ii = [5 8 11] and cc = [1 2 3 4 6 7 9 10
12 13 14 15].
5-847
5 Functions — Alphabetical List
poimesh
(Not recommended) Make regular mesh on rectangular geometry
Note poimesh is not recommended. To solve Poisson's equations, use solvepde. For
details, see “Solve Problems Using PDEModel Objects”.
Syntax
[p,e,t] = poimesh(g,nx,ny)
[p,e,t] = poimesh(g,n)
[p,e,t] = poimesh(g)
Description
[p,e,t] = poimesh(g,nx,ny) constructs a regular mesh on the rectangular geometry
specified by g, by dividing the “x edge” into nx pieces and the “y edge” into ny pieces,
and placing (nx+1)*(ny+1) points at the intersections.
The “x edge” is the one that makes the smallest angle with the x-axis.
The triangular mesh is described by the mesh data p, e, and t. For details on the mesh
data representation, see initmesh.
For best performance with poisolv, the larger of nx and ny should be a power of 2.
5-848
poisolv
poisolv
(Not recommended) Fast solution of Poisson's equation on rectangular grid
Note poisolv is not recommended. To solve Poisson's equations, use solvepde. For
details, see “Solve Problems Using PDEModel Objects”.
Syntax
u = poisolv(b,p,e,t,f)
Description
u = poisolv(b,p,e,t,f) solves Poisson's equation with Dirichlet boundary conditions
on a regular rectangular grid. A combination of sine transforms and tridiagonal solutions
is used for increased performance.
The boundary conditions b must specify Dirichlet conditions for all boundary points.
The mesh p, e, and t must be a regular rectangular grid. For details on the mesh data
representation, see initmesh.
Apart from roundoff errors, the result should be the same as u = assempde(b,p,e,t,
1,0,f).
References
Strang, Gilbert, Introduction to Applied Mathematics, Wellesley-Cambridge Press,
Cambridge, MA, 1986, pp. 453–458.
5-849
5 Functions — Alphabetical List
refinemesh
Refine triangular mesh
Note This page describes the legacy workflow. New features might not be compatible
with the legacy workflow. For the corresponding step in the recommended workflow, see
generateMesh.
Syntax
[p1,e1,t1] = refinemesh(g,p,e,t)
[p1,e1,t1] = refinemesh(g,p,e,t,'regular')
[p1,e1,t1] = refinemesh(g,p,e,t,'longest')
[p1,e1,t1] = refinemesh(g,p,e,t,it)
[p1,e1,t1] = refinemesh(g,p,e,t,it,'regular')
[p1,e1,t1] = refinemesh(g,p,e,t,it,'longest')
[p1,e1,t1,u1] = refinemesh(g,p,e,t,u)
[p1,e1,t1,u1] = refinemesh(g,p,e,t,u,'regular')
[p1,e1,t1,u1] = refinemesh(g,p,e,t,u,'longest')
[p1,e1,t1,u1] = refinemesh(g,p,e,t,u,it)
[p1,e1,t1,u1] = refinemesh(g,p,e,t,u,it,'regular')
[p1,e1,t1,u1] = refinemesh(g,p,e,t,u,it,'longest')
Description
[p1,e1,t1] = refinemesh(g,p,e,t) returns a refined version of the triangular
mesh specified by the geometry g, Point matrix p, Edge matrix e, and Triangle matrix t.
5-850
refinemesh
The triangular mesh is given by the mesh data p, e, and t. For details on the mesh data
representation, see “Mesh Data” on page 2-241.
The default refinement method is regular refinement, where all of the specified triangles
are divided into four triangles of the same shape. Longest edge refinement, where the
longest edge of each specified triangle is bisected, can be demanded by giving longest
as a final parameter. Using regular as a final parameter results in regular refinement.
Some triangles outside of the specified set may also be refined to preserve the
triangulation and its quality.
Examples
Mesh Refinement
Refine the mesh of the L-shaped membrane several times. Plot the mesh for the geometry
of the L-shaped membrane.
[p,e,t] = initmesh('lshapeg','hmax',inf);
subplot(2,2,1), pdemesh(p,e,t)
[p,e,t] = refinemesh('lshapeg',p,e,t);
subplot(2,2,2), pdemesh(p,e,t)
[p,e,t] = refinemesh('lshapeg',p,e,t);
subplot(2,2,3), pdemesh(p,e,t)
[p,e,t] = refinemesh('lshapeg',p,e,t);
subplot(2,2,4), pdemesh(p,e,t)
5-851
5 Functions — Alphabetical List
subplot
Algorithms
The algorithm is described by the following steps:
5-852
refinemesh
See Also
initmesh | pdeent | pdesdt
Topics
“Mesh Data” on page 2-241
5-853
5 Functions — Alphabetical List
setInitialConditions
Package: pde
Syntax
setInitialConditions(model,u0)
setInitialConditions(model,u0,ut0)
setInitialConditions( ___ ,RegionType,RegionID)
setInitialConditions(model,results)
setInitialConditions(model,results,iT)
ic = setInitialConditions( ___ )
Description
setInitialConditions(model,u0) sets initial conditions in model. Use this syntax
for stationary nonlinear problems or time-dependent problems where the time derivative
is first order.
5-854
setInitialConditions
iT. If you do not specify the time index iT, setInitialConditions uses the last
solution time in results.
Examples
Create a PDE model, import geometry, and set the initial condition to 50 on the entire
geometry.
model = createpde();
importGeometry(model,'BracketWithHole.stl');
setInitialConditions(model,50);
Create a PDE model for a system with five components. Import the Block.stl geometry.
model = createpde(5);
importGeometry(model,'Block.stl');
Set the initial conditions for each component to twice the component number.
u0 = [2:2:10]';
setInitialConditions(model,u0)
ans =
GeometricInitialConditions with properties:
RegionType: 'cell'
RegionID: 1
InitialValue: [5x1 double]
InitialDerivative: []
5-855
5 Functions — Alphabetical List
Set different initial conditions on each portion of the L-shaped membrane geometry.
Create a model, set the geometry function, and view the subdomain labels.
model = createpde();
geometryFromEdges(model,@lshapeg);
pdegplot(model,'FaceLabels','on')
axis equal
ylim([-1.1,1.1])
5-856
setInitialConditions
Set subdomain 1 to initial value -1, subdomain 2 to initial value 1, and subdomain 3 to
initial value 5.
setInitialConditions(model,-1);
setInitialConditions(model,1,'Face',2);
setInitialConditions(model,5,'Face',3);
The initial setting applies to the entire geometry. The subsequent settings override the
initial settings for regions 2 and 3.
Set initial conditions for the L-shaped membrane geometry to be , except in the
lower left square where it is .
model = createpde();
geometryFromEdges(model,@lshapeg);
pdegplot(model,'FaceLabels','on')
axis equal
ylim([-1.1,1.1])
5-857
5 Functions — Alphabetical List
Set the initial conditions on region 2 to . This setting overrides the first setting
because you apply it after the first setting.
5-858
setInitialConditions
Hyperbolic equations have nonzero m coefficient, so you must set both the u0 and ut0
arguments.
Set the initial condition value to be 0 for all components. Set the initial derivative.
To create this initial gradient, write a function file, and ensure that the function is on your
MATLAB path.
M = length(location.x);
ut0 = zeros(3,M);
denom = location.x.^2+location.y.^2+location.z.^2;
ut0(1,:) = 4 + location.x./denom;
ut0(2,:) = 5 - tanh(location.z);
ut0(3,:) = 10*location.y./denom;
end
ans =
GeometricInitialConditions with properties:
5-859
5 Functions — Alphabetical List
RegionType: 'cell'
RegionID: 1
InitialValue: 0
InitialDerivative: @ut0fun
Set initial conditions using the solution from a previous analysis on the same geometry
and mesh.
5-860
setInitialConditions
Include the geometry in a PDE model, set boundary and initial conditions, and specify
coefficients.
model = createpde();
geometryFromEdges(model,dl);
% Set boundary conditions that the upper and left edges are at temperature 10.
applyBoundaryCondition(model,'dirichlet','Edge',[2,3],'u',10);
5-861
5 Functions — Alphabetical List
specifyCoefficients(model,'m',0,...
'd',1,...
'c',1,...
'a',0,...
'f',0);
generateMesh(model,'Hmax',0.05);
tlist = 0:0.01:0.5;
results = solvepde(model,tlist);
Plot the solution for times 0.02, 0.04, 0.1, and 0.5.
sol = results.NodalSolution;
subplot(2,2,1)
pdeplot(model,'XYData',sol(:,3))
title('Time 0.02')
subplot(2,2,2)
pdeplot(model,'XYData',sol(:,5))
title('Time 0.04')
subplot(2,2,3)
pdeplot(model,'XYData',sol(:,11))
title('Time 0.1')
subplot(2,2,4)
pdeplot(model,'XYData',sol(:,51))
title('Time 0.5')
5-862
setInitialConditions
Now, resume the analysis and solve the problem for times from 1/2 to 1. Use the
previously obtained solution for time 1/2 as an initial condition. Since 1/2 is the last
element in tlist, you do not need to specify the solution time index. By default,
setInitialConditions uses the last solution index.
setInitialConditions(model,results)
ans =
NodalInitialConditions with properties:
5-863
5 Functions — Alphabetical List
tlist1 = 0.5:0.01:1.0;
results1 = solvepde(model,tlist1);
sol1 = results1.NodalSolution;
figure
subplot(2,2,1)
pdeplot(model,'XYData',sol1(:,1))
title('Time 0.5')
subplot(2,2,2)
pdeplot(model,'XYData',sol1(:,21))
title('Time 0.7')
subplot(2,2,3)
pdeplot(model,'XYData',sol1(:,41))
title('Time 0.9')
subplot(2,2,4)
pdeplot(model,'XYData',sol1(:,51))
title('Time 1.0')
5-864
setInitialConditions
To use the previously obtained solution for a particular solution time instead of the last
one, specify the solution time index as a third parameter of setInitialConditions.
For example, use the solution at time 0.2, which is the 21st element in tlist.
setInitialConditions(model,results,21)
ans =
NodalInitialConditions with properties:
5-865
5 Functions — Alphabetical List
tlist2 = 0.2:0.01:1.0;
results2 = solvepde(model,tlist2);
Input Arguments
model — PDE model
PDEModel object
u0 — Initial condition
scalar | column vector of length N | function handle
• Scalar — Use it to represent a constant initial value for all solution components
throughout the domain.
• Column vector — Use it to represent a constant initial value for each of the N solution
components throughout the domain.
• Function handle — Use it to represent the initial conditions as a function of position.
The function must be of the form
u0 = initfun(location)
Solvers pass location as a structure with fields location.x, location.y, and, for
3-D problems, location.z. initfun must return a matrix u0 of size N-by-M, where M
= length(location.x).
Example: setInitialConditions(model,10)
Data Types: double | function_handle
Complex Number Support: Yes
Initial condition for time derivative, specified as a scalar, a column vector of length N, or a
function handle. N is the size of the system of PDEs. See “Equations You Can Solve Using
5-866
setInitialConditions
PDE Toolbox” on page 1-6. You must specify ut0 when there is a nonzero second-order
time-derivative coefficient m.
• Scalar — Use it to represent a constant initial value for all solution components
throughout the domain.
• Column vector — Use it to represent a constant initial value for each of the N solution
components throughout the domain.
• Function handle — Use it to represent the initial conditions as a function of position.
The function must be of the form
u0 = initfun(location)
Solvers pass location as a structure with fields location.x, location.y, and, for
3-D problems, location.z. initfun must return a matrix u0 of size N-by-M, where M
= length(location.x).
Example: setInitialConditions(model,10,@initfun)
Data Types: double | function_handle
Complex Number Support: Yes
When there are multiple initial condition assignments, solvers use the following
precedence rules for determining the initial condition.
• If there are multiple assignments to the same geometric region, solvers use the last
applied setting.
• If there are separate assignments to a geometric region and the boundaries of that
region, the solvers use the specified assignment on the region and choose the
assignment on the boundary as follows. The solvers give an 'Edge' assignment
precedence over a 'Face' assignment, even if you specify a 'Face' assignment after
an 'Edge' assignment. The precedence levels are 'Vertex (highest precedence),
'Edge', 'Face', 'Cell' (lowest precedence).
• If there is an assignment made with the results object, solvers use that assignment
instead of all previous assignments.
Example: setInitialConditions(model,10,'Face',1:4)
5-867
5 Functions — Alphabetical List
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot, as shown in “Create Geometry and Remove Face Boundaries” on page 2-13 or
“STL File Import” on page 2-47.
Example: setInitialConditions(model,10,'Face',1:4)
Data Types: double
iT — Time index
positive integer
Output Arguments
ic — Handle to initial condition
object
Handle to initial condition, returned as an object. ic associates the initial condition with
the geometric region in the case of a geometric assignment or the nodes in the case of a
results-based assignment.
5-868
setInitialConditions
Tips
• To ensure that the model has the correct TimeDependent property setting, if possible
specify coefficients before setting initial conditions.
• To avoid assigning initial conditions to a wrong region, ensure that you are using the
correct geometric region IDs by plotting and visually inspecting the geometry.
See Also
PDEModel | findInitialConditions | pdegplot
Topics
“Set Initial Conditions” on page 2-161
“Solve Problems Using PDEModel Objects” on page 2-6
“Equations You Can Solve Using PDE Toolbox” on page 1-6
Introduced in R2016a
5-869
5 Functions — Alphabetical List
solve
Package: pde
Syntax
thermalresults = solve(thermalmodel)
thermalresults = solve(thermalmodel,tlist)
structuralresults = solve(structuralmodel)
structuralresults = solve(structuralmodel,tlist)
structuralresults = solve(structuralmodel,'FrequencyRange',
[omega1,omega2])
Description
thermalresults = solve(thermalmodel) returns the solution to the steady-state
thermal model represented in thermalmodel.
structuralresults = solve(structuralmodel,'FrequencyRange',
[omega1,omega2]) returns the solution to the modal analysis model for all modes in the
frequency range [omega1,omega2]. Define omega1 as slightly smaller than the lowest
expected frequency and omega2 as slightly larger than the highest expected frequency.
For example, is the lowest expected frequency is zero, then use a small negative value for
omega1.
5-870
solve
Examples
thermalmodel = createpde('thermal');
importGeometry(thermalmodel,'Block.stl');
pdegplot(thermalmodel,'FaceLabel','on','FaceAlpha',0.5)
axis equal
5-871
5 Functions — Alphabetical List
thermalProperties(thermalmodel,'ThermalConductivity',80);
Apply a constant temperature of to the left side of the block (face 1) and a
constant temperature of to the right side of the block (face 3). All other faces are
insulated by default.
thermalBC(thermalmodel,'Face',1,'Temperature',100);
thermalBC(thermalmodel,'Face',3,'Temperature',300);
5-872
solve
generateMesh(thermalmodel);
thermalresults = solve(thermalmodel)
thermalresults =
SteadyStateThermalResults with properties:
The solver finds the temperatures and temperature gradients at the nodal locations. To
access these values, use thermalresults.Temperature,
thermalresults.XGradients, and so on. For example, plot temperatures at nodal
locations.
pdeplot3D(thermalmodel,'ColorMapData',thermalresults.Temperature)
5-873
5 Functions — Alphabetical List
5-874
solve
gd = [SQ1 D1];
sf = 'SQ1+D1';
ns = char('SQ1','D1');
ns = ns';
dl = decsg(gd,sf,ns);
geometryFromEdges(thermalmodel,dl);
pdegplot(thermalmodel,'EdgeLabels','on','FaceLabels','on')
xlim([-1.5 4.5])
ylim([-0.5 3.5])
axis equal
5-875
5 Functions — Alphabetical List
•
Thermal conductivity is .
•
Mass density is .
•
Specific heat is .
thermalProperties(thermalmodel,'ThermalConductivity',10, ...
'MassDensity',2, ...
'SpecificHeat',0.1, ...
'Face',1);
•
Thermal conductivity is .
•
Mass density is .
•
Specific heat is .
thermalProperties(thermalmodel,'ThermalConductivity',2, ...
'MassDensity',1, ...
'SpecificHeat',0.1, ...
'Face',2);
The dynamics for this problem are very fast. The temperature reaches a steady state in
about 0.1 second. To capture the interesting part of the dynamics, set the solution time to
5-876
solve
tlist = logspace(-2,-1,10);
thermalresults = solve(thermalmodel,tlist)
thermalresults =
TransientThermalResults with properties:
T = thermalresults.Temperature;
pdeplot(thermalmodel,'XYData',T(:,10),'Contour','on','ColorMap','hot')
5-877
5 Functions — Alphabetical List
structuralmodel = createpde('structural','static-solid');
Create the geometry and include it in the model. Plot the geometry.
5-878
solve
gm = multicylinder([0.01,0.015],0.05);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','CellLabels','on','FaceAlpha',0.5)
Specify the Young's modulus and Poisson's ratio for each metal.
structuralProperties(structuralmodel,'Cell',1,'YoungsModulus',110E9, ...
'PoissonsRatio',0.28);
structuralProperties(structuralmodel,'Cell',2,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3);
structuralBC(structuralmodel,'Face',[1,4],'Constraint','fixed');
5-879
5 Functions — Alphabetical List
structuralBoundaryLoad(structuralmodel,'Face',[2,5],'SurfaceTraction',[0;0;100]);
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel)
structuralresults =
StaticStructuralResults with properties:
The solver finds the values of displacement, stress, strain, and von Mises stress at the
nodal locations. To access these values, use structuralresults.Displacement,
structuralresults.Stress, and so on. Displacement, stress, and strain at the nodal
locations are structure arrays with fields representing their components.
structuralresults.Displacement
structuralresults.Stress
structuralresults.Strain
5-880
solve
pdeplot3D(structuralmodel,'ColorMapData',structuralresults.Stress.szz, ...
'Deformation',structuralresults.Displacement)
5-881
5 Functions — Alphabetical List
Solve for transient response of a thin 3-D plate under a harmonic load at the center.
Create the geometry and include it in the model. Plot the geometry.
gm = multicuboid([5,0.05],[5,0.05],0.01);
structuralmodel.Geometry=gm;
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
5-882
solve
Zoom in to see the face labels on the small plate in the center.
figure
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.25)
axis([-0.2 0.2 -0.2 0.2 -0.1 0.1])
Specify the Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9,...
'PoissonsRatio',0.3,...
'MassDensity',7800);
Specify that all faces on the periphery of the thin 3-D plate are fixed boundaries.
structuralBC(structuralmodel,'Constraint','fixed','Face',5:8);
5-883
5 Functions — Alphabetical List
Apply a sinusoidal pressure load on the small face at the center of the plate.
structuralBoundaryLoad(structuralmodel,'Face',12,'Pressure',5E7,'Frequency',25);
structuralresults =
TransientStructuralResults with properties:
The solver finds the values of displacement, velocity, and acceleration at the nodal
locations. To access these values, use structuralresults.Displacement,
structuralresults.Velocity, and so on. Displacement, velocity, and acceleration are
structure arrays with fields representing their components.
structuralresults.Displacement
structuralresults.Velocity
5-884
solve
structuralresults.Acceleration
Find the fundamental (lowest) mode of a 2-D cantilevered beam, assuming a prevalence of
the plane-stress condition.
Specify the following geometric and structural properties of the beam, along with a unit
plane-stress thickness.
length = 5;
height = 0.1;
E = 3E7;
nu = 0.3;
rho = 0.3/386;
Define a maximum element size (five elements through the beam thickness).
hmax = height/5;
msh=generateMesh(structuralmodel,'Hmax',hmax);
5-885
5 Functions — Alphabetical List
'PoissonsRatio',nu);
structuralBC(structuralmodel,'Edge',4,'Constraint','fixed');
Compute the analytical fundamental frequency (Hz) using the beam theory.
I = height^3/12;
analyticalOmega1 = 3.516*sqrt(E*I/(length^4*(rho*height)))/(2*pi)
analyticalOmega1 = 126.9498
Specify a frequency range that includes an analytically computed frequency and solve the
model.
modalresults = solve(structuralmodel,'FrequencyRange',[0,1e6])
modalresults =
ModalStructuralResults with properties:
The solver finds natural frequencies and modal displacement values at nodal locations. To
access these values, use modalresults.NaturalFrequencies and
modalresults.ModeShapes.
modalresults.NaturalFrequencies/(2*pi)
ans = 32×1
105 ×
0.0013
0.0079
0.0222
0.0433
0.0711
0.0983
0.1055
0.1462
0.1930
0.2455
⋮
modalresults.ModeShapes
5-886
solve
5-887
5 Functions — Alphabetical List
Find the deflection of a 3-D cantilever beam under a nonuniform thermal load. Specify the
thermal load on the structural model using the solution from a transient thermal analysis
on the same geometry and mesh.
thermalmodel = createpde('thermal','transient');
gm = multicuboid(0.5,0.1,0.05);
thermalmodel.Geometry = gm;
pdegplot(thermalmodel,'FaceLabels','on','FaceAlpha',0.5)
5-888
solve
Generate a mesh.
mesh = generateMesh(thermalmodel);
thermalProperties(thermalmodel,'ThermalConductivity',5e-3, ...
'MassDensity',2.7*10^(-6), ...
'SpecificHeat',10);
Specify the constant temperatures applied to the left and right ends on the beam.
thermalBC(thermalmodel,'Face',3,'Temperature',100);
thermalBC(thermalmodel,'Face',5,'Temperature',0);
5-889
5 Functions — Alphabetical List
internalHeatSource(thermalmodel,10);
thermalIC(thermalmodel,0);
tlist = [0:1e-4:2e-4];
thermalresults = solve(thermalmodel,tlist)
thermalresults =
TransientThermalResults with properties:
for n = 1:numel(thermalresults.SolutionTimes)
figure
pdeplot3D(thermalmodel,'ColorMapData',thermalresults.Temperature(:,n))
title(['Temperature at Time = ' num2str(tlist(n))])
caxis([0 100])
end
5-890
solve
5-891
5 Functions — Alphabetical List
5-892
solve
Use the same mesh that you used to obtain the thermal solution.
structuralmodel.Mesh = mesh;
Specify the Young's modulus, Poisson's ratio, and coefficient of thermal expansion.
5-893
5 Functions — Alphabetical List
structuralProperties(structuralmodel,'YoungsModulus',1e10, ...
'PoissonsRatio',0.3, ...'
'CTE',11.7e-6);
structuralBC(structuralmodel,'Face',5,'Constraint','fixed');
Apply a body load using the transient thermal model solution. By default,
structuralBodyLoad uses the solution for the last time step.
structuralBodyLoad(structuralmodel,'Temperature',thermalresults);
structuralmodel.ReferenceTemperature = 10;
thermalstressresults = solve(structuralmodel);
Plot the deformed shape of the beam corresponding to the last step of the transient
thermal model solution.
pdeplot3D(structuralmodel,'ColorMapData',thermalstressresults.Displacement.Magnitude, .
'Deformation',thermalstressresults.Displacement)
title(['Thermal Expansion at Solution Time = ' num2str(tlist(end))])
caxis([0 3e-3])
5-894
solve
Now specify the body loads as the thermal model solutions for all time steps. For each
body load, solve the structural model and plot the corresponding deformed shape of the
beam.
for n = 1:numel(thermalresults.SolutionTimes)
structuralBodyLoad(structuralmodel,'Temperature',thermalresults,'TimeStep',n);
thermalstressresults = solve(structuralmodel);
figure
pdeplot3D(structuralmodel,'ColorMapData',thermalstressresults.Displacement.Magnitud
'Deformation',thermalstressresults.Displacement)
title(['Thermal Results at Solution Time = ' num2str(tlist(n))])
caxis([0 3e-3])
end
5-895
5 Functions — Alphabetical List
5-896
solve
5-897
5 Functions — Alphabetical List
Input Arguments
thermalmodel — Thermal model
ThermalModel object
Thermal model, specified as a ThermalModel object. The model contains the geometry,
mesh, thermal properties of the material, internal heat source, boundary conditions, and
initial conditions.
Example: thermalmodel = createpde('thermal','steadystate')
5-898
solve
Frequency range, specified as a vector of two elements. Define omega1 as slightly smaller
than the lowest expected frequency and omega2 as slightly larger than the highest
expected frequency. For example, is the lowest expected frequency is zero, then use a
small negative value for omega1.
Example: [-0.1,1000]
Data Types: double
Output Arguments
thermalresults — Thermal results
SteadyStateThermalResults object | TransientThermalResults object
5-899
5 Functions — Alphabetical List
See Also
geometryFromEdges | PDEModel | StructuralModel | ThermalModel |
geometryFromMesh | importGeometry
Introduced in R2017a
5-900
solvepde
solvepde
Package: pde
Syntax
result = solvepde(model)
result = solvepde(model,tlist)
Description
result = solvepde(model) returns the solution to the stationary PDE represented in
model. A stationary PDE has the property model.IsTimeDependent = false. That is,
the time-derivative coefficients m and d in model.EquationCoefficients must be 0.
Examples
Create a PDE model, and include the geometry of the L-shaped membrane.
model = createpde();
geometryFromEdges(model,@lshapeg);
pdegplot(model,'EdgeLabels','on')
ylim([-1.1,1.1])
axis equal
5-901
5 Functions — Alphabetical List
applyBoundaryCondition(model,'dirichlet','Edge',1:model.Geometry.NumEdges,'u',0);
Poisson's equation is
5-902
solvepde
specifyCoefficients(model,'m',0,...
'd',0,...
'c',1,...
'a',0,...
'f',1);
generateMesh(model,'Hmax',0.25);
results = solvepde(model);
pdeplot(model,'XYData',results.NodalSolution)
5-903
5 Functions — Alphabetical List
Suppose that radiative cooling causes the solution to decrease as the cube of temperature
on the surface of the block.
gfun = @(region,state)-state.u.^3*1e-6;
applyBoundaryCondition(model,'neumann','Face',1:model.Geometry.NumFaces,'g',gfun);
5-904
solvepde
specifyCoefficients(model,'m',0,...
'd',1,...
'c',1,...
'a',0,...
'f',0);
setInitialConditions(model,350);
Mesh the geometry and solve the model for times 0 through 20.
generateMesh(model);
tlist = 0:20;
results = solvepde(model,tlist);
Plot the solution on the surface of the block at times 1 and 20.
pdeplot3D(model,'ColorMapData',results.NodalSolution(:,2))
5-905
5 Functions — Alphabetical List
figure
pdeplot3D(model,'ColorMapData',results.NodalSolution(:,21))
5-906
solvepde
Input Arguments
model — PDE model
PDEModel object
PDE model, specified as a PDEModel object. The model contains the geometry, mesh, and
problem coefficients.
Example: model = createpde(1)
5-907
5 Functions — Alphabetical List
Solution times, specified as a real vector. tlist must be a monotone vector (increasing
or decreasing).
Example: 0:20
Data Types: double
Output Arguments
result — PDE results
StationaryResults object | TimeDependentResults object
Tips
• If the Newton iteration does not converge, solvepde displays the error message Too
many iterations or Stepsize too small.
• If the initial guess produces matrices containing NaN or Inf elements, solvepde
displays the error message Unsuitable initial guess U0 (default: U0 =
0).
• If you have very small coefficients, or very small geometric dimensions, solvepde can
fail to converge, or can converge to an incorrect solution. In this case, you might
obtain better results by scaling the coefficients or geometry dimensions to be of order
one.
See Also
PDEModel | applyBoundaryCondition | setInitialConditions | solvepdeeig |
specifyCoefficients
Topics
“Solve Problems Using PDEModel Objects” on page 2-6
5-908
solvepde
Introduced in R2016a
5-909
5 Functions — Alphabetical List
solvepdeeig
Package: pde
Syntax
result = solvepdeeig(model,evr)
Description
result = solvepdeeig(model,evr) solves the PDE eigenvalue problem in model for
eigenvalues in the range evr.
Examples
The equations of elasticity have three components. Therefore, create a PDE model that
has three components. Import and view the BracketTwoHoles geometry.
model = createpde(3);
importGeometry(model,'BracketTwoHoles.stl');
pdegplot(model,'FaceLabels','on','FaceAlpha',0.5)
5-910
solvepdeeig
applyBoundaryCondition(model,'dirichlet','Face',1,'u',[0;0;0]);
Set the model coefficients to represent a steel bracket. For details, see 3-D Linear
Elasticity Equations in Toolbox Form.
5-911
5 Functions — Alphabetical List
evr = [-Inf,1e7];
generateMesh(model);
results = solvepdeeig(model,evr);
length(results.Eigenvalues)
ans = 3
Plot the solution on the geometry boundary for the lowest eigenvalue.
V = results.Eigenvectors;
subplot(2,2,1)
pdeplot3D(model,'ColorMapData',V(:,1,1))
title('x Deflection, Mode 1')
subplot(2,2,2)
pdeplot3D(model,'ColorMapData',V(:,2,1))
title('y Deflection, Mode 1')
subplot(2,2,3)
pdeplot3D(model,'ColorMapData',V(:,3,1))
title('z Deflection, Mode 1')
5-912
solvepdeeig
figure
subplot(2,2,1)
pdeplot3D(model,'ColorMapData',V(:,1,3))
title('x Deflection, Mode 3')
subplot(2,2,2)
pdeplot3D(model,'ColorMapData',V(:,2,3))
title('y Deflection, Mode 3')
subplot(2,2,3)
pdeplot3D(model,'ColorMapData',V(:,3,3))
title('z Deflection, Mode 3')
5-913
5 Functions — Alphabetical List
Input Arguments
model — PDE model
PDEModel object
PDE model, specified as a PDEModel object. The model contains the geometry, mesh, and
problem coefficients.
Example: model = createpde(1)
5-914
solvepdeeig
Eigenvalue range, specified as a two-element real vector. evr(1) specifies the lower limit
of the range of the real part of the eigenvalues, and may be -Inf. evr(2) specifies the
upper limit of the range, and must be finite.
Example: [-Inf;100]
Data Types: double
Output Arguments
result — Eigenvalue results
EigenResults object
Tips
• The equation coefficients cannot depend on the solution u or its gradient.
See Also
PDEModel | applyBoundaryCondition | solvepde | specifyCoefficients
Topics
“Eigenvalues and Eigenmodes of the L-Shaped Membrane” on page 3-233
“Eigenvalues and Eigenmodes of a Square” on page 3-244
“Solve Problems Using PDEModel Objects” on page 2-6
Introduced in R2016a
5-915
5 Functions — Alphabetical List
specifyCoefficients
Package: pde
Coefficients of a PDE
∂ 2u ∂u
m +d - —·( c—u ) + au = f
2 ∂t
∂t
- —·( c— u) + au = l du
or
- —·( c— u) + au = l 2mu
Syntax
specifyCoefficients(model,Name,Value)
specifyCoefficients(model,Name,Value,RegionType,RegionID)
CA = specifyCoefficients( ___ )
Description
specifyCoefficients(model,Name,Value) defines the specified coefficients in each
Name to each associated Value, and includes them in model. You must specify all of these
names: m, d, c, a, and f. This syntax applies coefficients to the entire geometry.
5-916
specifyCoefficients
specifyCoefficients(model,Name,Value,RegionType,RegionID) assigns
coefficients for a specified geometry region.
Examples
model = createpde();
geometryFromEdges(model,@lshapeg);
specifyCoefficients(model,'m',0,...
'd',0,...
'c',1,...
'a',0,...
'f',1);
Specify zero Dirichlet boundary conditions, mesh the model, and solve the PDE.
applyBoundaryCondition(model,'dirichlet','Edge',1:model.Geometry.NumEdges,'u',0);
generateMesh(model,'Hmax',0.25);
results = solvepde(model);
pdeplot(model,'XYData',results.NodalSolution)
5-917
5 Functions — Alphabetical List
Specify coefficients for Poisson's equation in 3-D with a nonconstant source term, and
obtain the coefficient object.
f = @(location,state)location.y.^2.*tanh(location.z)/1000;
5-918
specifyCoefficients
model = createpde();
importGeometry(model,'Block.stl');
CA = specifyCoefficients(model,'m',0,...
'd',0,...
'c',1,...
'a',0,...
'f',f)
CA =
CoefficientAssignment with properties:
RegionType: 'cell'
RegionID: 1
m: 0
d: 0
c: 1
a: 0
f: @(location,state)location.y.^2.*tanh(location.z)/1000
Set zero Dirichlet conditions on face 1, mesh the geometry, and solve the PDE.
applyBoundaryCondition(model,'dirichlet','Face',1,'u',0);
generateMesh(model);
results = solvepde(model);
pdeplot3D(model,'ColorMapData',results.NodalSolution)
5-919
5 Functions — Alphabetical List
Create a scalar PDE model with the L-shaped membrane as the geometry. Plot the
geometry and subdomain labels.
model = createpde();
geometryFromEdges(model,@lshapeg);
pdegplot(model,'FaceLabels','on')
axis equal
ylim([-1.1,1.1])
5-920
specifyCoefficients
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',0,'f',1,'Face',1);
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',0,'f',5,'Face',2);
specifyCoefficients(model,'m',0,'d',0,'c',1,'a',0,'f',-8,'Face',3);
Set zero Dirichlet boundary conditions to all edges. Create a mesh, solve the PDE, and
plot the result.
applyBoundaryCondition(model,'dirichlet','Edge',1:model.Geometry.NumEdges,'u',0);
generateMesh(model,'Hmax',0.25);
results = solvepde(model);
pdeplot(model,'XYData',results.NodalSolution)
5-921
5 Functions — Alphabetical List
Input Arguments
model — PDE model
PDEModel object
5-922
specifyCoefficients
Example: specifyCoefficients(model,'m',0,'d',0,'c',1,'a',
0,'f',@fcoeff)
Note If the m coefficient is nonzero, d must be 0 or a matrix, and not a function handle.
See “d Coefficient When m is Nonzero” on page 5-925.
5-923
5 Functions — Alphabetical List
Solution multiplier coefficient, specified as a scalar, column vector, or function handle. For
details on the sizes, and for details of the function handle form of the coefficient, see “m,
d, or a Coefficient for specifyCoefficients” on page 2-149.
f — Source coefficient
scalar | column vector | function handle
Source coefficient, specified as a scalar, column vector, or function handle. For details on
the sizes, and for details of the function handle form of the coefficient, see “f Coefficient
for specifyCoefficients” on page 2-107.
5-924
specifyCoefficients
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot, as shown in “Create Geometry and Remove Face Boundaries” on page 2-13 or
“STL File Import” on page 2-47.
Example: specifyCoefficients('m',0,'d',0,'c',1,'a',0,'f',10,'Cell',
1:3)
Data Types: double
Output Arguments
CA — Coefficient assignment
CoefficientAssignment object
Definitions
5-925
5 Functions — Alphabetical List
Tips
• For eigenvalue equations, the coefficients cannot depend on the solution u or its
gradient.
See Also
PDEModel | findCoefficients
Topics
“PDE Coefficients”
“Solve Problems Using PDEModel Objects” on page 2-6
Introduced in R2016a
5-926
sptarn
sptarn
(Not recommended) Solve generalized sparse eigenvalue problem
Syntax
[xv,lmb,iresult] = sptarn(A,B,lb,ub)
[xv,lmb,iresult] = sptarn(A,B,lb,ub,spd)
[xv,lmb,iresult] = sptarn(A,B,lb,ub,spd,tolconv)
[xv,lmb,iresult] = sptarn(A,B,lb,ub,spd,tolconv,jmax)
[xv,lmb,iresult] = sptarn(A,B,lb,ub,spd,tolconv,jmax,maxmul)
Description
[xv,lmb,iresult] = sptarn(A,B,lb,ub,spd,tolconv,jmax,maxmul) finds
eigenvalues of the pencil (A – λB)x = 0 in interval [lb,ub]. (A matrix of linear polynomials
Aij – λBij, A – λB, is called a pencil.)
A and B are sparse matrices. lb and ub are lower and upper bounds for eigenvalues to be
sought. We may have lb = -inf if all eigenvalues to the left of ub are sought, and rb =
inf if all eigenvalues to the right of lb are sought. One of lb and ub must be finite. A
narrower interval makes the algorithm faster. In the complex case, the real parts of lmb
are compared to lb and ub.
5-927
5 Functions — Alphabetical List
tolconv is the expected relative accuracy. Default is 100*eps, where eps is the machine
precision.
jmax is the maximum number of basis vectors. The algorithm needs jmax*n working
space so a small value may be justified on a small computer, otherwise let it be the default
value jmax = 100. Normally the algorithm stops earlier when enough eigenvalues have
converged.
maxmul is the number of Arnoldi runs tried. Must at least be as large as maximum
multiplicity of any eigenvalue. If a small value of jmax is given, many Arnoldi runs are
necessary. The default value is maxmul = n, which is needed when all the eigenvalues of
the unit matrix are sought.
Algorithms
The Arnoldi algorithm with spectral transformation is used. The shift is chosen at ub, lb,
or at a random point in interval (lb,ub) when both bounds are finite. The number of steps
j in the Arnoldi run depends on how many eigenvalues there are in the interval, but it
stops at j = min(jmax,n). After a stop, the algorithm restarts to find more Schur
vectors in orthogonal complement to all those already found. When no more eigenvalues
are found in lb < lmb <= ub, the algorithm stops. For small values of jmax, several
restarts may be needed before a certain eigenvalue has converged. The algorithm works
when jmax is at least one larger than the number of eigenvalues in the interval, but then
many restarts are needed. For large values of jmax, which is the preferred choice, mul+1
runs are needed. mul is the maximum multiplicity of an eigenvalue in the interval.
Note The algorithm works on nonsymmetric as well as symmetric pencils, but then
accuracy is approximately tol times the Henrici departure from normality. The
parameter spd is used only to choose between symamd and colamd when factorizing, the
former being marginally better for symmetric matrices close to the lower end of the
spectrum.
In case of trouble,
5-928
sptarn
• a larger maxmul
If factorization fails, try again with lb or ub finite. Then shift is chosen at random and
hopefully not at an eigenvalue. If it fails again, check whether pencil may be singular.
If it goes on forever, there may be too many eigenvalues in the strip. Try with a small
value maxmul = 2 and see which eigenvalues you get. Those you get are some of the
eigenvalues, but a negative iresult tells you that you have not gotten them all.
The algorithm is designed for eigenvalues close to the real axis. If you want those close to
the imaginary axis, try A = i*A.
When spd = 1, the shift is at lb so that advantage is taken of the faster factorization for
symmetric positive definite matrices. No harm is done, but the execution is slower if lb is
above the lowest eigenvalue.
References
[1] Golub, Gene H., and Charles F. Van Loan, Matrix Computations, 2nd edition, Johns
Hopkins University Press, Baltimore, MD, 1989.
[2] Saad, Yousef, “Variations on Arnoldi's Method for Computing Eigenelements of Large
Unsymmetric Matrices,” Linear Algebra and its Applications, Vol. 34, 1980, pp.
269–295.
See Also
solvepdeeig
5-929
5 Functions — Alphabetical List
StaticStructuralResults
Static structural solution and its derived quantities
Description
A StaticStructuralResults object contains the displacement, stress, strain, and von
Mises stress in a form convenient for plotting and postprocessing.
Displacements, stresses, and strains are reported for the nodes of the triangular or
tetrahedral mesh generated by generateMesh. Displacement values at the nodes appear
as a structure array in the Displacement property. The fields of the structure array
contain components of displacement at nodal locations.
Stress and strain values at the nodes appear as structure arrays in the Stress and
Strain properties, respectively.
von Mises stress at the nodes appears as a vector in the VonMisesStress property.
To interpolate the displacement, stress, strain, and von Mises stress to a custom grid,
such as the one specified by meshgrid, use interpolateDisplacement,
interpolateStress, interpolateStrain, and interpolateVonMisesStress,
respectively.
Creation
Solve a static linear elasticity problem by using the solve function. This function returns
a static structural solution as a StaticStructuralResults object.
5-930
StaticStructuralResults
Properties
Displacement — Displacement values at nodes
structure array
Displacement values at the nodes, returned as a structure array. The fields of the
structure array contain components of displacement at nodal locations.
Data Types: struct
Stress values at the nodes, returned as a structure array. The fields of the structure array
contain components of stress at nodal locations.
Data Types: struct
Strain values at the nodes, returned as a structure array. The fields of the structure array
contain components of strain at nodal locations.
Data Types: struct
Finite element mesh, returned as a FEMesh object. For details, see FEMesh.
Object Functions
interpolateDisplacement Interpolate displacement at arbitrary spatial locations
interpolateStress Interpolate stress at arbitrary spatial locations
5-931
5 Functions — Alphabetical List
Examples
structuralmodel = createpde('structural','static-solid');
Create the geometry and include it in the model. Plot the geometry.
gm = multicylinder([0.01,0.015],0.05);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','CellLabels','on','FaceAlpha',0.5)
5-932
StaticStructuralResults
Specify the Young's modulus and Poisson's ratio for each metal.
structuralProperties(structuralmodel,'Cell',1,'YoungsModulus',110E9, ...
'PoissonsRatio',0.28);
structuralProperties(structuralmodel,'Cell',2,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3);
structuralBC(structuralmodel,'Face',[1,4],'Constraint','fixed');
structuralBoundaryLoad(structuralmodel,'Face',[2,5],'SurfaceTraction',[0;0;100]);
5-933
5 Functions — Alphabetical List
structuralresults =
StaticStructuralResults with properties:
The solver finds the values of displacement, stress, strain, and von Mises stress at the
nodal locations. To access these values, use structuralresults.Displacement,
structuralresults.Stress, and so on. Displacement, stress, and strain at the nodal
locations are structure arrays with fields representing their components.
structuralresults.Displacement
structuralresults.Stress
structuralresults.Strain
5-934
StaticStructuralResults
pdeplot3D(structuralmodel,'ColorMapData',structuralresults.Stress.szz, ...
'Deformation',structuralresults.Displacement)
5-935
5 Functions — Alphabetical List
See Also
ModalStructuralResults | StructuralModel | TransientStructuralResults |
solve
Introduced in R2017b
5-936
ModalStructuralResults
ModalStructuralResults
Structural modal analysis solution
Description
A ModalStructuralResults object contains the natural frequencies and modal
displacement in a form convenient for plotting and postprocessing.
Modal displacement is reported for the nodes of the triangular or tetrahedral mesh
generated by generateMesh. The modal displacement values at the nodes appear as a
structure array in the ModeShapes property. The fields of the structure array contain the
components of the displacement at the nodal locations.
Creation
Solve a modal analysis problem by using the solve function. This function returns a
modal structural solution as a ModalStructuralResults object.
Properties
NaturalFrequencies — Natural frequencies
column vector
Modal displacement values at the nodes, returned as a structure array. The fields of the
structure array contain components of modal displacement at nodal locations.
Data Types: struct
5-937
5 Functions — Alphabetical List
Finite element mesh, returned as a FEMesh object. For details, see FEMesh.
Examples
Solution to Modal Analysis Structural Model
Find the fundamental (lowest) mode of a 2-D cantilevered beam, assuming a prevalence of
the plane-stress condition.
Specify the following geometric and structural properties of the beam, along with a unit
plane-stress thickness.
length = 5;
height = 0.1;
E = 3E7;
nu = 0.3;
rho = 0.3/386;
structuralmodel = createpde('structural','modal-planestress');
gdm = [3;4;0;length;length;0;0;0;height;height];
g = decsg(gdm,'S1',('S1')');
geometryFromEdges(structuralmodel,g);
Define a maximum element size (five elements through the beam thickness).
hmax = height/5;
msh=generateMesh(structuralmodel,'Hmax',hmax);
structuralProperties(structuralmodel,'YoungsModulus',E, ...
'MassDensity',rho, ...
'PoissonsRatio',nu);
structuralBC(structuralmodel,'Edge',4,'Constraint','fixed');
Compute the analytical fundamental frequency (Hz) using the beam theory.
5-938
ModalStructuralResults
I = height^3/12;
analyticalOmega1 = 3.516*sqrt(E*I/(length^4*(rho*height)))/(2*pi)
analyticalOmega1 = 126.9498
Specify a frequency range that includes an analytically computed frequency and solve the
model.
modalresults = solve(structuralmodel,'FrequencyRange',[0,1e6])
modalresults =
ModalStructuralResults with properties:
The solver finds natural frequencies and modal displacement values at nodal locations. To
access these values, use modalresults.NaturalFrequencies and
modalresults.ModeShapes.
modalresults.NaturalFrequencies/(2*pi)
ans = 32×1
105 ×
0.0013
0.0079
0.0222
0.0433
0.0711
0.0983
0.1055
0.1462
0.1930
0.2455
⋮
modalresults.ModeShapes
5-939
5 Functions — Alphabetical List
pdeplot(structuralmodel,'XYData',modalresults.ModeShapes.uy(:,1))
title(['First Mode with Frequency ', ...
num2str(modalresults.NaturalFrequencies(1)/(2*pi)),' Hz'])
axis equal
See Also
StaticStructuralResults | StructuralModel | TransientStructuralResults |
solve
5-940
ModalStructuralResults
Introduced in R2018a
5-941
5 Functions — Alphabetical List
TransientStructuralResults
Transient structural solution and its derived quantities
Description
A TransientStructuralResults object contains the displacement, velocity, and
acceleration in a form convenient for plotting and postprocessing.
Displacement, velocity, and acceleration are reported for the nodes of the triangular or
tetrahedral mesh generated by generateMesh. The displacement, velocity, and
acceleration values at the nodes appear as structure arrays in the Displacement,
Velocity, and Acceleration properties. The fields of the structure arrays contain the
components of the displacement, velocity, and acceleration at the nodal locations.
To evaluate the stress, strain, von Mises stress, principal stress, and principal strain at
the nodal locations, use evaluateStress, evaluateStrain,
evaluateVonMisesStress, evaluatePrincipalStress, and
evaluatePrincipalStrain, respectively.
To interpolate the displacement, velocity, acceleration, stress, strain, and von Mises stress
to a custom grid, such as the one specified by meshgrid, use
interpolateDisplacement, interpolateVelocity, interpolateAcceleration,
interpolateStress, interpolateStrain, and interpolateVonMisesStress,
respectively.
Creation
Solve a dynamic linear elasticity problem by using the solve function. This function
returns a transient structural solution as a TransientStructuralResults object.
5-942
TransientStructuralResults
Properties
Displacement — Displacement values at nodes
structure array
Displacement values at the nodes, returned as a structure array. The fields of the
structure array contain components of displacement at nodal locations.
Data Types: struct
Velocity values at the nodes, returned as a structure array. The fields of the structure
array contain components of velocity at nodal locations.
Data Types: struct
Acceleration values at the nodes, returned as a structure array. The fields of the structure
array contain components of acceleration at nodal locations.
Data Types: struct
Solution times, returned as a real vector. SolutionTimes is the same as the tlist input
to solve.
Data Types: double
Finite element mesh, returned as a FEMesh object. For details, see FEMesh.
Object Functions
evaluateStress Evaluate stress for dynamic structural analysis problem
5-943
5 Functions — Alphabetical List
Examples
Solution to Transient Structural Model
Solve for transient response of a thin 3-D plate under a harmonic load at the center.
structuralmodel = createpde('structural','transient-solid');
Create the geometry and include it in the model. Plot the geometry.
gm = multicuboid([5,0.05],[5,0.05],0.01);
structuralmodel.Geometry=gm;
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
5-944
TransientStructuralResults
Zoom in to see the face labels on the small plate in the center.
figure
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.25)
axis([-0.2 0.2 -0.2 0.2 -0.1 0.1])
5-945
5 Functions — Alphabetical List
Specify the Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9,...
'PoissonsRatio',0.3,...
'MassDensity',7800);
Specify that all faces on the periphery of the thin 3-D plate are fixed boundaries.
structuralBC(structuralmodel,'Constraint','fixed','Face',5:8);
Apply a sinusoidal pressure load on the small face at the center of the plate.
structuralBoundaryLoad(structuralmodel,'Face',12,'Pressure',5E7,'Frequency',25);
5-946
TransientStructuralResults
generateMesh(structuralmodel,'GeometricOrder','linear','Hmax',0.2);
structuralIC(structuralmodel,'Displacement',[0;0;0],'Velocity',[0;0;0]);
tlist = linspace(0,1,300);
structuralresults = solve(structuralmodel,tlist)
structuralresults =
TransientStructuralResults with properties:
The solver finds the values of displacement, velocity, and acceleration at the nodal
locations. To access these values, use structuralresults.Displacement,
structuralresults.Velocity, and so on. Displacement, velocity, and acceleration are
structure arrays with fields representing their components.
structuralresults.Displacement
structuralresults.Velocity
structuralresults.Acceleration
5-947
5 Functions — Alphabetical List
See Also
ModalStructuralResults | StaticStructuralResults | StructuralModel |
solve
Introduced in R2018a
5-948
structuralBC
structuralBC
Package: pde
Syntax
structuralBC(structuralmodel,RegionType,RegionID,'Constraint',Cval)
structuralBC(structuralmodel,RegionType,RegionID,'Displacement',
Dval)
structuralBC(structuralmodel,RegionType,RegionID,'XDisplacement',
XDval,'YDisplacement',YDval,'ZDisplacement',ZDval)
structuralBC(structuralmodel,RegionType,RegionID,'XDisplacement',
XDval,Name,Value)
structuralBC(structuralmodel,RegionType,RegionID,'YDisplacement',
YDval,Name,Value)
structuralBC(structuralmodel,RegionType,RegionID,'ZDisplacement',
ZDval,Name,Value)
Description
structuralBC(structuralmodel,RegionType,RegionID,'Constraint',Cval)
specifies one of the standard structural boundary constraints. Here, Cval can be
'fixed', 'free', 'roller', or 'symmetric'. The default value is 'free'.
Avoid using 'symmetric' for transient and modal analysis, since symmetric constraint
can prevent participation of some structural modes.
structuralBC(structuralmodel,RegionType,RegionID,'Displacement',
Dval) enforces displacement on the boundary of type RegionType with RegionID ID
numbers.
5-949
5 Functions — Alphabetical List
structuralBC(structuralmodel,RegionType,RegionID,'XDisplacement',
XDval,'YDisplacement',YDval,'ZDisplacement',ZDval) specifies the x-, y-, and
z-components of the enforced displacement.
structuralBC does not require you to specify all three components. Depending on your
structural analysis problem, you can specify one or more components by picking the
corresponding arguments and omitting others.
structuralBC(structuralmodel,RegionType,RegionID,'XDisplacement',
XDval,Name,Value)specifies the form and duration of the time-varying value of the x-
component of the enforced displacement.
structuralBC(structuralmodel,RegionType,RegionID,'YDisplacement',
YDval,Name,Value) specifies the form and duration of the time-varying value of the y-
component of the enforced displacement.
structuralBC(structuralmodel,RegionType,RegionID,'ZDisplacement',
ZDval,Name,Value) specifies the form and duration of the time-varying value of the z-
component of the enforced displacement.
Use this syntax with any of the input arguments from previous syntaxes.
bc = structuralBC( ___ ) returns the structural boundary condition object using any
of the input arguments from previous syntaxes.
Examples
structuralModel = createpde('structural','static-solid');
5-950
structuralBC
Assign the geometry to the structural model and plot the geometry.
structuralModel.Geometry = gm;
pdegplot(structuralModel,'CellLabels','on','FaceAlpha',0.4)
For each metal, specify the Young's modulus and Poisson's ratio.
structuralProperties(structuralModel,'Cell',1,'YoungsModulus',110E9, ...
'PoissonsRatio',0.28);
structuralProperties(structuralModel,'Cell',2,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3);
5-951
5 Functions — Alphabetical List
structuralBC(structuralModel,'Face',[1,4],'Constraint','fixed')
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: [1 4]
Vectorized: 'off'
Boundary Loads
SurfaceTraction: []
Pressure: []
TranslationalStiffness: []
structuralBoundaryLoad(structuralModel,'Face',[2,5],'SurfaceTraction',[0;0;100])
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: [2 5]
Vectorized: 'off'
Boundary Loads
SurfaceTraction: [3x1 double]
Pressure: []
5-952
structuralBC
TranslationalStiffness: []
Specify Displacements
structuralModel = createpde('structural','static-solid');
gm = multicuboid(0.2,0.1,0.05);
Assign the geometry to the structural model and plot the geometry.
structuralModel.Geometry = gm;
pdegplot(structuralModel,'FaceLabels','on','FaceAlpha',0.5)
5-953
5 Functions — Alphabetical List
structuralProperties(structuralModel,'YoungsModulus',74e9,...
'PoissonsRatio',0.42,...
'MassDensity',19.29e3);
structuralBodyLoad(structuralModel,'GravitationalAcceleration',[0;0;-9.8]);
structuralBC(structuralModel,'Face',5,'Constraint','fixed');
5-954
structuralBC
structuralBC(structuralModel,'Face',3,'ZDisplacement',0.0001);
generateMesh(structuralModel);
R = solve(structuralModel);
pdeplot3D(structuralModel,'ColorMapData',R.Stress.sxx,'Deformation',R.Displacement)
5-955
5 Functions — Alphabetical List
Now specify all three displacements on the same face. Here, z-displacement is the same,
but x- and y-displacements are both zero. Face 3 cannot move in the x- and y-directions.
structuralBC(structuralModel,'Face',3,'Displacement',[0;0;0.0001]);
R = solve(structuralModel);
pdeplot3D(structuralModel,'ColorMapData',R.Stress.sxx,'Deformation',R.Displacement)
structuralBC(structuralModel,'Face',3,'XDisplacement',0, ...
'YDisplacement',0, ...
'ZDisplacement',0.0001);
5-956
structuralBC
R = solve(structuralModel);
pdeplot3D(structuralModel,'ColorMapData',R.Stress.sxx,'Deformation',R.Displacement)
5-957
5 Functions — Alphabetical List
gm = multicuboid(0.06,0.005,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
Specify Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3, ...
'MassDensity',7800);
structuralBC(structuralmodel,'Face',5,'Constraint','fixed');
5-958
structuralBC
Apply a sinusoidal displacement along y-direction on the end opposite to the fixed end of
the beam.
yDisplacementFunc = @(location,state) ones(size(location.y))*1E-4*sin(50*state.time);
structuralBC(structuralmodel,'Face',3,'YDisplacement',yDisplacementFunc)
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 3
Vectorized: 'off'
Boundary Loads
SurfaceTraction: []
Pressure: []
TranslationalStiffness: []
5-959
5 Functions — Alphabetical List
gm = multicuboid(0.06,0.005,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
Specify the Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3, ...
'MassDensity',7800);
5-960
structuralBC
structuralBC(structuralmodel,'Face',5,'Constraint','fixed');
Apply a sinusoidal displacement along y-direction on the end opposite to the fixed end of
the beam.
structuralBC(structuralmodel,'Face',3,'YDisplacement',1E-4,'Frequency',50);
Input Arguments
structuralmodel — Structural model
StructuralModel object
Geometric region type, specified as 'Edge' for a 2-D model or 'Face' for a 3-D model.
Example: structuralBC(structuralmodel,'Face',[2,5],'XDisplacement',
0.1)
Data Types: char | string
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot, as shown in “Create Geometry and Remove Face Boundaries” on page 2-13 or
“STL File Import” on page 2-47.
Example: structuralBC(structuralmodel,'Face',[2,5],'XDisplacement',
0.01)
Data Types: double
5-961
5 Functions — Alphabetical List
5-962
structuralBC
Example: structuralBC(structuralmodel,'Face',[2,5],'ZDisplacement',
0.01)
Data Types: double | function_handle
You can model a rectangular, triangular, and trapezoidal displacement pulses. If the start
time is 0, you can omit specifying it.
5-963
5 Functions — Alphabetical List
You can model a harmonic displacement by specifying its frequency and initial phase. If
the initial phase is 0, you can omit specifying it.
5-964
structuralBC
Example: structuralBC(structuralmodel,'Face',[2,5],'XDisplacement',
0.01,'RiseTime',0.5,'FallTime',0.5,'EndTime',3)
Rectangular, Triangular, or Trapezoidal Pulse
Start time for the displacement component, specified as a positive number. Specify this
argument only for transient structural models.
structuralBC(structuralmodel,'Face',[2,5],'XDisplacement',
0.01,'StartTime',1,'EndTime',3)
Data Types: double
End time for the displacement component, specified as a positive number equal or greater
than the start time value. Specify this argument only for transient structural models.
5-965
5 Functions — Alphabetical List
structuralBC(structuralmodel,'Face',[2,5],'XDisplacement',
0.01,'StartTime',1,'EndTime',3)
Data Types: double
Rise time for the displacement component, specified as a positive number. Specify this
argument only for transient structural models.
structuralBC(structuralmodel,'Face',[2,5],'XDisplacement',
0.01,'RiseTime',0.5,'FallTime',0.5,'EndTime',3)
Data Types: double
Fall time for the displacement component, specified as a positive number. Specify this
argument only for transient structural models.
structuralBC(structuralmodel,'Face',[2,5],'XDisplacement',
0.01,'RiseTime',0.5,'FallTime',0.5,'EndTime',3)
Data Types: double
Harmonic Displacement
structuralBC(structuralmodel,'Face','XDisplacement',
0.01,'Frequency',25)
Data Types: double
5-966
structuralBC
structuralBC(structuralmodel,'Face',[2,5],'XDisplacement',
0.01,'Frequency',25,'Phase',pi/6)
Data Types: double
Output Arguments
bc — Handle to boundary condition
StructuralBC object
Tips
• Specify as many boundary conditions as needed to restrain all rigid body motions. Not
restraining all rigid body motions means that the entire geometry can freely rotate or
move. The resulting linear system of equations is singular. The system can take a long
time to converge, or it might not converge at all. If the system converges, the solution
includes a large rigid body motion in addition to deformation.
See Also
StructuralModel | structuralBodyLoad | structuralBoundaryLoad |
structuralDamping | structuralProperties
Introduced in R2017b
5-967
5 Functions — Alphabetical List
StructuralBC Properties
Boundary condition or boundary load for structural analysis model
Description
A StructuralBC object specifies the type of PDE boundary condition or boundary load
on a set of geometry boundaries. A StructuralModel object contains a vector of
StructuralBC objects in its BoundaryConditions.StructuralBCAssignments
property.
To specify boundary conditions for your model, use the structuralBC function. To
specify boundary loads, use structuralBoundaryLoad.
Properties
Properties of StructuralBC
Geometric region type, returned as 'Face' for 3-D geometry or 'Edge' for 2-D
geometry.
Data Types: char
Geometric region ID, returned as a vector of positive integers. Find the region IDs using
pdegplot with 'FaceLabels' (3-D) or 'EdgeLabels' (2-D) set to 'on'.
Data Types: double
Vectorized function evaluation, returned as 'off' or 'on'. This evaluation applies when
you pass a function handle as an argument. To save time in the function handle
5-968
StructuralBC Properties
evaluation, specify 'on', assuming that your function handle computes in a vectorized
fashion. See “Vectorization” (MATLAB). For details of this evaluation, see “Nonconstant
Boundary Conditions” on page 2-186.
Data Types: char
5-969
5 Functions — Alphabetical List
Boundary Loads
Normal and tangential distributed forces on the boundary (in global Cartesian
coordinates system), returned as a numeric vector or function handle. The numeric vector
must contain two elements for a 2-D model and three elements for a 3-D model. The
function must return a two-row matrix for a 2-D model and a three-row matrix for a 3-D
model. Each column of the matrix must correspond to the surface traction vector at the
boundary coordinates provided by the solver.
Data Types: double | function_handle
Pressure normal to the boundary, returned as a number or function handle. The function
must return a row vector with each column corresponding to value of pressure at the
boundary coordinates provided by the solver. A positive value of pressure acts in the
direction of the outward normal to the boundary.
Data Types: double | function_handle
Distributed spring stiffness for each translational direction used to model an elastic
foundation, returned as a numeric vector or function handle. The numeric vector must
contain two elements for a 2-D model and three elements for a 3-D model. The custom
function must return a two-row matrix for a 2-D model and a three-row matrix for a 3-D
5-970
StructuralBC Properties
model. Each column of this matrix corresponds to the stiffness vector at the boundary
coordinates provided by the solver.
Data Types: double | function_handle
See Also
findStructuralBC | structuralBC | structuralBoundaryLoad
Introduced in R2017b
5-971
5 Functions — Alphabetical List
structuralIC
Package: pde
Syntax
structuralIC(structuralmodel,'Displacement',u0,'Velocity',v0)
structuralIC( ___ RegionType,RegionID)
structuralIC(structuralmodel,Sresults)
structuralIC(structuralmodel,Sresults,iT)
struct_ic = structuralIC( ___ )
Description
structuralIC(structuralmodel,'Displacement',u0,'Velocity',v0) sets
initial displacement and velocity for the entire geometry.
Examples
5-972
structuralIC
Specify initial velocity values for the entire geometry and for a particular face.
structuralmodel = createpde('structural','transient-solid');
Create a geometry and include it into the model. Plot the geometry.
gm = multicuboid(0.06,0.005,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
5-973
5 Functions — Alphabetical List
Specify the zero initial velocity on the entire geometry. When you specify only the initial
velocity or initial displacement, structuralIC assumes that the omitted parameter is
zero. For example, here the initial displacement is also zero.
structuralIC(structuralmodel,'Velocity',[0;0;0])
ans =
GeometricStructuralICs with properties:
RegionType: 'Cell'
RegionID: 1
InitialDisplacement: []
InitialVelocity: [3x1 double]
ans =
GeometricStructuralICs with properties:
RegionType: 'Face'
RegionID: 2
InitialDisplacement: []
InitialVelocity: [3x1 double]
Create the geometry and include it into the model. Plot the geometry.
gm = multicuboid(0.06,0.005,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
5-974
structuralIC
structuralIC(structuralmodel,'Displacement',[0;0;0])
ans =
GeometricStructuralICs with properties:
RegionType: 'Cell'
RegionID: 1
InitialDisplacement: [3x1 double]
InitialVelocity: []
5-975
5 Functions — Alphabetical List
Now change the initial displacement in the z-direction on face 2 to a function of the
coordinates x and y:
Write the following function file. Save it to a location on your MATLAB® path.
M = length(location.x);
uinit = zeros(3,M);
structuralIC(structuralmodel,'Face',2,'Displacement',@initdisp)
ans =
GeometricStructuralICs with properties:
RegionType: 'Face'
RegionID: 2
InitialDisplacement: @initdisp
InitialVelocity: []
staticmodel = createpde('structural','static-solid');
Create the geometry and include it in the model. Plot the geometry.
5-976
structuralIC
gm = multicuboid(0.06,0.005,0.01);
staticmodel.Geometry = gm;
pdegplot(staticmodel,'FaceLabels','on','FaceAlpha',0.5)
view(50,20)
5-977
5 Functions — Alphabetical List
Generate a mesh.
generateMesh(dynamicmodel,'Hmax',0.02);
ans =
NodalStructuralICs with properties:
Input Arguments
structuralmodel — Transient structural model
StructuralModel object
u0 — Initial displacement
numeric vector | function handle
5-978
structuralIC
The function must return a two-row matrix for a 2-D model and a three-row matrix for a 3-
D model. Each column of the matrix corresponds to the initial displacement at the
coordinates provided by the solver. The approaches for using function handles to specify
initial conditions for StructuralModel and PDEModel are the same. For details about
nonconstant initial conditions for a PDEModel object, see “Nonconstant Initial
Conditions” on page 2-161.
Example: structuralIC(structuralmodel,'Face',[2,5],'Displacement',
[0;0;0.01])
Data Types: double | function_handle
v0 — Initial velocity
numeric vector | function handle
Initial velocity, specified as a numeric vector or function handle. A numeric vector must
contain two elements for a 2-D model and three elements for a 3-D model. The elements
represent the components of initial velocity.
The function must return a two-row matrix for a 2-D model and a three-row matrix for a 3-
D model. Each column of the matrix corresponds to the initial velocity at the coordinates
provided by the solver. The approaches for using function handles to specify initial
conditions for StructuralModel and PDEModel are the same. For details about
nonconstant initial conditions for a PDEModel object, see “Nonconstant Initial
Conditions” on page 2-161.
Example: structuralIC(structuralmodel,'Face',[2,5],'Displacement',
[0;0;0.01],'Velocity',[0;60;0])
Data Types: double | function_handle
When you apply multiple initial condition assignments, the solver uses these precedence
rules for determining the initial condition.
5-979
5 Functions — Alphabetical List
• For multiple assignments to the same geometric region, the solver uses the last
applied setting.
• For separate assignments to a geometric region and the boundaries of that region, the
solver uses the specified assignment on the region and chooses the assignment on the
boundary as follows. The solver gives an 'Edge' assignment precedence over a
'Face' assignment, even if you specify a 'Face' assignment after an 'Edge'
assignment. The precedence levels are 'Vertex (highest precedence), 'Edge',
'Face', 'Cell' (lowest precedence).
• For an assignment made with the results object, the solver uses that assignment
instead of all previous assignments.
Example: structuralIC(structuralmodel,'Face',[2,5],'Displacement',
[0;0;0.01],'Velocity',[0;60;0])
Data Types: char
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot, as shown in “Create Geometry and Remove Face Boundaries” on page 2-13 or
“STL File Import” on page 2-47.
Example: structuralIC(structuralmodel,'Face',[2,5],'Displacement',
[0;0;0.01],'Velocity',[0;60;0])
Data Types: double
iT — Time index
positive integer
5-980
structuralIC
Output Arguments
struct_ic — Handle to initial conditions
object
See Also
GeometricStructuralICs Properties | NodalStructuralICs Properties | StructuralModel |
findStructuralIC | structuralBC | structuralBodyLoad |
structuralBoundaryLoad | structuralDamping | structuralProperties
Introduced in R2018a
5-981
5 Functions — Alphabetical List
structuralDamping
Specify damping parameters for transient structural model
Syntax
structuralDamping(structuralmodel,'proportional','Alpha',a,'Beta',b)
ab = structuralDamping( ___ )
Description
structuralDamping(structuralmodel,'proportional','Alpha',a,'Beta',b)
specifies proportional (Rayleigh) damping parameters a and b for structuralmodel.
The second argument must be 'proportional'.
Examples
structuralModel = createpde('structural','transient-solid');
gm = importGeometry(structuralModel,'SquareBeam.STL');
pdegplot(structuralModel,'FaceAlpha',0.5)
5-982
structuralDamping
ans =
StructuralDampingAssignment with properties:
RegionType: 'Cell'
RegionID: 1
5-983
5 Functions — Alphabetical List
DampingModel: 'proportional'
Alpha: 10
Beta: 2
Input Arguments
a — Mass proportional damping
real number
Output Arguments
ab — Handle to damping parameters
StructuralDampingAssignment object
See Also
StructuralModel | solve | structuralBC | structuralBodyLoad |
structuralBoundaryLoad | structuralProperties
Introduced in R2018a
5-984
findStructuralDamping
findStructuralDamping
Package: pde
Syntax
dma = findStructuralDamping(structuralmodel.DampingModels)
Description
dma = findStructuralDamping(structuralmodel.DampingModels) returns the
damping model and its parameters assigned to the structural dynamics model. The
toolbox supports the proportional (Rayleigh) damping model. The parameters of this
damping model are the mass and stiffness proportional damping parameters.
Examples
structuralModel = createpde('structural','transient-solid');
importGeometry(structuralModel,'Block.stl');
pdegplot(structuralModel,'CellLabels','on')
5-985
5 Functions — Alphabetical List
Check the damping parameter assignment for structuralModel. Notice that the Beta
parameter is empty.
findStructuralDamping(structuralModel.DampingModels)
ans =
StructuralDampingAssignment with properties:
5-986
findStructuralDamping
RegionType: 'Cell'
RegionID: 1
DampingModel: 'proportional'
Alpha: 10
Beta: []
structuralDamping(structuralModel,'proportional','Alpha',10,'Beta',40);
findStructuralDamping(structuralModel.DampingModels)
ans =
StructuralDampingAssignment with properties:
RegionType: 'Cell'
RegionID: 1
DampingModel: 'proportional'
Alpha: 10
Beta: 40
Input Arguments
structuralmodel.DampingModels — Damping model
DampingModels property of StructuralModel object
5-987
5 Functions — Alphabetical List
Output Arguments
dma — Damping model assignment
StructuralDampingAssignment object
See Also
StructuralDampingAssignment Properties | structuralDamping
Introduced in R2018a
5-988
StructuralDampingAssignment Properties
StructuralDampingAssignment Properties
Damping assignment for a structural analysis model
Description
A StructuralDampingAssignment object contains the damping model and its
parameters for a structural analysis model. A StructuralModel container has a vector
of StructuralDampingAssignment objects in its
DampingModels.StructuralDampingAssignments property.
To set damping parameters for your structural model, use the structuralDamping
function.
Properties
Properties of StructuralDampingAssignment
Region type, returned as 'Face' for a 2-D region, or 'Cell' for a 3-D region.
Data Types: char
RegionID — Region ID
positive integer
Region ID, returned as a positive integer. The toolbox defines damping parameters for the
entire geometry.
Data Types: double
5-989
5 Functions — Alphabetical List
See Also
findStructuralDamping | structuralDamping
Introduced in R2018a
5-990
StructuralMaterialAssignment Properties
StructuralMaterialAssignment Properties
Structural material property assignments
Description
A StructuralMaterialAssignment object contains the description of material
properties of a structural analysis model. A StructuralModel container has a vector of
StructuralMaterialAssignment objects in its
MaterialProperties.MaterialAssignments property.
To create the material properties assignments for your structural analysis model, use the
structuralProperties function.
Properties
Properties of StructuralMaterialAssignment
Region type, returned as 'Face' for a 2-D region, or 'Cell' for a 3-D region.
Data Types: char
RegionID — Region ID
vector of positive integers
5-991
5 Functions — Alphabetical List
Mass density of the material, returned as a positive number. This property is required
when modeling gravitational effects.
Data Types: double
See Also
findStructuralProperties | structuralProperties
Introduced in R2017b
5-992
structuralBodyLoad
structuralBodyLoad
Package: pde
Syntax
structuralBodyLoad(structuralmodel,'GravitationalAcceleration',
GAval)
structuralBodyLoad(structuralmodel,'Temperature',Tval)
structuralBodyLoad(structuralmodel,'Temperature',Tresults)
structuralBodyLoad(structuralmodel,'Temperature',
Tresults,'TimeStep',iT)
Description
structuralBodyLoad(structuralmodel,'GravitationalAcceleration',
GAval) specifies acceleration due to gravity as a body load for a static or transient
structural model. Structural models for modal analysis cannot have body loads.
structuralBodyLoad(structuralmodel,'Temperature',Tval) specifies a
thermal load on a static structural analysis model.
Tip If Tval is the temperature itself, and not a change in temperature, you also must
specify a reference temperature. To specify it, assign the reference temperature value to
structuralmodel.ReferenceTemperature. For details, see StructuralModel.
5-993
5 Functions — Alphabetical List
structuralBodyLoad(structuralmodel,'Temperature',
Tresults,'TimeStep',iT) uses the transient thermal analysis results Tresults and
the time step index iT to specify a thermal load on a static structural analysis model.
bodyLoad = structuralBodyLoad( ___ ) returns the body load object, using the
input arguments from any of the previous syntaxes.
Examples
structuralModel = createpde('structural','static-solid');
gm = multicuboid(0.5,0.1,0.1);
structuralModel.Geometry = gm;
pdegplot(structuralModel,'FaceAlpha',0.5)
5-994
structuralBodyLoad
Specify the Young's modulus, Poisson's ratio, and mass density. The mass density value is
required for modeling gravitational effects.
structuralProperties(structuralModel,'YoungsModulus',210E3, ...
'PoissonsRatio',0.3, ...
'MassDensity',2.7E-6);
structuralBodyLoad(structuralModel,'GravitationalAcceleration',[0;0;-9.8])
ans =
BodyLoadAssignment with properties:
5-995
5 Functions — Alphabetical List
RegionType: 'Cell'
RegionID: 1
GravitationalAcceleration: [3x1 double]
Temperature: []
TimeStep: []
Specify a constant temperature rise for a thermal stress analysis of a bimetallic cantilever
beam.
structuralmodel = createpde('structural','static-solid');
gm = multicuboid(0.5,0.04,[0.03,0.03],'Zoffset',[0,0.03]);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'CellLabels','on')
5-996
structuralBodyLoad
Set the reference temperature. This temperature corresponds to the state of zero thermal
stress of the model.
structuralmodel.ReferenceTemperature = 20
structuralmodel =
StructuralModel with properties:
AnalysisType: 'static-solid'
Geometry: [1x1 DiscreteGeometry]
MaterialProperties: []
BodyLoads: []
BoundaryConditions: []
ReferenceTemperature: 20
5-997
5 Functions — Alphabetical List
Mesh: []
structuralBodyLoad(structuralmodel,'Temperature',300)
ans =
BodyLoadAssignment with properties:
RegionType: 'Cell'
RegionID: [1 2]
GravitationalAcceleration: []
Temperature: 300
TimeStep: []
Specify a thermal load using the solution from a steady-state thermal analysis on the
same geometry and mesh.
thermalmodel = createpde('thermal','steadystate');
gm = multicuboid(0.5,0.1,0.05);
thermalmodel.Geometry = gm;
pdegplot(thermalmodel,'FaceLabels','on','FaceAlpha',0.5)
5-998
structuralBodyLoad
Generate a mesh.
generateMesh(thermalmodel);
thermalProperties(thermalmodel,'ThermalConductivity',5e-3);
Specify constant temperatures on the left and right ends on the beam.
thermalBC(thermalmodel,'Face',3,'Temperature',100);
thermalBC(thermalmodel,'Face',5,'Temperature',0);
5-999
5 Functions — Alphabetical List
internalHeatSource(thermalmodel,10);
thermalresults = solve(thermalmodel)
thermalresults =
SteadyStateThermalResults with properties:
pdeplot3D(thermalmodel,'ColorMapData',thermalresults.Temperature)
5-1000
structuralBodyLoad
Apply the solution of the thermal model analysis as a body load for the structural model.
structuralBodyLoad(structuralmodel,'Temperature',thermalresults)
ans =
BodyLoadAssignment with properties:
5-1001
5 Functions — Alphabetical List
RegionType: 'Cell'
RegionID: 1
GravitationalAcceleration: []
Temperature: [1x1 pde.SteadyStateThermalResults]
TimeStep: []
Specify a thermal load using the solution from a transient thermal analysis on the same
geometry and mesh.
thermalmodel = createpde('thermal','transient');
gm = multicuboid(0.5,0.1,0.05);
thermalmodel.Geometry = gm;
pdegplot(thermalmodel,'FaceLabels','on','FaceAlpha',0.5)
5-1002
structuralBodyLoad
Generate a mesh.
generateMesh(thermalmodel);
thermalProperties(thermalmodel,'ThermalConductivity',5e-3, ...
'MassDensity',2.7*10^(-6), ...
'SpecificHeat',10);
Specify the constant temperatures on the left and right ends on the beam.
thermalBC(thermalmodel,'Face',3,'Temperature',100);
thermalBC(thermalmodel,'Face',5,'Temperature',0);
5-1003
5 Functions — Alphabetical List
internalHeatSource(thermalmodel,10);
thermalIC(thermalmodel,0);
tlist = [0:1e-4:2e-4];
thermalresults = solve(thermalmodel,tlist)
thermalresults =
TransientThermalResults with properties:
for n = 1:numel(thermalresults.SolutionTimes)
figure
pdeplot3D(thermalmodel,'ColorMapData',thermalresults.Temperature(:,n))
title(['Time = ' num2str(tlist(n))])
caxis([0 100])
end
5-1004
structuralBodyLoad
5-1005
5 Functions — Alphabetical List
5-1006
structuralBodyLoad
structuralmodel = createpde('structural','static-solid');
structuralmodel.Geometry = gm;
Apply the solution of the thermal model analysis as a body load for the structural model.
By default, structuralBodyLoad uses the thermal model solution for the last time step.
structuralBodyLoad(structuralmodel,'Temperature',thermalresults);
5-1007
5 Functions — Alphabetical List
You also can specify the time step you want to use. For example, apply the thermal model
solution for the second time step as a body load for the structural model.
structuralBodyLoad(structuralmodel,'Temperature',thermalresults, ...
'TimeStep',2);
Input Arguments
structuralmodel — Static or transient structural model
StructuralModel object
Constant thermal load on a static structural model, specified as a real number. Tval must
be specified in units consistent with the geometry and material properties units.
Example: structuralBodyLoad(structuralmodel,'Temperature',300)
Data Types: double
5-1008
structuralBodyLoad
Thermal model solution applied as a body load on a static structural model, specified as a
StaticThermalResults or TransientThermalResults object. Create Tresults by
using solve.
Example: Tresults = solve(thermalmodel);
structuralBodyLoad(structuralmodel,'Temperature',Tresults)
iT — Time index
positive integer
Output Arguments
bodyLoad — Handle to body load
BodyLoadAssignment object
See Also
StructuralModel | structuralBC | structuralBoundaryLoad |
structuralDamping | structuralProperties
Introduced in R2017b
5-1009
5 Functions — Alphabetical List
structuralBoundaryLoad
Package: pde
Syntax
structuralBoundaryLoad(structuralmodel,RegionType,
RegionID,'SurfaceTraction',STval,'Pressure',
Pval,'TranslationalStiffness',TSval)
structuralBoundaryLoad( ___ ,'Pressure',Pval,Name,Value)
structuralBoundaryLoad( ___ ,'Vectorized','on')
boundaryLoad = structuralBoundaryLoad( ___ )
Description
structuralBoundaryLoad(structuralmodel,RegionType,
RegionID,'SurfaceTraction',STval,'Pressure',
Pval,'TranslationalStiffness',TSval) specifies surface traction, pressure, and
translational stiffness on the boundary of type RegionType with RegionID ID numbers.
You can specify translational stiffness for a static, transient, or modal analysis. To specify
pressure or surface traction, structuralmodel must be static or transient. Structural
models for modal analysis cannot have pressure or surface traction.
structuralBoundaryLoad does not require you to specify all three body loads.
Depending on your structural analysis problem, you can specify one or more boundary
loads by picking the corresponding arguments and omitting others.
5-1010
structuralBoundaryLoad
Use this syntax with any of the input arguments from previous syntaxes.
Examples
structuralModel = createpde('structural','static-solid');
gm = multicylinder([0.01,0.015],0.05);
Assign the geometry to the structural model and plot the geometry.
structuralModel.Geometry = gm;
pdegplot(structuralModel,'CellLabels','on','FaceAlpha',0.4)
5-1011
5 Functions — Alphabetical List
For each metal, specify the Young's modulus and Poisson's ratio.
structuralProperties(structuralModel,'Cell',1,'YoungsModulus',110E9, ...
'PoissonsRatio',0.28);
structuralProperties(structuralModel,'Cell',2,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3);
ans =
StructuralBC with properties:
RegionType: 'Face'
5-1012
structuralBoundaryLoad
RegionID: [1 4]
Vectorized: 'off'
Boundary Loads
SurfaceTraction: []
Pressure: []
TranslationalStiffness: []
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: [2 5]
Vectorized: 'off'
Boundary Loads
SurfaceTraction: [3x1 double]
Pressure: []
TranslationalStiffness: []
5-1013
5 Functions — Alphabetical List
structuralModel = createpde('structural','static-solid');
Assign the geometry to the structural model and plot the geometry.
structuralModel.Geometry = gm;
pdegplot(structuralModel,'FaceLabels','on','FaceAlpha',0.5)
5-1014
structuralBoundaryLoad
The bottom face of the block is resting on an elastic foundation (a spring). To model this
foundation, specify the translational stiffness.
structuralBoundaryLoad(structuralModel,'Face',1,'TranslationalStiffness',[0;0;30])
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 1
Vectorized: 'off'
Boundary Loads
SurfaceTraction: []
Pressure: []
TranslationalStiffness: [3x1 double]
Use a function handle to specify a harmonically varying pressure at the center of a thin 3-
D plate.
structuralmodel = createpde('structural','transient-solid');
Create a geometry consisting of a thin 3-D plate and a small plate in the center. Include
the geometry in the model and plot it.
gm = multicuboid([5,0.05],[5,0.05],0.01);
structuralmodel.Geometry=gm;
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
5-1015
5 Functions — Alphabetical List
Zoom in to see the face labels on the small plate in the center.
figure
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.25)
axis([-0.2 0.2 -0.2 0.2 -0.1 0.1])
5-1016
structuralBoundaryLoad
Specify the Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9,...
'PoissonsRatio',0.3,...
'MassDensity',7800);
Specify that all faces on the periphery of the thin 3-D plate are fixed boundaries.
structuralBC(structuralmodel,'Constraint','fixed','Face',5:8);
Apply a harmonically varying pressure load on the small face at the center of the plate.
plungerLoad = @(location,state)5E7.*sin(25.*state.time);
structuralBoundaryLoad(structuralmodel,'Face',12,'Pressure',plungerLoad)
5-1017
5 Functions — Alphabetical List
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 12
Vectorized: 'off'
Boundary Loads
SurfaceTraction: []
Pressure: @(location,state)5E7.*sin(25.*state.time)
TranslationalStiffness: []
Specify a harmonically varying pressure at the center of a thin 3-D plate by specifying its
frequency.
structuralmodel = createpde('structural','transient-solid');
Create a geometry consisting of a thin 3-D plate and a small plate in the center. Include
the geometry in the model and plot it.
5-1018
structuralBoundaryLoad
gm = multicuboid([5,0.05],[5,0.05],0.01);
structuralmodel.Geometry=gm;
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.5)
Zoom in to see the face labels on the small plate in the center.
figure
pdegplot(structuralmodel,'FaceLabels','on','FaceAlpha',0.25)
axis([-0.2 0.2 -0.2 0.2 -0.1 0.1])
5-1019
5 Functions — Alphabetical List
Specify the Young's modulus, Poisson's ratio, and mass density of the material.
structuralProperties(structuralmodel,'YoungsModulus',210E9,...
'PoissonsRatio',0.3,...
'MassDensity',7800);
Specify that all faces on the periphery of the thin 3-D plate are fixed boundaries.
structuralBC(structuralmodel,'Constraint','fixed','Face',5:8);
Apply a harmonically varying pressure load on the small face at the center of the plate.
structuralBoundaryLoad(structuralmodel,'Face',12,'Pressure',5E7,'Frequency',25)
5-1020
structuralBoundaryLoad
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 12
Vectorized: 'off'
Boundary Loads
SurfaceTraction: []
Pressure: 50000000
TranslationalStiffness: []
structuralModel = createpde('structural','transient-solid');
importGeometry(structuralModel,'BracketWithHole.stl');
pdegplot(structuralModel,'FaceLabels','on')
view(-20,10)
5-1021
5 Functions — Alphabetical List
structuralProperties(structuralModel,'YoungsModulus',200e9, ...
'PoissonsRatio',0.3,...
'MassDensity',7800);
structuralBC(structuralModel,'Face',4,'Constraint','fixed');
Apply a rectangular pressure pulse on face 7 in the direction normal to the face.
structuralBoundaryLoad(structuralModel,'Face',7,'Pressure',10^5,...
'StartTime',0.1,'EndTime',0.5)
5-1022
structuralBoundaryLoad
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 7
Vectorized: 'off'
Boundary Loads
SurfaceTraction: []
Pressure: 100000
TranslationalStiffness: []
Input Arguments
structuralmodel — Static or transient structural model
StructuralModel object
5-1023
5 Functions — Alphabetical List
Geometric region type, specified as 'Edge' for a 2-D model or 'Face' for a 3-D model.
Example: structuralBoundaryLoad(structuralmodel,'Face',
[2,5],'SurfaceTraction',[0,0,100])
Data Types: char | string
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot, as shown in “Create Geometry and Remove Face Boundaries” on page 2-13 or
“STL File Import” on page 2-47.
Example: structuralBoundaryLoad(structuralmodel,'Face',
[2,5],'SurfaceTraction',[0,0,100])
Data Types: double
Distributed normal and tangential forces on the boundary, resolved along the global
Cartesian coordinate system, specified as a numeric vector or function handle. A numeric
vector must contain two elements for a 2-D model and three elements for a 3-D model.
The function must return a two-row matrix for a 2-D model and a three-row matrix for a 3-
D model. Each column of the matrix must correspond to the surface traction vector at the
boundary coordinates provided by the solver. In case of a transient structural model,
STval also can be a function of time.
Example: structuralBoundaryLoad(structuralmodel,'Face',
[2,5],'SurfaceTraction',[0;0;100])
Data Types: double | function_handle
Pressure normal to the boundary, specified as a number or function handle. The function
must return a row vector with each column corresponding to the value of pressure at the
boundary coordinates provided by the solver. In case of a transient structural model,
5-1024
structuralBoundaryLoad
Pval also can be a function of time. A positive value of pressure acts into the boundary
(for example, compression), while a negative value pressure acts away from the boundary
(for example, suction).
Example: structuralBoundaryLoad(structuralmodel,'Face',
[2,5],'Pressure',10^5)
Data Types: double | function_handle
Distributed spring stiffness for each translational direction used to model elastic
foundation, specified as a numeric vector or function handle. A numeric vector must
contain two elements for a 2-D model and three elements for a 3-D model. The custom
function must return a two-row matrix for a 2-D model and a three-row matrix for a 3-D
model. Each column of this matrix corresponds to the stiffness vector at the boundary
coordinates provided by the solver. In case of a transient structural model, TSval also
can be a function of time.
Example: structuralBoundaryLoad(structuralmodel,'Edge',
[2,5],'TranslationalStiffness',[0;5500])
Data Types: double | function_handle
You can model a rectangular, triangular, and trapezoidal pressure pulses. If the start time
is 0, you can omit specifying it.
5-1025
5 Functions — Alphabetical List
You can model a harmonic pressure load by specifying its frequency and initial phase. If
the initial phase is 0, you can omit specifying it.
5-1026
structuralBoundaryLoad
Example: structuralBoundaryLoad(structuralmodel,'Face',
[2,5],'Pressure',10^5,'RiseTime',0.5,'FallTime',0.5,'EndTime',3)
Rectangular, Triangular, or Trapezoidal Pulse
Start time for pressure load, specified as a positive number. Specify this argument only
for transient structural models.
structuralBoundaryLoad(structuralmodel,'Face',[2,5],'Pressure',
10^5,'StartTime',1,'EndTime',3)
Data Types: double
End time for pressure load, specified as a positive number equal or greater than the start
time value. Specify this argument only for transient structural models.
5-1027
5 Functions — Alphabetical List
structuralBoundaryLoad(structuralmodel,'Face',[2,5],'Pressure',
10^5,'StartTime',1,'EndTime',3)
Data Types: double
Rise time for pressure load, specified as a positive number. Specify this argument only for
transient structural models.
structuralBoundaryLoad(structuralmodel,'Face',[2,5],'Pressure',
10^5,'RiseTime',0.5,'FallTime',0.5,'EndTime',3)
Data Types: double
Fall time for pressure load, specified as a positive number. Specify this argument only for
transient structural models.
structuralBoundaryLoad(structuralmodel,'Face',[2,5],'Pressure',
10^5,'RiseTime',0.5,'FallTime',0.5,'EndTime',3)
Data Types: double
Harmonic Pressure Load
structuralBoundaryLoad(structuralmodel,'Face',[2,5],'Pressure',
10^5,'Frequency',25)
Data Types: double
5-1028
structuralBoundaryLoad
structuralBoundaryLoad(structuralmodel,'Face',[2,5],'Pressure',
10^5,'Frequency',25,'Phase',pi/6)
Data Types: double
Output Arguments
boundaryLoad — Handle to boundary load
StructuralBC object
See Also
StructuralModel | structuralBC | structuralBodyLoad | structuralDamping |
structuralProperties
Introduced in R2017b
5-1029
5 Functions — Alphabetical List
StructuralModel
Structural model object
Description
A StructuralModel object contains information about a structural analysis problem:
the geometry, material properties, damping parameters, body loads, boundary loads,
boundary constraints, initial displacement and velocity, and mesh.
Creation
To create a StructuralModel object, use createpde, specifying the first argument
'structural'.
Properties
AnalysisType — Type of structural analysis
'static-solid' | 'static-planestress' | 'static-planestrain' |
'transient-solid' | 'transient-planestress' | 'transient-planestrain' |
'modal-solid' | 'modal-planestress' | 'modal-planestrain'
Static analysis:
Transient analysis:
5-1030
StructuralModel
Modal analysis:
To create the material properties assignments for your structural analysis model, use the
structuralProperties function.
To create body load assignments for your structural analysis model, use the
structuralBodyLoad function.
5-1031
5 Functions — Alphabetical List
To specify boundary conditions for your model, use the structuralBC function. To
specify boundary loads, use structuralBoundaryLoad.
To set damping parameters for your structural model, use the structuralDamping
function.
To specify the reference temperature for a thermal load in your static structural model,
assign the property value directly, for example,
structuralmodel.ReferenceTemperature = 10. To specify the thermal load itself,
use the structuralBodyLoad function.
Data Types: double
5-1032
StructuralModel
To set initial conditions for your transient structural model, use the structuralIC
function.
Mesh for solution, returned as a FEMesh object. For property details, see FEMesh.
Object Functions
geometryFromEdges Create 2-D geometry
geometryFromMesh Create geometry from mesh
importGeometry Import geometry from STL data
structuralBC Specify boundary conditions for structural model
structuralBodyLoad Specify body load for structural model
structuralBoundaryLoad Specify boundary loads for structural model
structuralIC Set initial conditions for a transient structural model
structuralProperties Assign structural properties of material for structural model
solve Solve heat transfer or structural analysis problem
Examples
structuralModel = createpde('structural','static-solid')
structuralModel =
StructuralModel with properties:
AnalysisType: 'static-solid'
Geometry: []
MaterialProperties: []
BodyLoads: []
BoundaryConditions: []
ReferenceTemperature: []
5-1033
5 Functions — Alphabetical List
Mesh: []
gm = multicuboid(0.5,0.1,0.1);
structuralModel.Geometry = gm;
pdegplot(structuralModel,'FaceAlpha',0.5)
structuralProperties(structuralModel,'Cell',1,'YoungsModulus',210E3, ...
'PoissonsRatio',0.3, ...
'MassDensity',2.7E-6)
5-1034
StructuralModel
ans =
StructuralMaterialAssignment with properties:
RegionType: 'Cell'
RegionID: 1
YoungsModulus: 210000
PoissonsRatio: 0.3000
MassDensity: 2.7000e-06
CTE: []
structuralBodyLoad(structuralModel,'GravitationalAcceleration',[0;0;-9.8])
ans =
BodyLoadAssignment with properties:
RegionType: 'Cell'
RegionID: 1
GravitationalAcceleration: [3x1 double]
Temperature: []
TimeStep: []
structuralBC(structuralModel,'Face',6,'Constraint','fixed')
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 6
Vectorized: 'off'
Boundary Loads
SurfaceTraction: []
5-1035
5 Functions — Alphabetical List
Pressure: []
TranslationalStiffness: []
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 5
Vectorized: 'off'
Boundary Loads
SurfaceTraction: [3x1 double]
Pressure: []
TranslationalStiffness: []
Generate a mesh.
generateMesh(structuralModel)
ans =
FEMesh with properties:
5-1036
StructuralModel
structuralModel =
StructuralModel with properties:
AnalysisType: 'static-solid'
Geometry: [1x1 DiscreteGeometry]
MaterialProperties: [1x1 StructuralMaterialAssignmentRecords]
BodyLoads: [1x1 BodyLoadAssignmentRecords]
BoundaryConditions: [1x1 StructuralBCRecords]
ReferenceTemperature: []
Mesh: [1x1 FEMesh]
See Also
createpde | generateMesh | geometryFromEdges | geometryFromMesh |
importGeometry | pdegplot | pdeplot | pdeplot3D | solve | structuralBC |
structuralBodyLoad | structuralBoundaryLoad | structuralProperties
Introduced in R2017b
5-1037
5 Functions — Alphabetical List
structuralProperties
Package: pde
Syntax
structuralProperties(structuralmodel,'YoungsModulus',
YMval,'PoissonsRatio',PRval)
structuralProperties( ___ ,'MassDensity',MDval)
structuralProperties( ___ ,'CTE',CTEval)
structuralProperties( ___ ,RegionType,RegionID)
mtl = structuralProperties( ___ )
Description
structuralProperties(structuralmodel,'YoungsModulus',
YMval,'PoissonsRatio',PRval) assigns the Young's modulus and Poisson's ratio for
the entire geometry. Use this syntax if your model is static and does not account for
gravitational and thermal effects.
Tip A structural model supports only homogeneous isotropic materials. Therefore, all
material properties must be numeric scalars.
5-1038
structuralProperties
Examples
structuralModel = createpde('structural','static-solid');
importGeometry(structuralModel,'BracketWithHole.stl');
pdegplot(structuralModel,'FaceAlpha',0.5)
5-1039
5 Functions — Alphabetical List
structuralProperties(structuralModel,'YoungsModulus',200e9, ...
'PoissonsRatio',0.3, ...
'MassDensity',7800)
ans =
StructuralMaterialAssignment with properties:
RegionType: 'Cell'
RegionID: 1
YoungsModulus: 2.0000e+11
PoissonsRatio: 0.3000
MassDensity: 7800
5-1040
structuralProperties
CTE: []
structuralModel = createpde('structural','modal-solid');
gm = multicuboid(0.5,0.1,0.1);
structuralModel.Geometry = gm;
pdegplot(structuralModel,'FaceAlpha',0.5)
5-1041
5 Functions — Alphabetical List
structuralProperties(structuralModel,'YoungsModulus',210E3, ...
'PoissonsRatio',0.3, ...
'MassDensity',2.7E-6)
ans =
StructuralMaterialAssignment with properties:
RegionType: 'Cell'
RegionID: 1
YoungsModulus: 210000
PoissonsRatio: 0.3000
MassDensity: 2.7000e-06
5-1042
structuralProperties
CTE: []
Specify the coefficients of thermal expansion for a bimetallic cantilever beam. The bottom
layer is steel. The top layer is copper.
structuralmodel = createpde('structural','static-solid');
gm = multicuboid(0.5,0.04,[0.03,0.03],'Zoffset',[0,0.03]);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,'CellLabels','on')
5-1043
5 Functions — Alphabetical List
Specify the Young's modulus, Poisson's ratio, and coefficient of thermal expansion for the
bottom cell C1.
structuralProperties(structuralmodel,'Cell',1','YoungsModulus',210e9, ...
'PoissonsRatio',0.28, ...
'CTE',1.3e-5)
ans =
StructuralMaterialAssignment with properties:
RegionType: 'Cell'
RegionID: 1
YoungsModulus: 2.1000e+11
PoissonsRatio: 0.2800
5-1044
structuralProperties
MassDensity: []
CTE: 1.3000e-05
Specify the Young's modulus, Poisson's ratio, and coefficient of thermal expansion for the
top cell C2.
structuralProperties(structuralmodel,'Cell',2','YoungsModulus',110e9, ...
'PoissonsRatio',0.37, ...
'CTE',2.4e-5)
ans =
StructuralMaterialAssignment with properties:
RegionType: 'Cell'
RegionID: 2
YoungsModulus: 1.1000e+11
PoissonsRatio: 0.3700
MassDensity: []
CTE: 2.4000e-05
structuralModel = createpde('structural','static-solid');
gm = multicylinder([0.01,0.015],0.05);
Assign the geometry to the structural model and plot the geometry.
structuralModel.Geometry = gm;
pdegplot(structuralModel,'CellLabels','on','FaceAlpha',0.4)
5-1045
5 Functions — Alphabetical List
Specify the Young's modulus and Poisson's ratio for each metal.
structuralProperties(structuralModel,'Cell',1,'YoungsModulus',110E9, ...
'PoissonsRatio',0.28)
ans =
StructuralMaterialAssignment with properties:
RegionType: 'Cell'
RegionID: 1
YoungsModulus: 1.1000e+11
PoissonsRatio: 0.2800
MassDensity: []
5-1046
structuralProperties
CTE: []
structuralProperties(structuralModel,'Cell',2,'YoungsModulus',210E9, ...
'PoissonsRatio',0.3)
ans =
StructuralMaterialAssignment with properties:
RegionType: 'Cell'
RegionID: 2
YoungsModulus: 2.1000e+11
PoissonsRatio: 0.3000
MassDensity: []
CTE: []
Input Arguments
structuralmodel — Structural model
StructuralModel object
Poisson's ratio of the material, specified as a number greater than 0 and less than 0.5.
5-1047
5 Functions — Alphabetical List
Example: structuralProperties(structuralmodel,'YoungsModulus',
210e3,'PoissonsRatio',0.3)
Data Types: double
Mass density of the material, specified as a positive number. This argument is required
for transient and modal models. MDval is also required when modeling gravitational
effects.
Example: structuralProperties(structuralmodel,'YoungsModulus',
210e3,'PoissonsRatio',0.3,'MassDensity',11.7e-6)
Data Types: double
Geometric region type, specified as 'Face' for a 2-D model or 'Cell' for a 3-D model.
Example: structuralProperties(structuralmodel,'Cell',
1,'YoungsModulus',110E9,'PoissonsRatio',0.3)
Data Types: char | string
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot with the 'FaceLabels' (3-D) or 'EdgeLabels' (2-D) value set to 'on'.
5-1048
structuralProperties
Example: structuralProperties(structuralmodel,'Cell',
1:3,'YoungsModulus',110E9,'PoissonsRatio',0.3)
Data Types: double
Output Arguments
mtl — Handle to material properties
StructuralMaterialAssignment object
See Also
StructuralModel | createpde | structuralBC | structuralBodyLoad |
structuralBoundaryLoad | structuralDamping
Introduced in R2017b
5-1049
5 Functions — Alphabetical List
StationaryResults
Time-independent PDE solution and derived quantities
Description
A StationaryResults object contains the solution of a PDE and its gradients in a form
convenient for plotting and postprocessing.
• A StationaryResults object contains the solution and its gradient calculated at the
nodes of the triangular or tetrahedral mesh, generated by generateMesh.
• Solution values at the nodes appear in the NodalSolution property.
• The three components of the gradient of the solution values at the nodes appear in the
XGradients, YGradients, and ZGradients properties.
• The array dimensions of NodalSolution, XGradients, YGradients, and
ZGradients enable you to extract solution and gradient values for specified equation
indices in a PDE system.
To interpolate the solution or its gradient to a custom grid (for example, specified by
meshgrid), use interpolateSolution or evaluateGradient.
Creation
There are several ways to create a StationaryResults object:
• Solve a time-independent problem using the solvepde function. This function returns
a PDE solution as a StationaryResults object. This is the recommended approach.
• Solve a time-independent problem using the assempde or pdenonlin function. Then
use the createPDEResults function to obtain a StationaryResults object from a
PDE solution returned by assempde or pdenonlin. Note that assempde and
pdenonlin are legacy functions. They are not recommended for solving PDE
problems.
5-1050
StationaryResults
Properties
Mesh — Finite element mesh
FEMesh object
Solution values at the nodes, returned as a vector or array. For details about the
dimensions of NodalSolution, see “Dimensions of Solutions, Gradients, and Fluxes” on
page 3-299.
Data Types: double
x-component of the gradient at the nodes, returned as a vector or array. For details about
the dimensions of XGradients, see “Dimensions of Solutions, Gradients, and Fluxes” on
page 3-299.
Data Types: double
y-component of the gradient at the nodes, returned as a vector or array. For details about
the dimensions of YGradients, see “Dimensions of Solutions, Gradients, and Fluxes” on
page 3-299.
Data Types: double
z-component of the gradient at the nodes, returned as a vector or array. For details about
the dimensions of ZGradients, see “Dimensions of Solutions, Gradients, and Fluxes” on
page 3-299.
Data Types: double
5-1051
5 Functions — Alphabetical List
Object Functions
evaluateCGradient Evaluate flux of PDE solution
evaluateGradient Evaluate gradients of PDE solutions at arbitrary points
interpolateSolution Interpolate PDE solution to arbitrary points
Examples
Create a PDE model for a system of three equations. Import the geometry of a bracket
and plot the face labels.
model = createpde(3);
importGeometry(model,'BracketWithHole.stl');
figure
pdegplot(model,'FaceLabels','on')
view(30,30)
title('Bracket with Face Labels')
5-1052
StationaryResults
figure
pdegplot(model,'FaceLabels','on')
view(-134,-32)
title('Bracket with Face Labels, Rear View')
5-1053
5 Functions — Alphabetical List
Set boundary conditions such that face 4 is immobile, and face 8 has a force in the
negative z direction.
applyBoundaryCondition(model,'dirichlet','Face',4,'u',[0,0,0]);
applyBoundaryCondition(model,'neumann','Face',8,'g',[0,0,-1e4]);
Set coefficients that represent the equations of linear elasticity. See 3-D Linear Elasticity
Equations in Toolbox Form.
E = 200e9;
nu = 0.3;
specifyCoefficients(model,'m',0,...
'd',0,...
'c',elasticityC3D(E,nu),...
5-1054
StationaryResults
'a',0,...
'f',[0;0;0]);
Create a mesh.
generateMesh(model,'Hmax',1e-2);
results = solvepde(model)
results =
StationaryResults with properties:
u = results.NodalSolution;
pdeplot3D(model,'ColorMapData',u(:,3))
5-1055
5 Functions — Alphabetical List
Create a PDE model for a system of three equations. Import the geometry of a bracket
and plot the face labels.
model = createpde(3);
importGeometry(model,'BracketWithHole.stl');
5-1056
StationaryResults
figure
pdegplot(model,'FaceLabels','on')
view(30,30)
title('Bracket with Face Labels')
figure
pdegplot(model,'FaceLabels','on')
view(-134,-32)
title('Bracket with Face Labels, Rear View')
5-1057
5 Functions — Alphabetical List
Set boundary conditions such that F4 is immobile, and F8 has a force in the negative z
direction.
applyBoundaryCondition(model,'dirichlet','Face',4,'u',[0,0,0]);
applyBoundaryCondition(model,'neumann','Face',8,'g',[0,0,-1e4]);
Set coefficients for a legacy solver that represent the equations of linear elasticity. See 3-
D Linear Elasticity Equations in Toolbox Form.
E = 200e9;
nu = 0.3;
c = elasticityC3D(E,nu);
a = 0;
f = [0;0;0];
5-1058
StationaryResults
Create a mesh.
generateMesh(model,'Hmax',1e-2);
u = assempde(model,c,a,f);
results = createPDEResults(model,u)
results =
StationaryResults with properties:
u = results.NodalSolution;
pdeplot3D(model,'ColorMapData',u(:,3))
5-1059
5 Functions — Alphabetical List
See Also
EigenResults | TimeDependentResults | evaluateCGradient |
evaluateGradient | interpolateSolution | solvepde
Topics
“Poisson's Equation on Unit Disk” on page 3-150
“Minimal Surface Problem on Unit Disk”
“Solve Problems Using PDEModel Objects” on page 2-6
5-1060
StationaryResults
Introduced in R2016a
5-1061
5 Functions — Alphabetical List
SteadyStateThermalResults
Steady-state thermal solution and derived quantities
Description
A SteadyStateThermalResults object contains the temperature and temperature
gradient values in a form convenient for plotting and postprocessing.
The temperature and its gradients are calculated at the nodes of the triangular or
tetrahedral mesh generated by generateMesh. Temperature values at the nodes appear
in the Temperature property. The three components of the temperature gradient at the
nodes appear in the XGradients, YGradients, and ZGradients properties.
To interpolate the temperature or its gradients to a custom grid (for example, specified by
meshgrid), use interpolateTemperature or evaluateTemperatureGradient.
To evaluate heat flux of a thermal solution at nodal or arbitrary spatial locations, use
evaluateHeatFlux. To evaluate integrated heat flow rate normal to specified boundary,
use evaluateHeatRate.
Creation
Solve a steady-state thermal problem using the solve function. This function returns a
steady-state thermal solution as a SteadyStateThermalResults object.
Properties
Mesh — Finite element mesh
FEMesh object
5-1062
SteadyStateThermalResults
Object Functions
evaluateHeatFlux Evaluate heat flux of a thermal solution at nodal or
arbitrary spatial locations
evaluateHeatRate Evaluate integrated heat flow rate normal to specified
boundary
evaluateTemperatureGradient Evaluate temperature gradient of a thermal solution at
arbitrary spatial locations
interpolateTemperature Interpolate temperature in a thermal result at arbitrary
spatial locations
Examples
5-1063
5 Functions — Alphabetical List
thermalmodel = createpde('thermal');
importGeometry(thermalmodel,'Block.stl');
pdegplot(thermalmodel,'FaceLabel','on','FaceAlpha',0.5)
axis equal
thermalProperties(thermalmodel,'ThermalConductivity',80);
5-1064
SteadyStateThermalResults
Apply a constant temperature of to the left side of the block (face 1) and a
constant temperature of to the right side of the block (face 3). All other faces are
insulated by default.
thermalBC(thermalmodel,'Face',1,'Temperature',100);
thermalBC(thermalmodel,'Face',3,'Temperature',300);
generateMesh(thermalmodel);
thermalresults = solve(thermalmodel)
thermalresults =
SteadyStateThermalResults with properties:
The solver finds the temperatures and temperature gradients at the nodal locations. To
access these values, use thermalresults.Temperature,
thermalresults.XGradients, and so on. For example, plot temperatures at nodal
locations.
pdeplot3D(thermalmodel,'ColorMapData',thermalresults.Temperature)
5-1065
5 Functions — Alphabetical List
See Also
TransientThermalResults | evaluateHeatFlux | evaluateHeatRate |
evaluateTemperatureGradient | interpolateTemperature
Introduced in R2017a
5-1066
ThermalBC Properties
ThermalBC Properties
Boundary condition for thermal model
Description
A ThermalBC object specifies the type of PDE boundary condition on a set of geometry
boundaries. A ThermalModel object contains a vector of ThermalBC objects in its
BoundaryConditions.ThermalBCAssignments property.
Specify boundary conditions for your model using the thermalBC function.
Properties
Properties
Geometric region type, returned as 'Face' for 3-D geometry or 'Edge' for 2-D
geometry.
Data Types: char
Geometric region ID, returned as a vector of positive integers. Find the region IDs using
pdegplot with the 'FaceLabels' (3-D) or 'EdgeLabels' (2-D) value set to 'on'.
Data Types: double
5-1067
5 Functions — Alphabetical List
Heat flux boundary condition, returned as a number or a function handle. Use a function
handle to specify a spatially or temporally varying heat flux or a nonlinear heat flux.
Data Types: double | function_handle
Radiation emissivity coefficient, returned as a number in the range (0,1). Use a function
handle to specify spatially or temporally varying emissivity or nonlinear emissivity.
Specify ambient temperature using the AmbientTemperature argument and the Stefan-
Boltzmann constant using the thermal model properties.
Data Types: double | function_handle
Vectorized function evaluation, returned as 'on' or 'off'. This evaluation applies when
you pass a function handle as an argument. To save time in function handle evaluation,
specify 'on', assuming that your function handle computes in a vectorized fashion. See
5-1068
ThermalBC Properties
See Also
ThermalModel | findthermalBC | thermalBC
Introduced in R2017a
5-1069
5 Functions — Alphabetical List
ThermalMaterialAssignment Properties
Thermal material properties assignments
Description
A ThermalMaterialAssignment object contains the description of a thermal model’s
material properties. A ThermalModel container has a vector of
ThermalMaterialAssignment objects in its
MaterialProperties.MaterialAssignments property.
Create material properties assignments for your thermal model using the
thermalProperties function.
Properties
Properties
Region type, returned as 'Face' for a 2-D region, or 'Cell' for a 3-D region.
Data Types: char
RegionID — Region ID
vector of positive integers
5-1070
ThermalMaterialAssignment Properties
See Also
findThermalProperties | thermalProperties
Introduced in R2017a
5-1071
5 Functions — Alphabetical List
ThermalModel
Thermal model object
Description
A ThermalModel object contains information about a heat transfer problem: the
geometry, material properties, internal heat sources, temperature on the boundaries, heat
fluxes through the boundaries, mesh, and initial conditions.
Creation
Create a ThermalModel object using createpde with the first argument 'thermal'.
Properties
AnalysisType — Type of thermal analysis
'steadystate' | 'transient'
• AnalyticGeometry object for 2-D geometry. Create this geometry using the
geometryFromEdges function.
• DiscreteGeometry object for 3-D geometry. Create this geometry using the
importGeometry function or the geometryFromMesh function.
Material properties within the domain, returned as an object containing the material
property assignments.
5-1072
ThermalModel
Heat source within the domain or subdomain, returned as an object containing heat
source assignments.
Mesh for solution, returned as a FEMesh object. You create the mesh using the
generateMesh function.
• SI – 5.670367e-8 W/(m2·K4)
• CGS – 5.6704e-5 erg/(cm2·s·K4)
• US customary – 1.714e-9 BTU/(hr·ft2·R4)
Algorithm options for the PDE solvers, returned as a PDESolverOptions object. The
properties of PDESolverOptions include absolute and relative tolerances for internal
ODE solvers, maximum solver iterations, and so on.
5-1073
5 Functions — Alphabetical List
Object Functions
geometryFromEdges Create 2-D geometry
geometryFromMesh Create geometry from mesh
importGeometry Import geometry from STL data
thermalProperties Assign thermal properties of a material for a thermal model
internalHeatSource Specify internal heat source for a thermal model
thermalBC Specify boundary conditions for a thermal model
thermalIC Set initial conditions or initial guess for a thermal model
generateMesh Create triangular or tetrahedral mesh
solve Solve heat transfer or structural analysis problem
Examples
thermalmodel = createpde('thermal','transient')
thermalmodel =
ThermalModel with properties:
AnalysisType: 'transient'
Geometry: []
MaterialProperties: []
HeatSources: []
StefanBoltzmannConstant: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 PDESolverOptions]
g = @squareg;
geometryFromEdges(thermalmodel,g)
ans =
AnalyticGeometry with properties:
5-1074
ThermalModel
NumCells: 0
NumFaces: 1
NumEdges: 4
NumVertices: 4
ans =
ThermalMaterialAssignment with properties:
RegionType: 'face'
RegionID: 1
ThermalConductivity: 79.5000
MassDensity: 7850
SpecificHeat: 450
Specify that the entire geometry generates heat at the rate 25 W/m^3.
internalHeatSource(thermalmodel,25)
ans =
HeatSourceAssignment with properties:
RegionType: 'face'
RegionID: 1
HeatSource: 25
Apply insulated boundary conditions on three edges and the free convection boundary
condition on the right edge.
thermalBC(thermalmodel,'Edge',[1,3,4],'HeatFlux',0);
thermalBC(thermalmodel,'Edge',2,...
'ConvectionCoefficient',5000,...
'AmbientTemperature',25)
ans =
ThermalBC with properties:
5-1075
5 Functions — Alphabetical List
RegionType: 'Edge'
RegionID: 2
Temperature: []
HeatFlux: []
ConvectionCoefficient: 5000
Emissivity: []
AmbientTemperature: 25
Vectorized: 'off'
Set the initial conditions: uniform room temperature across domain and higher
temperature on the left edge.
thermalIC(thermalmodel,25);
thermalIC(thermalmodel,100,'Edge',4)
ans =
GeometricThermalICs with properties:
RegionType: 'edge'
RegionID: 4
InitialTemperature: 100
thermalmodel.StefanBoltzmannConstant = 5.670367e-8;
Generate mesh.
generateMesh(thermalmodel)
ans =
FEMesh with properties:
5-1076
ThermalModel
thermalmodel
thermalmodel =
ThermalModel with properties:
AnalysisType: 'transient'
Geometry: [1x1 AnalyticGeometry]
MaterialProperties: [1x1 MaterialAssignmentRecords]
HeatSources: [1x1 HeatSourceAssignmentRecords]
StefanBoltzmannConstant: 5.6704e-08
BoundaryConditions: [1x1 ThermalBCRecords]
InitialConditions: [1x1 ThermalICRecords]
Mesh: [1x1 FEMesh]
SolverOptions: [1x1 PDESolverOptions]
See Also
createpde | generateMesh | geometryFromEdges | geometryFromMesh |
importGeometry | internalHeatSource | pdegplot | pdeplot | pdeplot3D |
thermalBC | thermalIC | thermalProperties
Introduced in R2017a
5-1077
5 Functions — Alphabetical List
thermalProperties
Package: pde
Syntax
thermalProperties(thermalmodel,'ThermalConductivity',
TCval,'MassDensity',MDval,'SpecificHeat',SHval)
thermalProperties( ___ ,RegionType,RegionID)
mtl = thermalProperties( ___ )
Description
thermalProperties(thermalmodel,'ThermalConductivity',
TCval,'MassDensity',MDval,'SpecificHeat',SHval) assigns material properties,
such as thermal conductivity, mass density, and specific heat. For transient analysis,
specify all three properties. For steady-state analysis, specifying thermal conductivity is
enough. This syntax sets material properties for the entire geometry.
For a nonconstant or nonlinear material, specify TCval, MDval, and SHval as function
handles.
Examples
5-1078
thermalProperties
model = createpde('thermal','steadystate');
gm = importGeometry(model,'SquareBeam.STL');
thermalProperties(model,'ThermalConductivity',0.08)
ans =
ThermalMaterialAssignment with properties:
RegionType: 'cell'
RegionID: 1
ThermalConductivity: 0.0800
MassDensity: []
SpecificHeat: []
thermalmodel = createpde('thermal','transient');
gm = importGeometry(thermalmodel,'SquareBeam.STL');
thermalProperties(thermalmodel,'ThermalConductivity',0.2,...
'MassDensity',2.7*10^(-6),...
'SpecificHeat',920)
ans =
ThermalMaterialAssignment with properties:
RegionType: 'cell'
RegionID: 1
ThermalConductivity: 0.2000
MassDensity: 2.7000e-06
SpecificHeat: 920
thermalModel = createpde('thermal');
5-1079
5 Functions — Alphabetical List
Create nested cylinders to model a two-layered insulated pipe section, consisting of inner
metal pipe surrounded by insulated material.
gm = multicylinder([20,25,35],20,'Void',[1,0,0]);
thermalModel.Geometry = gm;
pdegplot(thermalModel,'CellLabels','on','FaceAlpha',0.5)
thermalProperties(thermalModel,'Cell',1,'ThermalConductivity',0.4)
5-1080
thermalProperties
ans =
ThermalMaterialAssignment with properties:
RegionType: 'cell'
RegionID: 1
ThermalConductivity: 0.4000
MassDensity: []
SpecificHeat: []
thermalProperties(thermalModel,'Cell',2,'ThermalConductivity',0.0015)
ans =
ThermalMaterialAssignment with properties:
RegionType: 'cell'
RegionID: 2
ThermalConductivity: 0.0015
MassDensity: []
SpecificHeat: []
Use function handles to specify a thermal conductivity that depends on temperature and
specific heat that depends on coordinates.
Create a thermal model for transient analysis and include the geometry. The geometry is
a rod with a circular cross section. The 2-D model is a rectangular strip whose y-
dimension extends from the axis of symmetry to the outer surface, and whose x-dimension
extends over the actual length of the rod.
thermalmodel = createpde('thermal','transient');
5-1081
5 Functions — Alphabetical List
cp = @(location,state)500*location.y;
Specify the thermal conductivity, mass density, and specific heat of the material.
thermalProperties(thermalmodel,'ThermalConductivity',k,...
'MassDensity',2.7*10^(-6),...
'SpecificHeat',cp)
ans =
ThermalMaterialAssignment with properties:
RegionType: 'face'
RegionID: 1
ThermalConductivity: @(location,state)40+0.003*state.u
MassDensity: 2.7000e-06
SpecificHeat: @(location,state)500*location.y
Input Arguments
thermalmodel — Thermal model
ThermalModel object
Thermal model, specified as a ThermalModel object. The model contains the geometry,
mesh, thermal properties of the material, internal heat source, boundary conditions, and
initial conditions.
Example: thermalmodel = createpde('thermal','steadystate')
5-1082
thermalProperties
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot, as shown in “Create Geometry and Remove Face Boundaries” on page 2-13 or
“STL File Import” on page 2-47.
Example: thermalProperties(thermalmodel,'Cell',
1:3,'ThermalConductivity',100)
Data Types: double
Use a function handle to specify the thermal conductivity that depends on space, time, or
temperature. The function must be of the form
TCval = TCfun(location,state)
The solver passes location data as a structure array with the fields location.x,
location.y, and, for 3-D problems, location.z. The state data is a structure array
with the fields state.u, state.ux, state.uy, state.uz (for 3-D problems), and
state.time (for transient problems). The state.u field contains the solution vector.
The state.ux, state.uy, state.uz fields are estimates of the solution’s partial
derivatives at the corresponding points of the location structure. The state.time field
contains time at evaluation points.
TCfun must return a matrix TCval with number of rows equal to 1, Ndim, Ndim*(Ndim
+1)/2, or Ndim*Ndim, where Ndim is 2 for 2-D problems and 3 for 3-D problems. The
number of columns must equal the number of evaluation points, M =
length(location.x). For details about dimensions of the matrix, see “c Coefficient for
specifyCoefficients” on page 2-110.
Example: thermalProperties(thermalmodel,'Cell',
1,'ThermalConductivity',100) or
thermalProperties(thermalmodel,'ThermalConductivity',[80;10;80]) for
orthotropic thermal conductivity
Data Types: double | function_handle
5-1083
5 Functions — Alphabetical List
Mass density of the material, specified as a positive number or a function handle. Specify
this property for a transient thermal conduction analysis model.
Use a function handle to specify the mass density that depends on space, time, or
temperature. The function must be of the form
MDval = MDfun(location,state)
The solver passes location data as a structure array with the fields location.x,
location.y, and, for 3-D problems, location.z. The state data is a structure array
with the fields state.u, state.ux, state.uy, state.uz (for 3-D problems), and
state.time (for transient problems). The state.u field contains the solution vector.
The state.ux, state.uy, state.uz fields are estimates of the solution’s partial
derivatives at the corresponding points of the location structure. The state.time field
contains time at evaluation points.
MDfun must return a row vector MDval with the number of columns equal to the number
of evaluation points, M = length(location.x).
Example: thermalProperties(thermalmodel,'Cell',
1,'ThermalConductivity',100,'MassDensity',2730e-9,'SpecificHeat',
910)
Data Types: double | function_handle
Specific heat of the material, specified as a positive number or a function handle. Specify
this property for a transient thermal conduction analysis model.
Use a function handle to specify the specific heat that depends on space, time, or
temperature. The function must be of the form
SHval = SHfun(location,state)
The solver passes location data as a structure array with the fields location.x,
location.y, and, for 3-D problems, location.z. The state data is a structure array
with the fields state.u, state.ux, state.uy, state.uz (for 3-D problems), and
state.time (for transient problems). The state.u field contains the solution vector.
The state.ux, state.uy, state.uz fields are estimates of the solution’s partial
derivatives at the corresponding points of the location structure. The state.time field
contains time at evaluation points.
5-1084
thermalProperties
SHfun must return a row vector SHval with the number of columns equal to the number
of evaluation points, M = length(location.x).
Example: thermalProperties(thermalmodel,'Cell',
1,'ThermalConductivity',100,'MassDensity',2730e-9,'SpecificHeat',
910)
Data Types: double | function_handle
Output Arguments
mtl — Handle to material properties
object
See Also
internalHeatSource | specifyCoefficients
Topics
“Heat Conduction in Multidomain Geometry with Nonuniform Heat Flux”
Introduced in R2017a
5-1085
5 Functions — Alphabetical List
TimeDependentResults
Time-dependent PDE solution and derived quantities
Description
A TimeDependentResults object contains the solution of a PDE and its gradients in a
form convenient for plotting and postprocessing.
To interpolate the solution or its gradient to a custom grid (for example, specified by
meshgrid), use interpolateSolution or evaluateGradient.
Creation
There are several ways to create a TimeDependentResults object:
• Solve a time-dependent problem using the solvepde function. This function returns a
PDE solution as a TimeDependentResults object. This is the recommended
approach.
• Solve a time-dependent problem using the parabolic or hyperbolic function. Then
use the createPDEResults function to obtain a TimeDependentResults object
from a PDE solution returned by parabolic or hyperbolic. Note that parabolic
and hyperbolic are legacy functions. They are not recommended for solving PDE
problems.
5-1086
TimeDependentResults
Properties
Mesh — Finite element mesh
FEMesh object
Solution values at the nodes, returned as a vector or array. For details about the
dimensions of NodalSolution, see “Dimensions of Solutions, Gradients, and Fluxes” on
page 3-299.
Data Types: double
Complex Number Support: Yes
Solution times, returned as a real vector. SolutionTimes is the same as the tlist input
to solvepde, or the tlist input to the legacy parabolic or hyperbolic solvers.
Data Types: double
x-component of the gradient at the nodes, returned as a vector or array. For details about
the dimensions of XGradients, see “Dimensions of Solutions, Gradients, and Fluxes” on
page 3-299.
Data Types: double
Complex Number Support: Yes
y-component of the gradient at the nodes, returned as a vector or array. For details about
the dimensions of YGradients, see “Dimensions of Solutions, Gradients, and Fluxes” on
page 3-299.
Data Types: double
5-1087
5 Functions — Alphabetical List
z-component of the gradient at the nodes, returned as a vector or array. For details about
the dimensions of ZGradients, see “Dimensions of Solutions, Gradients, and Fluxes” on
page 3-299.
Data Types: double
Object Functions
evaluateCGradient Evaluate flux of PDE solution
evaluateGradient Evaluate gradients of PDE solutions at arbitrary points
interpolateSolution Interpolate PDE solution to arbitrary points
Examples
5-1088
TimeDependentResults
model = createpde();
geometryFromEdges(model,dl);
Set boundary conditions that the upper and left edges are at temperature 10.
applyBoundaryCondition(model,'dirichlet','Edge',[2,3],'u',10);
Set initial conditions that the square region is at temperature 0, and the circle is at
temperature 100.
setInitialConditions(model,0);
setInitialConditions(model,100,'Face',2);
5-1089
5 Functions — Alphabetical List
specifyCoefficients(model,'m',0,'d',1,'c',1,'a',0,'f',0);
generateMesh(model,'Hmax',0.05);
tlist = 0:0.01:0.5;
results = solvepde(model,tlist);
Plot the solution for times 0.02, 0.04, 0.1, and 0.5.
sol = results.NodalSolution;
subplot(2,2,1)
pdeplot(model,'XYData',sol(:,3))
title('Time 0.02')
subplot(2,2,2)
pdeplot(model,'XYData',sol(:,5))
title('Time 0.04')
subplot(2,2,3)
pdeplot(model,'XYData',sol(:,11))
title('Time 0.1')
subplot(2,2,4)
pdeplot(model,'XYData',sol(:,51))
title('Time 0.5')
5-1090
TimeDependentResults
See Also
EigenResults | StationaryResults | evaluateCGradient | evaluateGradient |
interpolateSolution
Topics
“Heat Transfer in Block with Cavity” on page 3-183
“Wave Equation on Square Domain”
“Solve Problems Using PDEModel Objects” on page 2-6
5-1091
5 Functions — Alphabetical List
Introduced in R2016a
5-1092
TransientThermalResults
TransientThermalResults
Transient thermal solution and derived quantities
Description
A TransientThermalResults object contains the temperature and gradients values in
a form convenient for plotting and postprocessing.
The temperature and its gradient are calculated at the nodes of the triangular or
tetrahedral mesh generated by generateMesh. Temperature values at the nodes appear
in the Temperature property. The solution times appear in the SolutionTimes
property. The three components of the temperature gradient at the nodes appear in the
XGradients, YGradients, and ZGradients properties. The array dimensions of
Temperature, XGradients, YGradients, and ZGradients let you extract solution and
gradient values for specified time indices.
To interpolate the temperature or its gradient to a custom grid (for example, specified by
meshgrid), use interpolateTemperature or evaluateTemperatureGradient.
To evaluate heat flux of a thermal solution at nodal or arbitrary spatial locations, use
evaluateHeatFlux. To evaluate integrated heat flow rate normal to specified boundary,
use evaluateHeatRate.
Creation
Solve a transient thermal problem using the solve function. This function returns a
transient thermal solution as a TransientThermalResults object.
Properties
Mesh — Finite element mesh
FEMesh object
5-1093
5 Functions — Alphabetical List
Solution times, returned as a real vector. SolutionTimes is the same as the tlist input
to solve.
Data Types: double
Object Functions
evaluateHeatFlux Evaluate heat flux of a thermal solution at nodal or
arbitrary spatial locations
evaluateHeatRate Evaluate integrated heat flow rate normal to specified
boundary
evaluateTemperatureGradient Evaluate temperature gradient of a thermal solution at
arbitrary spatial locations
5-1094
TransientThermalResults
Examples
thermalmodel = createpde('thermal','transient');
5-1095
5 Functions — Alphabetical List
•
Thermal conductivity is .
•
Mass density is .
•
Specific heat is .
thermalProperties(thermalmodel,'ThermalConductivity',10, ...
'MassDensity',2, ...
'SpecificHeat',0.1, ...
'Face',1);
5-1096
TransientThermalResults
•
Thermal conductivity is .
•
Mass density is .
•
Specific heat is .
thermalProperties(thermalmodel,'ThermalConductivity',2, ...
'MassDensity',1, ...
'SpecificHeat',0.1, ...
'Face',2);
internalHeatSource(thermalmodel,4,'Face',2);
thermalBC(thermalmodel,'Temperature',0,'Edge',[1 2 7 8]);
thermalIC(thermalmodel,0);
generateMesh(thermalmodel);
The dynamics for this problem are very fast. The temperature reaches a steady state in
about 0.1 second. To capture the interesting part of the dynamics, set the solution time to
logspace(-2,-1,10). This command returns 10 logarithmically spaced solution times
between 0.01 and 0.1.
tlist = logspace(-2,-1,10);
thermalresults = solve(thermalmodel,tlist)
thermalresults =
TransientThermalResults with properties:
5-1097
5 Functions — Alphabetical List
T = thermalresults.Temperature;
pdeplot(thermalmodel,'XYData',T(:,10),'Contour','on','ColorMap','hot')
5-1098
TransientThermalResults
See Also
SteadyStateThermalResults | evaluateHeatFlux | evaluateHeatRate |
evaluateTemperatureGradient | interpolateTemperature
Introduced in R2017a
5-1099
5 Functions — Alphabetical List
thermalBC
Package: pde
Syntax
thermalBC(thermalmodel,RegionType,RegionID,'Temperature',Tval)
thermalBC(thermalmodel,RegionType,RegionID,'HeatFlux,HFval)
thermalBC(thermalmodel,RegionType,RegionID,'ConvectionCoefficient',
CCval,'AmbientTemperature',ATval)
thermalBC(thermalmodel,RegionType,RegionID,'Emissivity',
REval,'AmbientTemperature',ATval)
thermalBC = thermalBC( ___ )
Description
thermalBC(thermalmodel,RegionType,RegionID,'Temperature',Tval) adds a
temperature boundary condition to thermalmodel. The boundary condition applies to
regions of type RegionType with ID numbers in RegionID.
Note Use thermalBC with the HeatFlux parameter to specify a heat flux to or from an
external source. To specify internal heat generation, that is, heat sources that belong to
the geometry of the model, use internalHeatSource.
thermalBC(thermalmodel,RegionType,RegionID,'ConvectionCoefficient',
CCval,'AmbientTemperature',ATval) adds a convection boundary condition to
thermalmodel. The boundary condition applies to regions of type RegionType with ID
numbers in RegionID.
5-1100
thermalBC
thermalBC(thermalmodel,RegionType,RegionID,'Emissivity',
REval,'AmbientTemperature',ATval) adds a radiation boundary condition to
thermalmodel. The boundary condition applies to regions of type RegionType with ID
numbers in RegionID.
Examples
ans =
ThermalBC with properties:
RegionType: 'Edge'
RegionID: [1 3]
Temperature: 100
HeatFlux: []
ConvectionCoefficient: []
Emissivity: []
AmbientTemperature: []
Vectorized: 'off'
ans =
ThermalBC with properties:
5-1101
5 Functions — Alphabetical List
RegionType: 'Face'
RegionID: [1 3]
Temperature: []
HeatFlux: 20
ConvectionCoefficient: []
Emissivity: []
AmbientTemperature: []
Vectorized: 'off'
ans =
ThermalBC with properties:
RegionType: 'Face'
RegionID: [2 4 5 6]
Temperature: []
HeatFlux: []
ConvectionCoefficient: 5
Emissivity: []
AmbientTemperature: 27
Vectorized: 'off'
5-1102
thermalBC
thermalmodel.StefanBoltzmannConstant = 5.670373E-8;
thermalBC(thermalmodel,'Face',[2,4,5,6],...
'Emissivity',0.1,...
'AmbientTemperature',300)
ans =
ThermalBC with properties:
RegionType: 'Face'
RegionID: [2 4 5 6]
Temperature: []
HeatFlux: []
ConvectionCoefficient: []
Emissivity: 0.1000
AmbientTemperature: 300
Vectorized: 'off'
Use function handles to specify thermal boundary conditions that depend on coordinates.
Create a thermal model for transient analysis and include the geometry. The geometry is
a rod with a circular cross section. The 2-D model is a rectangular strip whose y-
dimension extends from the axis of symmetry to the outer surface, and whose x-dimension
extends over the actual length of the rod.
thermalmodel = createpde('thermal','transient');
g = decsg([3 4 -1.5 1.5 1.5 -1.5 0 0 .2 .2]');
geometryFromEdges(thermalmodel,g);
figure
pdegplot(thermalmodel,'EdgeLabels','on');
xlim([-2 2]);
ylim([-2 2]);
title 'Rod Section Geometry with Edge Labels';
5-1103
5 Functions — Alphabetical List
Assume that there is a heat source at the left end of the rod and a fixed temperature at
the right end. The outer surface of the rod exchanges heat with the environment due to
convection.
Define the boundary conditions for the model. The edge at y = 0 (edge 1) is along the axis
of symmetry. No heat is transferred in the direction normal to this edge. This boundary is
modeled as an insulated boundary, by default.
The temperature at the right end of the rod (edge 2) is a fixed temperature, T = 100 C.
Specify the boundary condition for edge 2 as follows.
thermalBC(thermalmodel,'Edge',2,'Temperature',100)
5-1104
thermalBC
ans =
ThermalBC with properties:
RegionType: 'Edge'
RegionID: 2
Temperature: 100
HeatFlux: []
ConvectionCoefficient: []
Emissivity: []
AmbientTemperature: []
Vectorized: 'off'
The convection coefficient for the outer surface of the rod (edge 3) depends on the y-
coordinate, 50y. Specify the boundary condition for this edge as follows.
ans =
ThermalBC with properties:
RegionType: 'Edge'
RegionID: 3
Temperature: []
HeatFlux: []
ConvectionCoefficient: @(location,~)50*location.y
Emissivity: []
AmbientTemperature: 100
Vectorized: 'off'
The heat flux at the left end of the rod (edge 4) is also a function of the y-coordinate,
5000y. Specify the boundary condition for this edge as follows.
ans =
ThermalBC with properties:
RegionType: 'Edge'
5-1105
5 Functions — Alphabetical List
RegionID: 4
Temperature: []
HeatFlux: @(location,~)5000*location.y
ConvectionCoefficient: []
Emissivity: []
AmbientTemperature: []
Vectorized: 'off'
Input Arguments
thermalmodel — Thermal model
ThermalModel object
Thermal model, specified as a ThermalModel object. The model contains the geometry,
mesh, thermal properties of the material, internal heat source, boundary conditions, and
initial conditions.
Example: thermalmodel = createpde('thermal','steadystate')
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot with the 'FaceLabels' (3-D) or 'EdgeLabels' (2-D) value set to 'on'.
Example: thermalBC(thermalmodel,'Edge',2:5,'Temperature',72)
Data Types: double
5-1106
thermalBC
The solver passes location data as a structure array with the fields location.x,
location.y, and, for 3-D problems, location.z. The state data is a structure array
with the fields state.u, state.ux, state.uy, state.uz (for 3-D problems), and
state.time (for transient problems). The state.u field contains the solution vector.
The state.ux, state.uy, state.uz fields are estimates of the solution’s partial
derivatives at the corresponding points of the location structure. The state.time field
contains time at evaluation points.
Tfun must return a row vector Tval with the number of columns equal to the number of
evaluation points, M = length(location.x).
Example: thermalBC(thermalmodel,'Face',1,'Temperature',72)
Data Types: double | function_handle
Heat flux boundary condition, specified as a number or a function handle. Use a function
handle to specify the heat flux that depends on space, time, or temperature. The function
must be of the form
HFval = HFfun(location,state)
The solver passes location data as a structure array with the fields location.x,
location.y, and, for 3-D problems, location.z. The state data is a structure array
with the fields state.u, state.ux, state.uy, state.uz (for 3-D problems), and
state.time (for transient problems). The state.u field contains the solution vector.
The state.ux, state.uy, state.uz fields are estimates of the solution’s partial
derivatives at the corresponding points of the location structure. The state.time field
contains time at evaluation points.
HFfun must return a row vector HFval with the number of columns equal to the number
of evaluation points, M = length(location.x).
Example: thermalBC(thermalmodel,'Face',[1,3],'HeatFlux',20)
Data Types: double | function_handle
5-1107
5 Functions — Alphabetical List
The solver passes location data as a structure array with the fields location.x,
location.y, and, for 3-D problems, location.z. The state data is a structure array
with the fields state.u, state.ux, state.uy, state.uz (for 3-D problems), and
state.time (for transient problems). The state.u field contains the solution vector.
The state.ux, state.uy, state.uz fields are estimates of the solution’s partial
derivatives at the corresponding points of the location structure. The state.time field
contains time at evaluation points.
CCfun must return a row vector CCval with the number of columns equal to the number
of evaluation points, M = length(location.x).
Radiation emissivity coefficient, specified as a number in the range (0,1). Use a function
handle to specify the radiation emissivity that depends on space, time, or temperature.
The function must be of the form
REval = REfun(location,state)
The solver passes location data as a structure array with the fields location.x,
location.y, and, for 3-D problems, location.z. The state data is a structure array
with the fields state.u, state.ux, state.uy, state.uz (for 3-D problems), and
state.time (for transient problems). The state.u field contains the solution vector.
The state.ux, state.uy, state.uz fields are estimates of the solution’s partial
derivatives at the corresponding points of the location structure. The state.time field
contains time at evaluation points.
5-1108
thermalBC
REfun must return a row vector REval with the number of columns equal to the number
of evaluation points, M = length(location.x).
Specify ambient temperature using the AmbientTemperature argument and the Stefan-
Boltzmann constant using the thermal model properties. The value of Emissivity is
positive for heat radiation into the ambient environment.
Example: thermalmodel.StefanBoltzmannConstant = 5.670373E-8;
thermalBC(thermalmodel,'Edge',[2,4,5,6],'Emissivity',
0.1,'AmbientTemperature',300)
Data Types: double | function_handle
Output Arguments
thermalBC — Handle to thermal boundary condition
object
See Also
applyBoundaryCondition | internalHeatSource | thermalIC |
thermalProperties
Topics
“Heat Conduction in Multidomain Geometry with Nonuniform Heat Flux”
Introduced in R2017a
5-1109
5 Functions — Alphabetical List
thermalIC
Package: pde
Syntax
thermalIC(thermalmodel,T0)
thermalIC(thermalmodel,T0,RegionType,RegionID)
thermalIC(thermalmodel,Tresults)
thermalIC(thermalmodel,Tresults,iT)
thermalIC = thermalIC( ___ )
Description
thermalIC(thermalmodel,T0) sets initial temperature or initial guess for temperature
to the entire geometry.
thermalIC = thermalIC( ___ ), for any previous syntax, returns a handle to the
thermal initial conditions object.
Examples
5-1110
thermalIC
Create a thermal model, import geometry, and set the initial temperature to 0 on the
entire geometry.
thermalModel = createpde('thermal','transient');
geometryFromEdges(thermalModel,@lshapeg);
thermalIC(thermalModel,0)
ans =
GeometricThermalICs with properties:
RegionType: 'face'
RegionID: [1 2 3]
InitialTemperature: 0
Set different initial conditions on each portion of the L-shaped membrane geometry.
thermalModel = createpde('thermal','transient');
geometryFromEdges(thermalModel,@lshapeg);
pdegplot(thermalModel,'FaceLabels','on')
axis equal
ylim([-1.1 1.1])
5-1111
5 Functions — Alphabetical List
thermalIC(thermalModel,0,'Face',1)
ans =
GeometricThermalICs with properties:
RegionType: 'face'
RegionID: 1
InitialTemperature: 0
thermalIC(thermalModel,10,'Face',2)
5-1112
thermalIC
ans =
GeometricThermalICs with properties:
RegionType: 'face'
RegionID: 2
InitialTemperature: 10
thermalIC(thermalModel,75,'Face',3)
ans =
GeometricThermalICs with properties:
RegionType: 'face'
RegionID: 3
InitialTemperature: 75
Create a thermal model for transient analysis and include the geometry. The geometry is
a rod with a circular cross section.The 2-D model is a rectangular strip whose y-dimension
extends from the axis of symmetry to the outer surface, and whose x-dimension extends
over the actual length of the rod.
thermalmodel = createpde('thermal','transient');
g = decsg([3 4 -1.5 1.5 1.5 -1.5 0 0 .2 .2]');
geometryFromEdges(thermalmodel,g);
Set the initial temperature in the rod to be dependent on the y-coordinate, for example,
.
T0 = @(location)10^3*(0.2 - location.y.^2);
thermalIC(thermalmodel,T0)
ans =
GeometricThermalICs with properties:
RegionType: 'face'
5-1113
5 Functions — Alphabetical List
RegionID: 1
InitialTemperature: @(location)10^3*(0.2-location.y.^2)
thermalmodel = createpde('thermal','transient');
geometryFromEdges(thermalmodel,@squareg);
pdegplot(thermalmodel,'FaceLabels','on')
ylim([-1.1,1.1])
axis equal
5-1114
thermalIC
Specify material properties and internal heat source, and set boundary conditions and
initial conditions.
thermalProperties(thermalmodel,'ThermalConductivity',500,...
'MassDensity',200,...
'SpecificHeat',100);
internalHeatSource(thermalmodel,2);
thermalBC(thermalmodel,'Edge',[1,3],'Temperature',100);
thermalIC(thermalmodel,0);
5-1115
5 Functions — Alphabetical List
generateMesh(thermalmodel);
tlist = 0:0.5:10;
result1 = solve(thermalmodel,tlist)
result1 =
TransientThermalResults with properties:
pdeplot(thermalmodel,'XYData',result1.Temperature(:,end))
5-1116
thermalIC
Now, resume the analysis and solve the problem for times from 10 to 15 seconds. Use the
previously obtained solution for 10 seconds as an initial condition. Since 10 seconds is the
last element in tlist, you do not need to specify the solution time index. By default,
thermalIC uses the last solution index.
thermalIC(thermalmodel,result1)
ans =
NodalThermalICs with properties:
5-1117
5 Functions — Alphabetical List
result2 = solve(thermalmodel,10:0.5:15)
result2 =
TransientThermalResults with properties:
pdeplot(thermalmodel,'XYData',result2.Temperature(:,end))
5-1118
thermalIC
To use the previously obtained solution for a particular solution time instead of the last
one, specify the solution time index as a third parameter of thermalIC. For example, use
the solution at time 5 seconds, which is the 11th element in tlist.
tlist(11)
ans = 5
thermalIC(thermalmodel,result1,11);
result2 = solve(thermalmodel,5:0.5:15)
result2 =
TransientThermalResults with properties:
pdeplot(thermalmodel,'XYData',result2.Temperature(:,end))
5-1119
5 Functions — Alphabetical List
Input Arguments
thermalmodel — Thermal model
ThermalModel object
Thermal model, specified as a ThermalModel object. The model contains the geometry,
mesh, thermal properties of the material, internal heat source, boundary conditions, and
initial conditions.
Example: thermalmodel = createpde('thermal','steadystate')
5-1120
thermalIC
T0 = T0fun(location)
The solver passes location as a structure with fields location.x, location.y, and,
for 3-D problems, location.z. T0fun must return a row vector T0 with the number of
columns equal to M = length(location.x).
Data Types: double | function_handle
Geometric region type, specified as 'Vertex', 'Edge', 'Face', or 'Cell' for a 3-D
model. For a 2-D model, use 'Vertex', 'Edge', or 'Face'.
Example: thermalIC(thermalmodel,10,'Face',1)
Data Types: char | string
Geometric region ID, specified as a vector of positive integers. Find the region IDs using
pdegplot, as shown in “Create Geometry and Remove Face Boundaries” on page 2-13 or
“STL File Import” on page 2-47.
Example: thermalIC(thermalmodel,10,'Edge',2:5)
Data Types: double
iT — Time index
positive integer
5-1121
5 Functions — Alphabetical List
Output Arguments
thermalIC — Handle to initial condition
object
See Also
internalHeatSource | setInitialConditions | thermalBC | thermalProperties
Introduced in R2017a
5-1122
tri2grid
tri2grid
(Not recommended) Interpolate from PDE triangular mesh to rectangular grid
Syntax
uxy = tri2grid(p,t,u,x,y)
[uxy,tn,a2,a3] = tri2grid(p,t,u,x,y)
uxy = tri2grid(p,t,u,tn,a2,a3)
Description
uxy = tri2grid(p,t,u,x,y) computes the function values uxy over the grid defined
by the vectors x and y, from the function u with values on the triangular mesh defined by
p and t. Values are computed using linear interpolation in the triangle containing the grid
point. The vectors x and y must be increasing. u must be a vector. For systems of
equations, uxy interpolates only the first component. For solutions returned by
hyperbolic or parabolic, pass u as the vector of values at one time, u(:,k).
All tri2grid output arguments are ny-by-nx matrices, where nx and ny are the lengths
of the vectors x and y respectively. At grid points outside of the triangular mesh, all
tri2grid output arguments are NaN.
See Also
interpolateSolution | solvepde
5-1123
5 Functions — Alphabetical List
5-1124
volume
volume
Package: pde
Syntax
V = volume(mesh)
[V,VE] = volume(mesh)
V = volume(mesh,elements)
Description
V = volume(mesh) returns the volume V of the entire mesh.
Examples
5-1125
5 Functions — Alphabetical List
mesh = generateMesh(model);
figure
pdemesh(model)
5-1126
volume
mv = volume(mesh)
mv = 8.0295e-04
5-1127
5 Functions — Alphabetical List
model = createpde;
importGeometry(model,'BracketWithHole.stl');
pdegplot(model)
mesh = generateMesh(model);
figure
pdemesh(model)
5-1128
volume
Compute the volume of the entire mesh and the volume of each individual element of the
mesh. Display the volumes of the first 5 elements.
[va,vi] = volume(mesh);
vi(1:5)
ans = 1×5
10-6 ×
5-1129
5 Functions — Alphabetical List
model = createpde;
importGeometry(model,'BracketWithHole.stl');
pdegplot(model)
5-1130
volume
mesh = generateMesh(model);
figure
pdemesh(model)
Evaluate the shape quality of the mesh elements and find the elements with the quality
values less than 0.5.
Q = meshQuality(mesh);
elemIDs = find(Q < 0.5);
mv05 = 4.2568e-06
5-1131
5 Functions — Alphabetical List
Find how much of the total mesh volume belongs to these elements. Return the result as a
percentage.
mv05_percent = mv05/volume(mesh)*100
mv05_percent = 0.5301
Input Arguments
mesh — Mesh object
Mesh property of a PDEModel object | output of generateMesh
Mesh object, specified as the Mesh property of a PDEModel object or as the output of
generateMesh.
Example: model.Mesh
Output Arguments
V — Volume
positive number
Volume of the entire mesh or the combined volume of the specified elements of the mesh,
returned as a positive number.
See Also
FEMesh Properties | area | findElements | findNodes | meshQuality
5-1132
volume
Topics
“Finite Element Method Basics” on page 1-27
Introduced in R2018a
5-1133
5 Functions — Alphabetical List
wbound
(Not recommended) Write boundary condition specification file
Syntax
fid = wbound(bl,mn)
Description
fid = wbound(bl,mn) writes a Boundary file with the name [mn,'.m']. The Boundary
file is equivalent to the Boundary Condition matrix bl. The output fid is -1 if the file
could not be written.
The output file [mn,'.m'] is the name of a Boundary file. (See “Boundary Conditions by
Writing Functions” on page 2-204.)
See Also
decsg | wgeom
5-1134
wgeom
wgeom
Write geometry specification function
Note This page describes the legacy workflow. New features might not be compatible
with the legacy workflow.
Syntax
fid = wgeom(dl,mn)
Description
fid = wgeom(dl,mn) writes a Geometry file with the name [mn,'.m']. The Geometry
file is equivalent to the Decomposed Geometry matrix dl. fid returns -1 if the file could
not be written.
The output file [mn,'.m'] is the name of a Geometry file. For a description of the
Geometry file format, see “Parametrized Function for 2-D Geometry Creation” on page 2-
17.
See Also
decsg
5-1135