MATLAB 2023b Partial Differential Equation Toolbox
MATLAB 2023b Partial Differential Equation Toolbox
User's Guide
R2023b
How to Contact MathWorks
Phone: 508-647-7000
Getting Started
1
Partial Differential Equation Toolbox Product Description . . . . . . . . . . . . 1-2
Key Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
Poisson’s Equation with Complex 2-D Geometry: PDE Modeler App . . . . . 1-7
v
Geometry from Triangulated Mesh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-62
3-D Geometry from Finite Element Mesh . . . . . . . . . . . . . . . . . . . . . . . . 2-62
2-D Multidomain Geometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-64
Set Initial Condition for Model with Fine Mesh Using Solution Obtained
with Coarser Mesh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-120
vi Contents
Identify Boundary Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-127
vii
Solving PDEs
3
von Mises Effective Stress and Displacements: PDE Modeler App . . . . . . 3-3
Modal and Frequency Response Analysis for Single Part of Kinova Gen3
Robotic Arm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-39
viii Contents
Linear Elasticity Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-194
Summary of the Equations of Linear Elasticity . . . . . . . . . . . . . . . . . . . 3-194
3D Linear Elasticity Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-195
Plane Stress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-197
Plane Strain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-198
Axisymmetric Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-198
DC Conduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-217
Skin Effect in Copper Wire with Circular Cross Section: PDE Modeler App
........................................................ 3-223
ix
Poisson's Equation with Point Source and Adaptive Mesh Refinement 3-294
x Contents
Dimensions of Solutions, Gradients, and Fluxes . . . . . . . . . . . . . . . . . . 3-429
Functions
5
xi
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 PDE Toolbox
∂2 u ∂u
m +d − ∇ · c ∇u + au = f
∂t 2 ∂t
− ∇ · c ∇u + au = λdu
or
2
− ∇ · c ∇u + au = λ mu
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
n is the outward unit normal. q and g are functions defined on ∂Ω, and can be 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
∂t2 ∂t
− ∇ · c ⊗ ∇u + au = λdu
or
2
− ∇ · c ⊗ ∇u + au = λ mu
A system of PDEs with N components is N coupled PDEs with coupled boundary conditions. Scalar
PDEs are those with N = 1, meaning just one PDE. Systems of PDEs generally means N > 1. The
documentation sometimes refers to systems as multidimensional PDEs or as PDEs with a vector
solution u. In all cases, PDE systems have a single geometry and mesh. It is only N, the number of
equations, that can vary.
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
1-3
1 Getting Started
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-91.
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:
• hu = r represents a matrix h multiplying the solution vector u, and equaling the vector r.
• n · c ⊗ ∇u + qu = g. For 2-D systems, the notation n · c ⊗ ∇u means the N-by-1 matrix with
(i,1)-component
N
∂ ∂ ∂ ∂
∑ cos(α)ci, j, 1, 1
∂x
+ cos(α)ci, j, 1, 2
∂y
+ sin(α)ci, j, 2, 1
∂x
+ sin(α)ci, j, 2, 2 u
∂y j
j=1
For 3-D systems, the notation n · c ⊗ ∇u means the N-by-1 vector with (i,1)-component
N
∂ ∂ ∂
∑ sin φ cos θ ci, j, 1, 1
∂x
+ sin φ cos θ ci, j, 1, 2
∂y
+ sin φ cos θ ci, j, 1, 3 u
∂z j
j=1
N
∂ ∂ ∂
+ ∑ sin φ sin θ ci, j, 2, 1
∂x
+ sin φ sin θ ci, j, 2, 2
∂y
+ sin φ sin θ ci, j, 2, 3 u
∂z j
j=1
N
∂ ∂ ∂
+ ∑ cos θ ci, j, 3, 1
∂x
+ cos θ ci, j, 3, 2
∂y
+ cos θ ci, j, 3, 3 u
∂z j
j=1
where the outward normal vector of the boundary n = sin(φ)cos(θ), sin(φ)sin(θ), cos(φ) .
For each edge or face segment, there are a total of N boundary conditions.
See Also
Related Examples
• “Put Equations in Divergence Form” on page 2-86
• “Solve Problems Using PDEModel Objects” on page 2-3
• “f Coefficient for specifyCoefficients” on page 2-89
• “c Coefficient for specifyCoefficients” on page 2-91
• “m, d, or a Coefficient for specifyCoefficients” on page 2-106
1-4
Solve 2-D PDEs Using the PDE Modeler App
1 Start the PDE Modeler app by using the Apps tab or typing pdeModeler in the MATLAB®
Command Window. For details, see “Open the PDE Modeler App” on page 4-2.
2 Choose the application mode by selecting Application from the Options menu.
3 Create a 2-D geometry by drawing, rotating, and combining the basic shapes: circles, ellipses,
rectangles, and polygons. To draw and rotate shapes, use the Draw menu or the corresponding
toolbar buttons. To combine shapes, use the Set formula field. See “2-D Geometry Creation in
PDE Modeler App” on page 4-3.
4 Specify boundary conditions for each boundary segment. To do this, first switch to the Boundary
Mode by using the Boundary menu. Click the boundary to select it, then specify the boundary
condition for that boundary. You can have different types of boundary conditions on different
boundary segments. The default boundary condition is the Dirichlet condition hu = r with h = 1
and r = 0. You can remove unnecessary subdomain borders by selecting Remove Subdomain
Border or Remove All Subdomain Borders from the Boundary menu. For details, see
“Specify Boundary Conditions in the PDE Modeler App” on page 4-12.
5 Specify PDE coefficients by selecting PDE Mode from the PDE menu. Then select a region or
multiple regions for which you are specifying the coefficients. Select PDE Specification from
the PDE menu or click the button on the toolbar. Type the coefficients in the resulting
dialog box. For details, see “Coefficients for Scalar PDEs” on page 4-14 and “Coefficients for
Systems of PDEs” on page 4-16.
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-24.
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:
• 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-26.
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-31.
1-5
1 Getting Started
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.
• 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: PDE Modeler App” on page 1-7
• “Poisson's Equation on Unit Disk” on page 3-263
• “Current Density Between Two Metallic Conductors: PDE Modeler App” on page 3-231
• “Minimal Surface Problem” on page 3-286
1-6
Poisson’s Equation with Complex 2-D Geometry: PDE Modeler App
To solve this problem in the PDE Modeler app, follow these steps:
0.2 and the center at (0.5,0.2). To draw a circle, first click the 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.
5 Draw two rectangles: one with corners (-1,0.2), (1,0.2), (1,-0.2), and (-1,-0.2) and another with
corners (0.5,1), (1,1), (1,-0.6), and (0.5,-0.6). To draw a rectangle, first click the button.
Then click any corner and drag to draw the rectangle.
6 Model the geometry by entering (R1+C1+R2)-C2 in the Set formula field.
7 Save the model to a file by selecting File > Save As.
8 Remove the subdomain borders. To do this, switch to the boundary mode by selecting Boundary
> Boundary Mode. Then select Boundary > Remove All Subdomain Borders.
9 Specify the boundary conditions for all circle arcs. Using Shift+click, select these borders. Then
select Boundary > Specify Boundary Conditions and specify the Neumann boundary
condition with g = -5 and q = 0. This boundary condition means that the solution has a slope of –
5 in the normal direction for these boundary segments.
10 For all other boundaries, keep the default Dirichlet boundary condition: h = 1, r = 0.
11
Specify the coefficients by selecting PDE > PDE Specification or clicking the button on
the toolbar. Specify c = 1, a = 0, and f = 10.
12 Initialize the mesh by selecting Mesh > Initialize Mesh. Refine the mesh by selecting Mesh >
Refine Mesh.
1-7
1 Getting Started
13
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.
1-8
Poisson’s Equation with Complex 2-D Geometry: PDE Modeler App
1-9
1 Getting Started
1-10
Finite Element Method Basics
− ∇ ⋅ c ∇u + au = f on domain Ω
Suppose that this equation is a subject to the Dirichlet boundary condition u = r on ∂ΩD and
Neumann boundary conditions on ∂ΩN. Here, ∂Ω = ∂ΩD ∪ ∂ΩN is the boundary of Ω.
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 Ω.
Ω
∫ − ∇ · c ∇u + au − f v dΩ = 0 ∀v
The test functions are chosen from a collection of functions (functional space) that vanish on the
Dirichlet portion of the boundary, v = 0 on ∂Ω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 ∂ΩD.
Ω
∫ c ∇u ∇v + auv dΩ − ∫ n · ∂ΩN
c ∇u v d ∂ΩN + ∫n ·
∂ΩD
c ∇u v d ∂ΩD =
Ω
∫ f v dΩ ∀v
Use the Neumann boundary condition to substitute for second term on the left side of the equation.
Also, note that v = 0 on ∂ΩD nullifies the third term. The resulting equation is:
Ω
∫ c ∇u ∇v + auv dΩ + ∫ quv d ∂Ω
∂ΩN
N = ∫ gv d ∂Ω
∂ΩN
N + ∫ f v dΩ
Ω
∀v
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
e e
subdomains or elements Ω , where Ω = ∪ Ω . 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-
e
dimensional equivalent of admissible and trial functions defined on Ω , you can write the discretized
weak form of the PDE as:
∫ c ∇u ∇v
e
h h + auhvh dΩ +
e
∫ qu v
e
e
h hd ∂ΩN = ∫ gv
e
e
hd ∂ΩN +
e
∫ f v dΩ h
e
∀vh
Ω ∂ΩN ∂ΩN Ω
1-11
1 Getting Started
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 = ∑ Uiϕi
1
Here Ui are yet undetermined scalar coefficients. Substituting uh into to the discretized weak form of
PDE and using each vh = φ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. 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)ϕi(x)
i=1
dU
M + KU = F
dt
− ∇ ⋅ c ∇u + au = λ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-12
Finite Element Method Basics
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-13
2
2-2
Solve Problems Using PDEModel Objects
model = createpde();
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 “Geometry and Mesh”.
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-43.
5 Create the boundary conditions. For details, see “Specify Boundary Conditions” on page 2-128.
f = [1;2];
a = 0;
c = [1;3;5];
specifyCoefficients(model,"m",0,"d",0,"c",c,"a",a,"f",f);
generateMesh(model);
9 Call the appropriate solver. For all problems except for eigenvalue problems, call solvepde.
result = solvepdeeig(model);
2-3
2 Setting Up Your PDE
10 Examine the solution. See “Solution and Gradient Plots with pdeplot and pdeplot3D” on page 3-
376, “2-D Solution and Gradient Plots with MATLAB Functions” on page 3-385, and “3-D Solution
and Gradient Plots with MATLAB Functions” on page 3-391.
See Also
createpde | importGeometry | geometryFromEdges | pdegplot | applyBoundaryCondition |
generateMesh | pdeplot3D | pdeplot
2-4
Geometry and Mesh Components
This example shows how the toolbox represents geometries and meshes, the components of
geometries and meshes, and the relationships between them within a model object.
Geometry
The toolbox supports 2-D and 3-D geometries. Each geometry in the toolbox consists of these
components, also called geometric regions: vertices, edges, faces, and cells (for a 3-D geometry).
Each geometric region has its own label that follows these conventions:
For example, the toolbox represents a unit cube geometry with these geometric regions and labels:
Numbering of geometric regions can differ in different releases. Always check that you are assigning
parameters of a problem to the intended geometric regions by plotting the geometry and visually
inspecting its regions and their labels.
2-5
2 Setting Up Your PDE
To set up a PDE problem, the toolbox combines a geometry, mesh, PDE coefficients, boundary and
initial conditions, and other parameters into a model object. A geometry can exist outside of a model.
For example, create a unit sphere geometry.
gm1 = multisphere(1)
gm1 =
DiscreteGeometry with properties:
NumCells: 1
NumFaces: 1
NumEdges: 0
NumVertices: 0
Vertices: []
gm2 = importGeometry("Block.stl")
gm2 =
DiscreteGeometry with properties:
NumCells: 1
NumFaces: 6
NumEdges: 12
2-6
Geometry and Mesh Components
NumVertices: 8
Vertices: [8x3 double]
When a geometry exists within a model, the toolbox stores it in the Geometry property of the model
object. For example, create a model and assign the unit sphere geometry gm1 to its Geometry
property.
model1 = createpde;
model1.Geometry = gm1
model1 =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
You also can import a geometry and assign it to the Geometry property of a model in one step by
using importGeometry.
model2 = createpde;
importGeometry(model2,"Block.stl")
ans =
DiscreteGeometry with properties:
NumCells: 1
NumFaces: 6
NumEdges: 12
NumVertices: 8
Vertices: [8x3 double]
Mesh
A mesh approximates a geometry and consists of elements and nodes. The toolbox uses meshes with
triangular elements for 2-D geometries and meshes with tetrahedral elements for 3-D geometries.
Triangular elements 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.
Tetrahedral elements 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.
Each mesh component has its own label that follows these conventions:
2-7
2 Setting Up Your PDE
The mesh generator can return slightly different meshes in different releases. For example, the
number of elements in the mesh can change. Write code that does not rely on explicitly specified node
and element IDs or node and element counts.
2-8
Geometry and Mesh Components
2-9
2 Setting Up Your PDE
Geometric regions do not describe a mesh or its elements. A geometry can exist outside of a model,
while a mesh is always a property of the model.
gm = multicuboid(1,1,1);
model = createpde;
model.Geometry = gm;
generateMesh(model,"Hmin",0.5);
model
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: [1x1 FEMesh]
SolverOptions: [1x1 pde.PDESolverOptions]
A geometry, even when it is a property of a model, is stored separately from a mesh. The toolbox does
not automatically regenerate the mesh when you modify a geometry.
new_gm = multicylinder(1,1);
model.Geometry = new_gm;
pdegplot(model,"FaceAlpha",0.3)
hold on
pdemesh(model)
2-10
Geometry and Mesh Components
You must explicitly update the mesh to correspond to the current cylinder geometry.
generateMesh(model);
pdegplot(model,"FaceAlpha",0.3)
hold on
pdemesh(model)
2-11
2 Setting Up Your PDE
The toolbox enables you to find mesh elements and nodes by their geometric location or proximity to
a particular point or node. For example, you can find all elements that belong to a particular face or
cell. You also can find all nodes that belong to a particular vertex, edge, face, or cell. For details, see
findElements and findNodes.
The toolbox also enables you to find edges and faces by their proximity to a particular point or to find
only those attached to a particular geometric region:
The toolbox lets you specify parameters of each problem, such as boundary and initial conditions
(including boundary constraints and boundary loads) and PDE coefficients (including properties of
materials, internal heat sources, body loads, and electromagnetic sources) on geometric regions. For
example, you can apply boundary conditions on the top and bottom faces of this cylinder. First, create
the cylinder geometry.
2-12
Geometry and Mesh Components
gm = multicylinder(5,10);
pdegplot(gm,"FaceLabels","on","FaceAlpha",0.5);
Then, create a model, add the geometry to the model, and apply the Dirichlet boundary conditions on
the top and bottom faces of the cylinder.
model = createpde;
model.Geometry = gm;
applyBoundaryCondition(model,"dirichlet","Face",1:2,"u",0)
ans =
BoundaryCondition with properties:
BCType: 'dirichlet'
RegionType: 'Face'
RegionID: [1 2]
r: []
h: []
g: []
q: []
u: 0
EquationIndex: []
Vectorized: 'off'
2-13
2 Setting Up Your PDE
PDE solvers do not work with geometries directly. They work with the corresponding meshes instead.
For example, if you generate a coarse mesh, the PDE solver uses the discretized cylinder.
generateMesh(model,"Hmin",4);
figure
pdemesh(model)
When you solve a problem, the toolbox internally finds all mesh nodes and elements that belong to
these geometric regions and applies the specified parameters to those nodes and elements. The
discretized top and bottom of the cylinder look like polygons rather than circles.
figure
pdemesh(model)
view([34 90])
2-14
Geometry and Mesh Components
When you refine a mesh for your problem, the toolbox automatically recalculates which nodes and
elements belong to particular geometric regions and applies the specified parameters to the new
nodes and elements.
generateMesh(model);
figure
pdemesh(model)
view([34 90])
2-15
2 Setting Up Your PDE
Although the solvers apply specified parameters to mesh elements and nodes, you cannot explicitly
specify these parameters directly on mesh components. All parameters must be specified on
geometric regions. This approach prevents unintended assignments that can happen, for example,
when you refine a mesh.
2-16
2-D Geometry Creation at Command Line
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).
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.
3 A set of characters describing the unions, intersections, and set differences of the basic shapes
that make the geometry.
Basic Shapes
To create basic shapes at the command line, create a matrix whose columns each describe a basic
shape. If necessary, add extra zeros to some columns so that all columns have the same length. Write
each column using the following encoding.
Circle
Row Value
1 1 (indicates a circle)
2 x-coordinate of circle center
3 y-coordinate of circle center
4 Radius (strictly positive)
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
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
2-17
2 Setting Up Your PDE
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
Specify a matrix that has a rectangle with a circular end cap and another circular excision.
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];
In order to create a formula describing the unions and intersections of basic shapes, you need a name
for each basic shape. Give the names as a matrix whose columns contain the names of the
2-18
2-D Geometry Creation at Command Line
corresponding columns in the basic shape matrix. Pad the columns with 0 or 32 if necessary so that
each has the same length.
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. This function 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';
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';
After you have created the basic shapes, given them names, and specified a set formula, create the
geometry using decsg. Often, you also remove some or all of the resulting face boundaries.
Completing the example, combine the basic shapes using the set formula.
[dl,bt] = decsg(gd,sf,ns);
pdegplot(dl,"EdgeLabels","on","FaceLabels","on")
xlim([-1.5,1.5])
axis equal
2-19
2 Setting Up Your PDE
[dl2,bt2] = csgdel(dl,bt);
figure
pdegplot(dl2,"EdgeLabels","on","FaceLabels","on")
xlim([-1.5,1.5])
axis equal
2-20
2-D Geometry Creation at Command Line
2-21
2 Setting Up Your PDE
2-22
Parametrized Function for 2-D Geometry Creation
Required Syntax
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.
The following figure shows how the direction of parameter increase relates to label numbering. The
arrows in the figure show the directions of increasing parameter values. The black dots indicate
curve beginning and end points. The red numbers indicate region labels. The red 0 in the center of
the figure indicates that the center square is a hole.
• 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.
2-23
2 Setting Up Your PDE
• The arrows by curves 7 and 8 show region 1 to the left and region 0 to the right.
This example shows how to write a geometry function for creating a circular region. Parametrize a
circle with radius 1 centered at the origin (0,0), as follows:
x = cos t ,
y = sin t ,
0 ≤ t ≤ 2π .
A geometry function must have at least two segments. To satisfy this requirement, break up the circle
into four segments.
• 0 ≤ t ≤ π/2
• π/2 ≤ t ≤ π
• π ≤ t ≤ 3π/2
• 3π/2 ≤ t ≤ 2π
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.
2-24
Parametrized Function for 2-D Geometry Creation
Plot the geometry displaying the edge numbers and the face label.
pdegplot(@circlefunction,"EdgeLabels","on","FaceLabels","on")
axis equal
2-25
2 Setting Up Your PDE
This example shows how to create a cardioid geometry using four distinct techniques. The techniques
are ways to parametrize your geometry using arc length calculations. The cardioid satisfies the
equation r = 2 1 + cos Φ .
ezpolar("2*(1+cos(Phi))")
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.
• 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.
2-26
Parametrized Function for 2-D Geometry Creation
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
pdegplot("cardioid1","EdgeLabels","on")
axis equal
2-27
2 Setting Up Your PDE
The built-in cardg function gives a slightly different version of this technique.
You can write an integral for the arc length of a curve. If the parametrization is in terms of x u and
y u , then the arc length s t is
2 dy 2
∫
t dx
st = + du .
0 du du
For a given value s0, you can find t as the root of the equation s t = s0. 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
2-28
Parametrized Function for 2-D Geometry Creation
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("cardioid2","EdgeLabels","on")
axis equal
2-29
2 Setting Up Your PDE
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);
arcl = simplify(sqrt(diff(x)^2+diff(y)^2));
s = int(arcl,t,0,t,"IgnoreAnalyticConstraints",true)
s =
t
8 sin
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);
2-30
Parametrized Function for 2-D Geometry Creation
r = 2*(1 + cos(th));
r = expand(r)
r =
s2
4−
16
x = r*cos(th);
x = simplify(expand(x))
x =
s4 3 s2
− +4
512 16
y = r*sin(th);
y = simplify(expand(y))
y =
3/2
s 64 − s2
512
Now that you have analytic expressions for x and y in terms of the arc length s, write the geometry
function.
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
2-31
2 Setting Up Your PDE
pdegplot("cardioid3","EdgeLabels","on")
axis equal
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
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
2-32
Parametrized Function for 2-D Geometry Creation
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)
model = createpde;
geometryFromEdges(model,@cardioid2);
generateMesh(model);
pdeplot(model)
2-33
2 Setting Up Your PDE
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
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.
This example shows how to create a geometry file for a region with subdomains and a hole. It uses
the "Analytic Arc Length" section of the "Arc Length Calculations for a Geometry Function" example
2-34
Parametrized Function for 2-D Geometry Creation
and a variant of the circle function from "Geometry Function for a Circle". The geometry consists of
an outer cardioid that is divided into an upper half called subdomain 1 and a lower half called
subdomain 2. Also, the lower half 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
pdegplot(@cardg3,"EdgeLabels","on", ...
"FaceLabels","on")
axis equal
This example shows how to include additional parameters into a function for creating a 2-D geometry.
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 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)
2-36
Parametrized Function for 2-D Geometry Creation
geometryFromEdges(model,@cardioidWithEllipseGeom);
pdegplot(model,"EdgeLabels","on","FaceLabels","on")
axis equal
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
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
2-37
2 Setting Up Your PDE
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-38
Parametrized Function for 2-D Geometry Creation
2-39
2 Setting Up Your PDE
This example shows how to create a polygonal geometry using the MATLAB® polyshape function.
Then use the triangulated representation of the geometry to create an fegeometry object.
pgon =
polyshape with properties:
plot(pgon)
axis equal
2-40
Geometry from polyshape
gm = fegeometry(tr)
gm =
fegeometry with properties:
NumFaces: 1
NumEdges: 5
NumVertices: 5
NumCells: 0
Vertices: [5x3 double]
Mesh: [1x1 FEMesh]
pdegplot(gm);
Because the triangulation data results in a low-quality linear mesh, generate a new finer mesh for
further analysis.
gm = generateMesh(gm);
gm.Mesh
ans =
FEMesh with properties:
2-41
2 Setting Up Your PDE
MaxElementSize: 0.0566
MinElementSize: 0.0283
MeshGradation: 1.5000
GeometricOrder: 'quadratic'
pdemesh(gm);
2-42
STL File Import
This example shows how to import a geometry from an STL file, and then plot the geometry.
Generally, you create the STL file by exporting from a CAD system, such as SolidWorks®. For best
results, export a fine (not coarse) STL file in binary (not ASCII) format. After importing, view the
geometry using the pdegplot function. To see the face IDs, set the FaceLabels name-value pair to
"on".
View the geometry examples included with Partial Differential Equation Toolbox™.
figure
gm = fegeometry("Torus.stl");
pdegplot(gm)
figure
gm = fegeometry("Block.stl");
pdegplot(gm,FaceLabels="on",FaceAlpha=0.3)
2-43
2 Setting Up Your PDE
figure
gm = fegeometry("Plate10x10x1.stl");
pdegplot(gm,FaceLabels="on",FaceAlpha=0.3)
2-44
STL File Import
figure
gm = fegeometry("Tetrahedron.stl");
pdegplot(gm,FaceLabels="on",FaceAlpha=0.3)
2-45
2 Setting Up Your PDE
figure
gm = fegeometry("BracketWithHole.stl");
pdegplot(gm,FaceLabels="on",FaceAlpha=0.3)
2-46
STL File Import
figure
gm = fegeometry("DampingMounts.stl");
pdegplot(gm,CellLabels="on",FaceAlpha=0.3)
2-47
2 Setting Up Your PDE
figure
gm = fegeometry("MotherboardFragment1.stl");
pdegplot(gm)
2-48
STL File Import
figure
gm = fegeometry("PlateHoleSolid.stl");
pdegplot(gm,FaceLabels="on",FaceAlpha=0.3)
2-49
2 Setting Up Your PDE
figure
gm = fegeometry("PlateSquareHoleSolid.stl");
pdegplot(gm)
2-50
STL File Import
figure
gm = fegeometry("SquareBeam.stl");
pdegplot(gm,FaceLabels="on",FaceAlpha=0.3)
2-51
2 Setting Up Your PDE
figure
gm = fegeometry("BracketTwoHoles.stl");
pdegplot(gm,FaceLabels="on",FaceAlpha=0.3)
2-52
STL File Import
To see hidden portions of the geometry, rotate the figure using Rotate 3D button or the view
function. You can rotate the angle bracket to obtain the following view.
figure
pdegplot(gm,FaceLabels="on",FaceAlpha=0.3)
view([-24 -19])
2-53
2 Setting Up Your PDE
figure
gm = fegeometry("ForearmLink.stl");
pdegplot(gm,FaceLabels="on",FaceAlpha=0.3);
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.
figure
gm = fegeometry("PlateHolePlanar.stl");
pdegplot(gm,"EdgeLabels","on")
2-55
2 Setting Up Your PDE
figure
gm = fegeometry("PlateSquareHolePlanar.stl");
pdegplot(gm);
2-56
STL File Import
See Also
Related Examples
• “STEP File Import” on page 2-58
2-57
2 Setting Up Your PDE
This example shows how to import a geometry from a STEP file and then plot the geometry. After
importing, view the geometry using the pdegplot function.
Import and view the geometry examples from the STEP files included with Partial Differential
Equation Toolbox™. To see the face IDs, set the FaceLabels name-value argument to "on". To see
the labels on all faces of the geometry, set the transparency to 0.3.
figure
gm = fegeometry("AngleBlock.step");
pdegplot(gm,FaceLabels="on",FaceAlpha=0.3)
figure
gm = fegeometry("AngleBlockBlendR10.step");
pdegplot(gm,FaceLabels="on",FaceAlpha=0.3)
2-58
STEP File Import
figure
gm = fegeometry("BlockBlendR15.step");
pdegplot(gm,FaceLabels="on",FaceAlpha=0.3)
2-59
2 Setting Up Your PDE
figure
gm = fegeometry("BlockWithHole.step");
pdegplot(gm,FaceLabels="on",FaceAlpha=0.3)
2-60
STEP File Import
See Also
Related Examples
• “STL File Import” on page 2-43
2-61
2 Setting Up Your PDE
This example shows how to create an fegeometry object and a DiscreteGeometry object from a 3-
D mesh.
The tetmesh file, which is included in Partial Differential Equation Toolbox™, contains a 3-D
tetrahedral mesh. Load the data into your workspace.
load tetmesh
The imported variable tet contains a connectivity list, and the variable X contains a matrix of points.
Using these variables, create the triangulation representation.
TR = triangulation(tet,X)
TR =
triangulation with properties:
gm = fegeometry(TR)
gm =
fegeometry with properties:
NumFaces: 23
NumEdges: 50
NumVertices: 30
NumCells: 1
Vertices: [30x3 double]
Mesh: [1x1 FEMesh]
gm.Mesh
ans =
FEMesh with properties:
2-62
Geometry from Triangulated Mesh
gm = generateMesh(gm);
gm.Mesh
ans =
FEMesh with properties:
pdegplot(gm,FaceLabels="on",FaceAlpha=0.5);
Alternatively, you can create a geometry as a DiscreteGeometry object. First, create data matrices
of the appropriate sizes.
nodes = X';
elements = tet';
Then, create a PDE model and use geometryFromMesh to create a geometry from the mesh.
model = createpde;
gm = geometryFromMesh(model,nodes,elements)
2-63
2 Setting Up Your PDE
gm =
DiscreteGeometry with properties:
NumCells: 1
NumFaces: 23
NumEdges: 50
NumVertices: 30
Vertices: [30x3 double]
model.Mesh
ans =
FEMesh with properties:
generateMesh(model)
ans =
FEMesh with properties:
This example shows how to create a 2-D multidomain geometry from a planar mesh.
The MultidomainMesh2D file, which is included in Partial Differential Equation Toolbox™, contains a
2-D mesh. Load information about nodes, elements, and element-to-domain correspondence into your
workspace.
load MultidomainMesh2D
model = createpde;
2-64
Geometry from Triangulated Mesh
geometryFromMesh(model,nodes,elements,ElementIdToRegionId);
pdegplot(model,FaceLabels="on")
2-65
2 Setting Up Your PDE
Create a 3-D geometry using the MATLAB® alphaShape function. First, create an alphaShape
object of a block with a cylindrical hole. Then create a geometry from the alphaShape boundary.
[xg,yg] = meshgrid(-3:0.25:3);
xg = xg(:);
yg = yg(:);
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);
gm = fegeometry(nodes,elements)
gm =
fegeometry with properties:
NumFaces: 7
NumEdges: 14
NumVertices: 10
NumCells: 1
Vertices: [10x3 double]
Mesh: []
For a 3-D geometry created from the surface mesh, the Mesh property remains empty. To use the
geometry in an analysis, generate a mesh.
gm = generateMesh(gm);
gm.Mesh
2-66
Geometry from alphaShape
ans =
FEMesh with properties:
pdegplot(gm,FaceLabels="on",FaceAlpha=0.5);
pdemesh(gm);
2-67
2 Setting Up Your PDE
2-68
Cuboids, Cylinders, and Spheres
This example shows how to create 3-D geometries formed by one or more cubic, cylindrical, and
spherical cells by using the multicuboid, multicylinder, and multisphere functions,
respectively. With these functions, you can create stacked or nested geometries. You also can create
geometries where some cells are empty; for example, hollow cylinders, cubes, or 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
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
Vertices: []
pdegplot(gm,CellLabels="on")
2-69
2 Setting Up Your PDE
Create a geometry that consists of three nested cuboids of the same height and plot it.
Create the geometry by using the multicuboid function. The resulting geometry consists of three
cells.
gm =
DiscreteGeometry with properties:
NumCells: 3
NumFaces: 18
NumEdges: 36
NumVertices: 24
Vertices: [24x3 double]
pdegplot(gm,CellLabels="on",FaceAlpha=0.5)
2-70
Cuboids, Cylinders, and Spheres
Stacked Cylinders
Create a geometry that consists of three stacked cylinders and plot it.
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
Vertices: [5x3 double]
pdegplot(gm,CellLabels="on",FaceAlpha=0.5)
2-71
2 Setting Up Your PDE
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
Vertices: [4x3 double]
pdegplot(gm,CellLabels="on",FaceAlpha=0.5)
2-72
Cuboids, Cylinders, and Spheres
2-73
2 Setting Up Your PDE
Sphere in Cube
This example shows how to create a nested multidomain geometry consisting of a unit sphere and a
cube. The first part of the example creates a cube with a spherical cavity by using alphaShape. The
second part creates a solid sphere using tetrahedral elements, and then combines all tetrahedral
elements to obtain a solid sphere embedded in a cube.
First, create a geometry consisting of a cube with a spherical cavity. This geometry has one cell.
Extract the grid points located outside of the unit spherical region.
[x1,y1,z1] = sphere(24);
Psphere = [x1(:) y1(:) z1(:)];
Psphere = unique(Psphere,"rows");
Combine the coordinates of the rectangular grid (without the points inside the sphere) and the
surface coordinates of the unit sphere.
Pcombined = [Pcavitycube;Psphere];
Create an alphaShape object representing the cube with the spherical cavity.
figure
plot(shpCubeWithSphericalCavity,"FaceAlpha",0.4)
title("alphaShape: Cube with Spherical Cavity")
2-74
Sphere in Cube
Recover the triangulation that defines the domain of the alphaShape object.
[tri,loc] = alphaTriangulation(shpCubeWithSphericalCavity);
modelCube = createpde;
Create a geometry from the mesh and import the geometry and the mesh into the model.
[gCube,mshCube] = geometryFromMesh(modelCube,loc',tri');
figure
pdegplot(modelCube,"FaceAlpha",0.5,"CellLabels","on")
title("PDEModel: Cube with Spherical Cavity")
2-75
2 Setting Up Your PDE
Create tetrahedral elements to form a solid sphere by using the spherical shell and adding a new
node at the center. First, obtain the spherical shell by extracting facets of the spherical boundary.
faceID = nearestFace(gCube,[0 0 0]);
sphereFacets = boundaryFacets(mshCube,"Face",faceID);
sphereNodes = findNodes(mshCube,"region","Face",faceID);
Construct the tetrahedral elements by using each of the three nodes on the spherical boundary facets
and the new node at the origin.
sphereTets = [sphereFacets; newNodeID*ones(1,size(sphereFacets,2))];
Create a model that combines the cube with the spherical cavity and a sphere.
model = createpde;
Create a vector that maps all mshCube elements to cell 1, and all elements of the solid sphere to cell
2.
e2c = [ones(1,size(mshCube.Elements,2)), 2*ones(1,size(sphereTets,2))];
Add a new node at the center [0;0;0] to the nodes of the cube with the cavity.
2-76
Sphere in Cube
combinedNodes = [mshCube.Nodes,[0;0;0]];
combinedElements = [mshCube.Elements,sphereTets];
[g,msh] = geometryFromMesh(model,combinedNodes,combinedElements,e2c);
figure
pdegplot(model,"FaceAlpha",0.5,"CellLabels","on")
title("Solid Sphere in Cube")
2-77
2 Setting Up Your PDE
This example shows how to create a 3-D multidomain geometry by extruding a 2-D geometry
imported from STL data. The original 2-D geometry represents a cooled turbine blade section defined
by a 2-D profile.
Before extruding the geometry, this example modifies the original 2-D profile as follows:
model = createpde;
g = importGeometry(model,"CooledBlade2D.STL");
figure
pdegplot(model,"FaceLabels","on")
2-78
3-D Multidomain Geometry from 2-D Geometry
Translate the geometry to align the tip of the blade with the origin.
tip = [1.802091,-127.98192215];
translate(g,tip);
angle = -36.26005;
rotate(g,angle);
scale(g,[25.4 -25.4]);
figure
pdegplot(model,"FaceLabels","on")
Fill the void regions with faces and plot the resulting geometry.
g = addFace(g,{3, 4, 5, 6, 7});
figure
pdegplot(model,"FaceLabels","on")
2-79
2 Setting Up Your PDE
Extrude the geometry to create a stacked multilayer 3-D model of the blade. The thickness of each
layer is 200 mm.
figure
pdegplot(model,"CellLabels","on","FaceAlpha",0.5)
2-80
3-D Multidomain Geometry from 2-D Geometry
2-81
2 Setting Up Your PDE
This example shows how to split a single-domain block geometry into two domains. The first part of
the example generates a mesh and divides the mesh elements into two groups. The second part of the
example creates a two-domain geometry based on this division.
figure
pdemesh(modelSingleDomain)
2-82
Multidomain Geometry Reconstructed from Mesh
Find the x-coordinates of the geometric centers of all elements of the mesh. First, create an array of
the same size as elements that contains the x-coordinates of the nodes forming the mesh elements.
Each column of this vector contains the x-coordinates of 10 nodes that form an element.
elemXCoords = reshape(nodes(1,elements),10,[]);
Compute the mean of each column of this array to get a vector of the x-coordinates of the element
geometric centers.
elemXCoordsGeometricCenter = mean(elemXCoords);
Assume that all elements have the same region ID and create a matrix ElementIdToRegionId.
ElementIdToRegionId = ones(1,size(elements,2));
Find IDs of all elements for which the x-coordinate of the geometric center exceeds 60.
For the elements with centers located beyond x = 60, change the region IDs to 2.
ElementIdToRegionId(idx) = 2;
modelTwoDomain = createpde;
Using geometryFromMesh, import the mesh. Assign the elements to two cells based on their IDs.
geometryFromMesh(modelTwoDomain,nodes,elements,ElementIdToRegionId)
ans =
DiscreteGeometry with properties:
NumCells: 2
NumFaces: 74
NumEdges: 151
NumVertices: 80
Vertices: [80x3 double]
pdegplot(modelTwoDomain,"CellLabels","on","FaceAlpha",0.5)
2-83
2 Setting Up Your PDE
Highlight the elements from cell 1 in red and the elements from cell 2 in green.
elementIDsCell1 = findElements(modelTwoDomain.Mesh,"region","Cell",1);
elementIDsCell2 = findElements(modelTwoDomain.Mesh,"region","Cell",2);
figure
pdemesh(modelTwoDomain.Mesh.Nodes, ...
modelTwoDomain.Mesh.Elements(:,elementIDsCell1), ...
"FaceColor","red")
hold on
pdemesh(modelTwoDomain.Mesh.Nodes, ...
modelTwoDomain.Mesh.Elements(:,elementIDsCell2), ...
"FaceColor","green")
2-84
Multidomain Geometry Reconstructed from Mesh
When you divide mesh elements into groups and then create a multidomain geometry based on this
division, the mesh might be invalid for the multidomain geometry. For example, elements in a cell
might be touching by only a node or an edge instead of sharing a face. In this case,
geometryFromMesh throws an error saying that neighboring elements in the mesh are not properly
connected.
2-85
2 Setting Up Your PDE
− ∇ ⋅ 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
∂2 u ∂2 u 1 + y 2 ∂2 u
1 + x2 − 3xy + =0
∂x2 ∂x ∂y 2 ∂y2
In order to transform this expanded equation into the required form, you can try to match the
coefficients of the equation in divergence form to the expanded form. In divergence form, if
c1 c3
c=
c2 c4
then
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
2-86
Put Equations in Divergence Form
− ∇ ⋅ c ∇u = 0
n · c ∇u + qu = g
So when you derive a divergence form of the c coefficient, keep in mind that this coefficient appears
elsewhere.
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.
c1 c3 ux
∇ · c ∇u = ∇ ·
c2 c4 uy
∂ ∂
= c u + c3uy + c u + c4uy
∂x 1 x ∂y 2 x
= c1uxx + c4uyy + c2 + c3 uxy
So there is freedom in choosing a c matrix. If you have a Neumann boundary condition such as
n · c ∇u = 2
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.
• pdeCoefficients converts a PDE into the required form and extracts the coefficients into a
structure of double-precision numbers and function handles, which can be used by
specifyCoefficients. The pdeCoefficients function also can return a structure of symbolic
expressions, in which case you need to convert these expressions to double format before passing
them to specifyCoefficients.
• pdeCoefficientsToDouble converts symbolic PDE coefficients to double format.
2-87
2 Setting Up Your PDE
“Solve Partial Differential Equation of Nonlinear Heat Transfer” (Symbolic Math Toolbox) shows how
the Symbolic Math Toolbox functions can help you convert a PDE to the required form. “Nonlinear
Heat Transfer in Thin Plate” on page 3-249 shows the same example without the use of Symbolic
Math Toolbox.
− ∇ ⋅ c ∇u + au = f
∂2 u cos(x + y) ∂2 u 1 ∂2 u
+ + =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,
−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-3
• “Solve Problems Using PDEModel Objects” on page 2-3
• “Solve Partial Differential Equation of Nonlinear Heat Transfer” (Symbolic Math Toolbox)
2-88
f Coefficient for specifyCoefficients
∂2 u ∂u
m +d − ∇ · c ∇u + au = f
∂t2 ∂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-3. Give f
as either of the following:
• If f is constant, give a column vector with N components. For example, if N = 3, f could be:
f = [3;4;10];
• If f is not constant, give a function handle. The function must be of the form
fcoeff = fcoeffunction(location,state)
specifyCoefficients(model,"f",@fcoeffunction,...)
solvepde or solvepdeeig compute and populate the data in the location and state
structure arrays and pass this data to your function. You can define your function so that its output
depends on this data. You can use any names instead of location and state, but the function
must have exactly two arguments. To use additional arguments in your function, wrap your
function (that takes additional arguments) with an anonymous function that takes only the
location and state arguments. For example:
fcoeff = ...
@(location,state) myfunWithAdditionalArgs(location,state,arg1,arg2...)
specifyCoefficients(model,"f",fcoeff,...
• 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
2-89
2 Setting Up Your PDE
• 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.
Your function must return a matrix of size N-by-Nr, where Nr is the number of points in the location
that solvepde passes. Nr is equal to the length of the location.x or any other location field.
The function should evaluate f at these points.
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)
(5 + u(3)) x2 + y2
See Also
Related Examples
• “Put Equations in Divergence Form” on page 2-86
• “Solve Problems Using PDEModel Objects” on page 2-3
• “m, d, or a Coefficient for specifyCoefficients” on page 2-106
• “c Coefficient for specifyCoefficients” on page 2-91
2-90
c Coefficient for specifyCoefficients
In this section...
“Overview of the c Coefficient” on page 2-91
“Definition of the c Tensor Elements” on page 2-91
“Some c Vectors Can Be Short” on page 2-93
“Functional Form” on page 2-103
∂2 u ∂u
m +d − ∇ · c ∇u + au = f
∂t 2 ∂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-91. N is
the number of equations, see “Equations You Can Solve Using PDE Toolbox” on page 1-3.
To write the coefficient c for inclusion in the PDE model via specifyCoefficients, give c as either
of the following:
ccoeffunction(location,state)
solvepde or solvepdeeig pass the location and state structures to ccoeffunction. The
function must return a matrix of size N1-by-Nr, where:
• 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-93. 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.
N
∂ ∂ ∂ ∂ ∂ ∂ ∂ ∂
∑ c
∂x i, j, 1, 1 ∂x
+ c
∂x i, j, 1, 2 ∂y
+ c
∂y i, j, 2, 1 ∂x
+ c u
∂y i, j, 2, 2 ∂y j
j=1
For 3-D systems, the notation ∇ ⋅ (c ⊗ ∇u) represents an N-by-1 matrix with an (i,1)-component
2-91
2 Setting Up Your PDE
N
∂ ∂ ∂ ∂ ∂ ∂
∑ c
∂x i, j, 1, 1 ∂x
+ c
∂x i, j, 1, 2 ∂y
+ c u
∂x i, j, 1, 3 ∂z j
j=1
N
∂ ∂ ∂ ∂ ∂ ∂
+ ∑ c
∂y i, j, 2, 1 ∂x
+ c
∂y i, j, 2, 2 ∂y
+ c u
∂y i, j, 2, 3 ∂z j
j=1
N
∂ ∂ ∂ ∂ ∂ ∂
+ ∑ c
∂z i, j, 3, 1 ∂x
+ c
∂z i, j, 3, 2 ∂y
+ c u
∂z i, j, 3, 3 ∂z 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(N, 1, 1, 1) c(N, 1, 1, 2) c(N, 2, 1, 1) c(N, 2, 1, 2) ⋯ 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) ⋯ 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) ⋯ 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) ⋯ 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) ⋯ c(1, N, 3, 1) c(1, N, 3, 2) c(1, 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-92
c Coefficient for specifyCoefficients
⋮ ⋮ ⋮ ⋮ ⋱ ⋮ ⋮
2
c(4N − 3) c(4N − 1) c(8N − 3) c(8N − 1) ⋯ c(4N − 3) c(4N2 − 1)
c(4N − 2) c(4N) c(8N − 2) c(8N) ⋯ c(4N2 − 2) c(4N2)
c(10) c(13) c(16) c(9N + 10) c(9N + 13) c(9N + 16) ⋯ c(9N(N − 1) + 10) c(9N(N − 1) + 13) c(9N(N − 1) + 16)
c(11) c(14) c(17) c(9N + 11) c(9N + 14) c(9N + 17) ⋯ c(9N(N − 1) + 11) c(9N(N − 1) + 14) c(9N(N − 1) + 17)
c(12) c(15) c(18) c(9N + 12) c(9N + 15) c(9N + 18) ⋯ c(9N(N − 1) + 12) c(9N(N − 1) + 15) c(9N(N − 1) + 18)
⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋱ ⋮ ⋮ ⋮
c(9N − 8) c(9N − 5) c(9N − 2) c(18N − 8) c(18N − 5) c(18N − 2) ⋯ c(9N2 − 8) c(9N2 − 5) c(9N2 − 2)
c(9N − 7) c(9N − 4) c(9N − 1) c(18N − 7) c(18N − 4) c(18N − 1) ⋯ c(9N2 − 7) c(9N2 − 4) c(9N2 − 1)
c(9N − 6) c(9N − 3) c(9N) c(18N − 6) c(18N − 3) c(18N) ⋯ c(9N2 − 6) c(9N2 − 3) c(9N2)
2-D Systems
2-93
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 ⋯ 0 0
0 c 0 0 ⋯ 0 0
0 0 c 0 ⋯ 0 0
0 0 0 c ⋯ 0 0
⋮⋮ ⋮⋮ ⋱ ⋮⋮
0 0 0 0 ⋯ c 0
0 0 0 0 ⋯ 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 ⋯ 0 0
0 c(2) 0 0 ⋯ 0 0
0 0 c(1) 0 ⋯ 0 0
0 0 0 c(2) ⋯ 0 0
⋮ ⋮ ⋮ ⋮ ⋱ ⋮ ⋮
0 0 0 0 ⋯ c(1) 0
0 0 0 0 ⋯ 0 c(2)
The software interprets a three-element column vector c as a symmetric block diagonal matrix, with
c(i,i,1,1) = c(1), c(i,i,2,2) = c(3), and c(i,i,1,2) = c(i,i,2,1) = c(2).
c(1) c(2) 0 0 ⋯ 0 0
c(2) c(3) 0 0 ⋯ 0 0
0 0 c(1) c(2) ⋯ 0 0
0 0 c(2) c(3) ⋯ 0 0
⋮ ⋮ ⋮ ⋮ ⋱ ⋮ ⋮
0 0 0 0 ⋯ c(1) c(2)
0 0 0 0 ⋯ c(2) c(3)
2-94
c Coefficient for specifyCoefficients
c(1) c(3) 0 0 ⋯ 0 0
c(2) c(4) 0 0 ⋯ 0 0
0 0 c(1) c(3) ⋯ 0 0
0 0 c(2) c(4) ⋯ 0 0
⋮ ⋮ ⋮ ⋮ ⋱ ⋮ ⋮
0 0 0 0 ⋯ c(1) c(3)
0 0 0 0 ⋯ c(2) c(4)
c(1) 0 0 0 ⋯ 0 0
0 c(1) 0 0 ⋯ 0 0
0 0 c(2) 0 ⋯ 0 0
0 0 0 c(2) ⋯ 0 0
⋮ ⋮ ⋮ ⋮ ⋱ ⋮ ⋮
0 0 0 0 ⋯ c(N) 0
0 0 0 0 ⋯ 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-95
2 Setting Up Your PDE
c(1) 0 0 0 ⋯ 0 0
0 c(2) 0 0 ⋯ 0 0
0 0 c(3) 0 ⋯ 0 0
0 0 0 c(4) ⋯ 0 0
⋮ ⋮ ⋮ ⋮ ⋱ ⋮ ⋮
0 0 0 0 ⋯ c(2N − 1) 0
0 0 0 0 ⋯ 0 c(2N)
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
The software interprets a 3N-element column vector c as a symmetric block diagonal matrix.
c(1) c(2) 0 0 ⋯ 0 0
c(2) c(3) 0 0 ⋯ 0 0
0 0 c(4) c(5) ⋯ 0 0
0 0 c(5) c(6) ⋯ 0 0
⋮ ⋮ ⋮ ⋮ ⋱ ⋮ ⋮
0 0 0 0 ⋯ c(3N − 2) c(3N − 1)
0 0 0 0 ⋯ c(3N − 1) c(3N)
2-96
c Coefficient for specifyCoefficients
c(1) c(3) 0 0 ⋯ 0 0
c(2) c(4) 0 0 ⋯ 0 0
0 0 c(5) c(7) ⋯ 0 0
0 0 c(6) c(8) ⋯ 0 0
⋮ ⋮ ⋮ ⋮ ⋱ ⋮ ⋮
0 0 0 0 ⋯ c(4N − 3) c(4N − 1)
0 0 0 0 ⋯ c(4N − 2) c(4N)
⋮ ⋮ ⋮ ⋮ ⋱ ⋮ ⋮
• • • • ⋯ c(N(2N + 1) − 2) c(N(2N + 1) − 1)
• • • • ⋯ • c(N(2N + 1))
Coefficient c(i,j,k,l), for i < j, is in row (2j2 – 3j + 4i + 2l + k – 5) of the vector c. For i = j, coefficient
c(i,j,k,l) is in row (2i2 + i + l + k – 4) of the vector c.
4N2-Element Column Vector c, 2-D Systems
⋮ ⋮ ⋮ ⋮ ⋱ ⋮ ⋮
c(4N − 3) c(4N − 1) c(8N − 3) c(8N − 1) ⋯ c(4N2 − 3) c(4N2 − 1)
c(4N − 2) c(4N) c(8N − 2) c(8N) ⋯ c(4N2 − 2) c(4N2)
3-D Systems
2-97
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 ⋯ 0 0 0
0 c 0 0 0 0 ⋯ 0 0 0
0 0 c 0 0 0 ⋯ 0 0 0
0 0 0 c 0 0 ⋯ 0 0 0
0 0 0 0 c 0 ⋯ 0 0 0
0 0 0 0 0 c ⋯ 0 0 0
⋮⋮ ⋮ ⋮⋮ ⋮⋱ ⋮⋮ ⋮
0 0 0 0 0 0 ⋯ c 0 0
0 0 0 0 0 0 ⋯ 0 c 0
0 0 0 0 0 0 ⋯ 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 ⋯ 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)
The software interprets a six-element column vector c as a symmetric block diagonal matrix, with
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)
2-98
c Coefficient for specifyCoefficients
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(N) 0 0
0 0 0 0 0 0 ⋯ 0 c(N) 0
0 0 0 0 0 0 ⋯ 0 0 c(N)
2-99
2 Setting Up Your PDE
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:
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)
2-100
c Coefficient for specifyCoefficients
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(3N − 2) 0 0
0 0 0 0 0 0 ⋯ 0 c(3N − 1) 0
0 0 0 0 0 0 ⋯ 0 0 c(3N)
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)
you cannot give c as [c1;c2;c3;c4;c5;c6;c7;c8;c9], because the software interprets this vector
as the 9-element form
2-101
2 Setting Up Your PDE
The software interprets a 6N-element column vector c as a symmetric block diagonal matrix. In the
following diagram, • means the entry is symmetric.
2-102
c Coefficient for specifyCoefficients
c(1) c(2) c(4) c(7) c(10) c(13) ⋯ c(3(N − 1)(3(N − 1) + 1)/2 + 1 c(3(N − 1)(3(N − 1) + 1)/2 + 4 c(3(N − 1)(3(N − 1) + 1)/2 + 7
• c(3) c(5) c(8) c(11) c(14) ⋯ c(3(N − 1)(3(N − 1) + 1)/2 + 2 c(3(N − 1)(3(N − 1) + 1)/2 + 5 c(3(N − 1)(3(N − 1) + 1)/2 + 8
• • c(6) c(9) c(12) c(15) ⋯ c(3(N − 1)(3(N − 1) + 1)/2 + 3 c(3(N − 1)(3(N − 1) + 1)/2 + 6 c(3(N − 1)(3(N − 1) + 1)/2 + 9
• • • c(16) c(17) c(19) ⋯ c(3(N − 1)(3(N − 1) + 1)/2 + 10 c(3(N − 1)(3(N − 1) + 1)/2 + 13 c(3(N − 1)(3(N − 1) + 1)/2 + 16
• • • • c(18) c(20) ⋯ c(3(N − 1)(3(N − 1) + 1)/2 + 11 c(3(N − 1)(3(N − 1) + 1)/2 + 14 c(3(N − 1)(3(N − 1) + 1)/2 + 17
• • • • • c(21) ⋯ c(3(N − 1)(3(N − 1) + 1)/2 + 12 c(3(N − 1)(3(N − 1) + 1)/2 + 15 c(3(N − 1)(3(N − 1) + 1)/2 + 18
⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋱ ⋮ ⋮ ⋮
• • • • • • ⋯ c(3N(3N + 1)/2 − 5) c(3N(3N + 1)/2 − 4) c(3N(3N + 1)/2 − 2)
• • • • • • ⋯ • c(3N(3N + 1)/2 − 3) c(3N(3N + 1)/2 − 1)
• • • • • • ⋯ • • c(3N(3N + 1)/2)
Coefficient c(i,j,k,l), for i < j, is in row (9(j–1)(j–2)/2 + 6(j–1) + 9i + 3l + k – 12) of the vector c. For
i = j, coefficient c(i,j,k,l) is in row (9(i–1)(i–2)/2 + 15(i–1) + 1/2l(l–1) + k) of the vector c.
9N2-Element Column Vector c, 3-D Systems
c(10) c(13) c(16) c(9N + 10) c(9N + 13) c(9N + 16) ⋯ c(9N(N − 1) + 10) c(9N(N − 1) + 13) c(9N(N − 1) + 16)
c(11) c(14) c(17) c(9N + 11) c(9N + 14) c(9N + 17) ⋯ c(9N(N − 1) + 11) c(9N(N − 1) + 14) c(9N(N − 1) + 17)
c(12) c(15) c(18) c(9N + 12) c(9N + 15) c(9N + 18) ⋯ c(9N(N − 1) + 12) c(9N(N − 1) + 15) c(9N(N − 1) + 18)
⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋱ ⋮ ⋮ ⋮
c(9N − 8) c(9N − 5) c(9N − 2) c(18N − 8) c(18N − 5) c(18N − 2) ⋯ c(9N2 − 8) c(9N2 − 5) c(9N2 − 2)
c(9N − 7) c(9N − 4) c(9N − 1) c(18N − 7) c(18N − 4) c(18N − 1) ⋯ c(9N2 − 7) c(9N2 − 4) c(9N2 − 1)
c(9N − 6) c(9N − 3) c(9N) c(18N − 6) c(18N − 3) c(18N) ⋯ c(9N2 − 6) c(9N2 − 3) c(9N2)
Functional Form
If your c coefficient is not constant, represent it as a function of the form
ccoeff = ccoeffunction(location,state)
specifyCoefficients(model,"c",@ccoeffunction,...)
solvepde or solvepdeeig compute and populate the data in the location and state structure
arrays and pass this data to your function. You can define your function so that its output depends on
this data. You can use any names instead of location and state, but the function must have exactly
two arguments. To use additional arguments in your function, wrap your function (that takes
additional arguments) with an anonymous function that takes only the location and state
arguments. For example:
2-103
2 Setting Up Your PDE
ccoeff = ...
@(location,state) myfunWithAdditionalArgs(location,state,arg1,arg2...)
specifyCoefficients(model,"c",ccoeff,...
• 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.
• 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-93. 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.
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 2 2
1 + u(1) + u(3)
c=
u(2)
2 2
1 + x2 + y2
1 + u(1) + u(3)
s1(x, y) −1
−1 s1(x, y)
where unlisted elements are zero. Here s1(x,y) is 5 in subdomain 1, and is 10 in subdomain 2.
2-104
c Coefficient for specifyCoefficients
This c is a symmetric, block-diagonal matrix with different coefficients in each block. So it is natural
to represent c as a “3N-Element Column Vector c, 2-D Systems” on page 2-96:
c(1) c(2) 0 0 ⋯ 0 0
c(2) c(3) 0 0 ⋯ 0 0
0 0 c(4) c(5) ⋯ 0 0
0 0 c(5) c(6) ⋯ 0 0
⋮ ⋮ ⋮ ⋮ ⋱ ⋮ ⋮
0 0 0 0 ⋯ c(3N − 2) c(3N − 1)
0 0 0 0 ⋯ c(3N − 1) c(3N)
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
• “Put Equations in Divergence Form” on page 2-86
• “Solve Problems Using PDEModel Objects” on page 2-3
• “f Coefficient for specifyCoefficients” on page 2-89
• “m, d, or a Coefficient for specifyCoefficients” on page 2-106
2-105
2 Setting Up Your PDE
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
∂t 2 ∂t
− ∇ · c ⊗ ∇u + au = λdu
or
2
− ∇ · c ⊗ ∇u + au = λ mu
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-1329.
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
2-106
m, d, or a Coefficient for specifyCoefficients
a 0 ⋯ 0
0 a ⋯ 0
⋮⋮ ⋱⋮
0 0 ⋯ a
d(1) 0 ⋯ 0
0 d(2) ⋯ 0
⋮ ⋮ ⋱ ⋮
0 0 ⋯ 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.
2-107
2 Setting Up Your PDE
solvepde or solvepdeeig compute and populate the data in the location and state structure
arrays and pass this data to your function. You can define your function so that its output depends on
this data. You can use any names instead of location and state, but the function must have exactly
two arguments. To use additional arguments in your function, wrap your function (that takes
additional arguments) with an anonymous function that takes only the location and state
arguments. For example:
dcoeff = ...
@(location,state) myfunWithAdditionalArgs(location,state,arg1,arg2...)
specifyCoefficients(model,"d",dcoeff,...
• 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.
• 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-106. 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.
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-108
m, d, or a Coefficient for specifyCoefficients
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
• “Put Equations in Divergence Form” on page 2-86
• “Solve Problems Using PDEModel Objects” on page 2-3
• “f Coefficient for specifyCoefficients” on page 2-89
• “c Coefficient for specifyCoefficients” on page 2-91
2-109
2 Setting Up Your PDE
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
specifyCoefficients(model,"m",0,"d",0,"c",1,"a",0,"f",2);
2-110
View, Edit, and Delete PDE Coefficients
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);
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)
coefv = model.EquationCoefficients.CoefficientAssignments;
delete(coefv(2))
2-111
2 Setting Up Your PDE
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-112
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.
setInitialConditions(model,15);
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);
function u0 = initfun(location)
solvepde computes and populates the data in the location structure array and passes this data to
your function. You can define your function so that its output depends on this data. You can use any
name instead of location. To use additional arguments in your function, wrap your function (that
takes additional arguments) with an anonymous function that takes only the location argument. For
example:
u0 = @(location) initfunWithAdditionalArgs(location,arg1,arg2...)
setInitialConditions(model,u0)
2-113
2 Setting Up Your PDE
location is a structure array with fields location.x, location.y, and, for 3-D problems,
location.z. Your function must return a matrix u0 of size N-by-M, where N is the number of
equations in your PDE and M = length(location.x). The fields in location are row vectors.
∂2 u 3+x
2
− ∇ · ∇u =
∂t 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
4−x−y
u and an initial value of the 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);
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)
2-114
Set Initial Conditions
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-3
• “Wave Equation on Square Domain” on page 3-346
• “Inhomogeneous Heat Equation on Square Domain” on page 3-325
• “Heat Distribution in Circular Cylindrical Rod” on page 3-329
• “Heat Transfer Problem with Temperature-Dependent Properties” on page 3-310
• “Dynamic Analysis of Clamped Beam” on page 3-27
2-115
2 Setting Up Your PDE
This example shows how to solve a nonlinear PDE system of two equations with cross-coupling
between the two components. The system is a Schnakenberg system
∂u1
− D1 Δu1 = κ a − u1 + u12u2
∂t
∂u2
− D2 Δu2 = κ b − u12u2
∂t
b
with the steady-state solution u1S = a + b and u2S = 2
. The initial conditions are a small
a+b
perturbation of the steady-state solution.
Generate the mesh using the linear geometric order to save memory.
generateMesh(model,"GeometricOrder","linear");
Based on these parameters, specify the PDE coefficients in the toolbox format.
d = [1;1];
c = [D1;D2];
f = @(region,state) [kappa*(a - state.u(1,:) + ...
state.u(1,:).^2.*state.u(2,:));
kappa*(b - state.u(1,:).^2.*state.u(2,:))
];
specifyCoefficients(model,"m",0,"d",d,"c",c,"a",0,"f",f);
Set the initial conditions. The first component is a small perturbation of the steady-state solution
b
u1S = a + b. The second component is the steady-state solution u2S = 2
.
a+b
setInitialConditions(model,icFcn);
2-116
Nonlinear System with Cross-Coupling Between Components
tlist = linspace(0,2,10);
results = solvepde(model,tlist);
Plot the first component of the solution at the last time step.
pdeplot3D(model,"ColorMapData",results.NodalSolution(:,1,end));
Now, resume the analysis and solve the problem for times from 2 to 5 seconds. Reduce the magnitude
of the previously obtained solution for time 2 seconds to 10% of the original value.
u2 = results.NodalSolution(:,:,end);
newResults = createPDEResults(model,u2(:)*0.1);
setInitialConditions(model,newResults);
tlist = linspace(2,5,10);
results25 = solvepde(model,tlist);
Plot the first component of the solution at the last time step.
2-117
2 Setting Up Your PDE
figure
pdeplot3D(model,"ColorMapData",results25.NodalSolution(:,1,end));
Alternatively, you can write a function that uses the results returned by the solver and computes the
initial conditions based on the results of the previous analysis.
delete(model.InitialConditions);
setInitialConditions(model,NewIC)
ans =
GeometricInitialConditions with properties:
RegionType: 'cell'
RegionID: 1
InitialValue: @(location)computeNewIC(results)
InitialDerivative: []
2-118
Nonlinear System with Cross-Coupling Between Components
results25f = solvepde(model,tlist);
Plot the first component of the solution at the last time step.
figure
pdeplot3D(model,"ColorMapData",results25f.NodalSolution(:,1,end));
2-119
2 Setting Up Your PDE
Set Initial Condition for Model with Fine Mesh Using Solution
Obtained with Coarser Mesh
Set initial conditions for a model with a fine mesh by using the coarse-mesh solution from a previous
analysis.
Create a PDE model and include the geometry of the built-in function squareg.
model = createpde;
geometryFromEdges(model,@squareg);
Specify the coefficients, apply boundary conditions, and set initial conditions.
specifyCoefficients(model,"m",0,"d",1,"c",5,"a",0,"f",0.1);
applyBoundaryCondition(model,"dirichlet","Edge",1,"u",1);
setInitialConditions(model,10);
Generate a comparatively coarse mesh with the target maximum element edge length of 0.1.
generateMesh(model,"Hmax",0.1);
Solve the model for the entire time span of 0 through 0.02 seconds.
tlist = linspace(0,2E-2,20);
Rtotal = solvepde(model,tlist);
Interpolate the solution at the origin for the entire time span.
singleSpanSol = Rtotal.interpolateSolution(0,0,1:numel(tlist));
Now solve the model for the first half of the time span. You will use this solution as an initial condition
when solving the model with a finer mesh for the second half of the time span.
tlist1 = linspace(0,1E-2,10);
R1 = solvepde(model,tlist1);
Generate a finer mesh by setting the target maximum element edge length to 0.05.
generateMesh(model,"Hmax",0.05);
Use the coarse mesh model results as the initial condition for the model with the finer mesh. For the
definition of the icFcn function, see Initial Conditions Function on page 2-121.
setInitialConditions(model,@(region) icFcn(region,interpolant));
Solve the model for the second half of the time span.
tlist2 = linspace(1E-2,2E-2,10);
R2 = solvepde(model,tlist2);
Interpolate the solutions at the origin for the first and the second halves of the time span.
2-120
Set Initial Condition for Model with Fine Mesh Using Solution Obtained with Coarser Mesh
multispanSol1 = R1.interpolateSolution(0,0,1:numel(tlist1));
multispanSol2 = R2.interpolateSolution(0,0,1:numel(tlist2));
figure
plot(tlist,singleSpanSol)
hold on
plot(tlist1, multispanSol1,"r*")
plot(tlist2, multispanSol2,"ko")
legend("Overall solution","Coarse mesh solution", "Fine mesh solution")
function u0 = icFcn(region,interpolant)
u0 = interpolant(region.x',region.y');
end
2-121
2 Setting Up Your PDE
A PDE model stores initial conditions in its InitialConditions property. Suppose model is the
name of your model. Obtain the initial conditions:
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
Specify constant initial conditions over all the regions in the model.
setInitialConditions(model,2);
2-122
View, Edit, and Delete Initial Conditions
setInitialConditions(model,3,"Face",2);
setInitialConditions(model,4,"Face",3);
ics = model.InitialConditions;
findInitialConditions(ics,"Face",2)
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))
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.
2-123
2 Setting Up Your PDE
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-124
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
Boundary conditions, either Dirichlet or generalized Neumann, apply only to boundaries between the
interior and exterior of the region. This is because the toolbox formulation uses the weak form of
PDEs. See “Finite Element Method Basics” on page 1-11. In the weak formulation you do not specify
boundary conditions between subdomains, even if coefficients are discontinuous between
subdomains. So the toolbox does not support defining boundary conditions on subdomain boundaries.
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", ...
"FaceLabels","on")
xlim([-1.1 1.1])
axis equal
2-125
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-126
Identify Boundary Labels
You can see the edge labels by using the pdegplot function with the EdgeLabels name-value pair
set to "on":
pdegplot(g,"EdgeLabels","on")
2-127
2 Setting Up Your PDE
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 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".
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-131.
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.
If the solution on edges or faces [e1,e2,e3] satisfies the equation 2u = 3, specify the boundary
condition as follows.
2-128
Specify Boundary Conditions
Systems of PDEs
The Dirichlet boundary condition for a system of PDEs is hu = r, where h is a matrix, u is the solution
vector, and r is a vector.
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.
• 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", ...
"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”. 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
2-129
2 Setting Up Your PDE
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 Ω
n is the outward unit normal. q and g 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.
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.
% For 3-D geometry:
applyBoundaryCondition(model,"neumann","Face",[e1,e2,e3],"q",2,"g",3);
% For 2-D geometry:
applyBoundaryCondition(model,"neumann","Edge",[e1,e2,e3],"q",2,"g",3);
Systems of PDEs
Neumann boundary conditions for a system of PDEs is n · c ⊗ ∇u + qu = g. For 2-D systems, the
notation n · c ⊗ ∇u means the N-by-1 vector with (i,1)-component
N
∂ ∂ ∂ ∂
∑ cos(α)ci, j, 1, 1
∂x
+ cos(α)ci, j, 1, 2
∂y
+ sin(α)ci, j, 2, 1
∂x
+ sin(α)ci, j, 2, 2 u
∂y j
j=1
For 3-D systems, the notation n · c ⊗ ∇u means the N-by-1 vector with (i,1)-component
N
∂ ∂ ∂
∑ sin φ cos θ ci, j, 1, 1
∂x
+ sin φ cos θ ci, j, 1, 2
∂y
+ sin φ cos θ ci, j, 1, 3 u
∂z j
j=1
N
∂ ∂ ∂
+ ∑ sin φ sin θ ci, j, 2, 1
∂x
+ sin φ sin θ ci, j, 2, 2
∂y
+ sin φ sin θ ci, j, 2, 3 u
∂z j
j=1
N
∂ ∂ ∂
+ ∑ cos θ ci, j, 3, 1
∂x
+ cos θ ci, j, 3, 2
∂y
+ cos θ ci, j, 3, 3 u
∂z j
j=1
where the outward normal vector of the boundary n = sin(φ)cos(θ), sin(φ)sin(θ), cos(φ) . 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);
% For 2-D geometry:
applyBoundaryCondition(model,"neumann","Edge",[e1,e2,e3],"q",Q,"g",G);
2-130
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”. 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];
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);
2-131
2 Setting Up Your PDE
"r",@myrfun);
applyBoundaryCondition(model,"neumann", ...
"Face",2, ...
"g",@mygfun,"q",@myqfun);
applyBoundaryCondition(model,"mixed", ...
"Edge",[3,4], ...
"u",@myufun, ...
"EquationIndex",[2,3]);
solvepde or solvepdeeig compute and populate the data in the location and state structure
arrays and pass this data to your function. You can define your function so that its output depends on
this data. You can use any names instead of location and state, but the function must have exactly
two arguments.
• 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.
Furthermore, if there are Neumann conditions, then solvers pass the following data in the
location structure.
• state.u contains the solution vector at evaluation points. state.u is an N-by-M matrix,
where each column corresponds to one evaluation point, and M is the number of evaluation
points.
• state.time contains the time at evaluation points. state.time is a scalar.
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”.
2-132
Specify Boundary Conditions
If boundary conditions depend on state.u or state.time, ensure that your function returns a
matrix of NaN of the correct size when state.u or state.time are NaN. Solvers check whether a
problem is nonlinear or time-dependent by passing NaN state values, and looking for returned NaN
values.
uVal = ...
@(location,state) myfunWithAdditionalArgs(location,state,arg1,arg2...)
applyBoundaryCondition(model,"mixed", ...
"Edge",[3,4], ...
"u",uVal, ...
"EquationIndex",[2,3]);
2-133
2 Setting Up Your PDE
This example shows how to apply various constant boundary condition specifications for both scalar
PDEs and systems of PDEs.
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-134
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);
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-135
2 Setting Up Your PDE
System of PDEs
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);
2-136
Solve PDEs with Constant Boundary Conditions
Solve an elliptic PDE with these boundary conditions using 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;
pdeplot(model,"XYData",u(:,2),"ZData",u(:,2))
See Also
More About
• “Specify Boundary Conditions” on page 2-128
• “Specify Nonconstant Boundary Conditions” on page 2-138
2-137
2 Setting Up Your PDE
model = createpde;
Include a unit square geometry in the model and plot the geometry.
geometryFromEdges(model,@squareg);
pdegplot(model,"EdgeLabels","on")
xlim([-1.1 1.1])
ylim([-1.1 1.1])
Generate a mesh with a maximum edge length of 0.25. Plot the mesh.
generateMesh(model,"Hmax",0.25);
figure
pdemesh(model)
2-138
Specify Nonconstant Boundary Conditions
Write a function that returns the value u x, y = 52 + 20x to represent the Dirichlet boundary
condition for edge 1.
function bc = bcfuncD(location,state)
bc = 52 + 20*location.x;
scatter(location.x,location.y,"filled","black");
hold on
end
Write a function that returns the value u x, y = cos x2 to represent the Neumann boundary condition
for edge 3.
function bc = bcfuncN(location,state)
bc = cos(location.x).^2;
scatter(location.x,location.y,"filled","red");
hold on
end
The scatter plot command in each of these functions enables you to visualize the location data used
by the toolbox. For Dirichlet boundary conditions, the location data (black markers on edge 1)
2-139
2 Setting Up Your PDE
corresponds with the mesh nodes. Each element of a quadratic mesh has nodes at its corners and
edge centers. For Neumann boundary conditions, the location data (red markers on edge 3)
corresponds with the quadrature integration points.
Specify the boundary condition for edges 1 and 3 using the functions that you wrote.
applyBoundaryCondition(model,"dirichlet", ...
"Edge",1, ...
"u",@bcfuncD);
applyBoundaryCondition(model,"neumann", ...
"Edge",3, ...
"g",@bcfuncN);
specifyCoefficients(model,"m",0,"d",0,"c",1, ...
"a",0,"f",10);
results = solvepde(model);
figure
pdeplot(model,"XYData",results.NodalSolution)
2-140
Specify Nonconstant Boundary Conditions
applyBoundaryCondition(model,"dirichlet", ...
"Edge",1, ...
"u",bcfuncD);
Additional Arguments
If a function that represents a nonconstant boundary condition requires more arguments than
location and state, follow these steps:
1 Write a function that takes the location and state arguments and the additional arguments.
2 Wrap that function with an anonymous function that takes only the location and state
arguments.
2-141
2 Setting Up Your PDE
For example, define boundary conditions on edge 1 as u x, y = 52a2 + 20bx + c. First, write the
function that takes the arguments a, b, and c in addition to the location and state arguments.
function bc = bcfunc_abc(location,state,a,b,c)
bc = 52*a^2 + 20*b*location.x + c;
end
Because a function defining nonconstant boundary conditions must have exactly two arguments, wrap
the bcfunc_abc function with an anonymous function.
Now you can use bcfunc_add_args to specify a boundary condition for edge 1.
applyBoundaryCondition(model,"dirichlet", ...
"Edge",1, ...
"u",bcfunc_add_args);
System of PDEs
Create a model for a system of two equations.
model = createpde(2);
Use the same unit square geometry that you used for the scalar PDE problem.
geometryFromEdges(model,@squareg);
The first component on edge 1 satisfies the equation u1 x, y = 52 + 20x + 10sin πx3 . The second
component on edge 1 satisfies the equation u1 x, y = 52 − 20x − 10sin πx3 .
Specify the boundary condition for edge 1 using the myufun function.
applyBoundaryCondition(model,"dirichlet","Edge",1, ...
"u",@myufun);
specifyCoefficients(model,"m",0,"d",0,"c",1, ...
"a",0,"f",[10;-10]);
Generate a mesh.
generateMesh(model);
results = solvepde(model);
u = results.NodalSolution;
2-142
Specify Nonconstant Boundary Conditions
figure
pdeplot(model,"XYData",u(:,1))
figure
pdeplot(model,"XYData",u(:,2))
2-143
2 Setting Up Your PDE
2-144
Specify Nonconstant PDE Coefficients
model = createpde;
geometryFromEdges(model,@squareg);
Generate a mesh with a maximum edge length of 0.25. Plot the mesh.
generateMesh(model,"Hmax",0.25);
pdemesh(model)
2-145
2 Setting Up Your PDE
populate the data in the location and state structure arrays and pass this data to your function.
To visualize the location data used by the toolbox, add the scatter plot command to your function.
Specify the PDE coefficients using the function that you wrote for the f coefficient.
specifyCoefficients(model,"m",0, ...
"d",0, ...
"c",1, ...
"a",0, ...
"f",@fcoefffunc);
Apply the Dirichlet boundary condition u = 0 for all edges of the square.
applyBoundaryCondition(model,"dirichlet","Edge",1:4,"u",0);
results = solvepde(model);
figure
pdeplot(model,"XYData",results.NodalSolution)
2-146
Specify Nonconstant PDE Coefficients
f = @(location,state)location.x.^2.*sin(location.y);
specifyCoefficients(model,"m",0, ...
"d",0, ...
"c",1, ...
"a",0, ...
"f",f);
Additional Arguments
If a function that represents a nonconstant PDE coefficient requires more arguments than location
and state, follow these steps:
1 Write a function that takes the location and state arguments and the additional arguments.
2 Wrap that function with an anonymous function that takes only the location and state
arguments.
2-147
2 Setting Up Your PDE
For example, define the coefficient f as f x, y = ax2sin by + c. First, write the function that takes the
arguments a, b, and c in addition to the location and state arguments.
Because functions defining nonconstant coefficients must have exactly two arguments, wrap the
fcoefffunc_abc function with an anonymous function.
fcoefffunc_add_args = ...
@(location,state) fcoefffunc_abc(location,state,1,2,3);
specifyCoefficients(model,"m",0, ...
"d",0, ...
"c",1, ...
"a",0, ...
"f",fcoefffunc_add_args);
2-148
Nonconstant Parameters of Finite Element Model
• Young's modulus, Poisson's ratio, shear modulus, and mass density (can depend on space only)
• Surface traction on the boundary
• Pressure normal to the boundary
• Concentrated force at a vertex
• Distributed spring stiffness for each translational direction used to model elastic foundation
• Enforced displacement and its components
• Initial displacement and velocity (can depend on space only)
For thermal problems, these nonconstant parameters can depend on space, temperature, and time:
For harmonic electromagnetic problems, these parameters can also depend on frequency:
2-149
2 Setting Up Your PDE
For nonlinear magnetostatic analysis, these parameters can also depend on the magnetic potential,
its gradients, and the norm of the magnetic flux density:
Function Form
For all parameters, except the initial temperature, displacement, and velocity, the function must be of
the form:
For the initial temperature, displacement, and velocity, the function must be of the form:
Furthermore, for boundary conditions, the solver passes this data in the location structure:
2-150
Nonconstant Parameters of Finite Element Model
To save time in function handle evaluation, location can contain multiple evaluation points. When
you use a unified femodel workflow, function handles for nonconstant parameters must support
computing in a vectorized fashion. For details about vectorized computations, see “Vectorization”. For
example, specify the nonconstant pressure load on a geometry face.
val = ...
@(location,state) myfunWithAdditionalArgs(location,state,arg1,arg2...)
model.EdgeBC(1) = edgeBC(Temperature=val)
Structural material properties (Young's modulus, Poisson's ratio, and shear modulus) and initial
conditions get this data from the solver:
If a parameter represents a vector value, such as surface traction, spring stiffness, force,
displacement, or velocity, your 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 parameter value (a vector) at
the boundary coordinates provided by the solver.
Note For vector values of Young's modulus, Poisson's ratio, and shear modulus, your function must
return a three-row matrix for both 2-D and 3-D models.
2-151
2 Setting Up Your PDE
If a parameter represents a scalar value, such as pressure, displacement component, or mass density,
your function must return a row vector where each element corresponds to the parameter value (a
scalar) at the boundary coordinates provided by the solver.
Boundary conditions (temperature on the boundary, heat flux, and convection coefficient) get this
data from the solver:
For all thermal parameters, except for thermal conductivity, your function must return a row vector
thermalVal with the number of columns equal to the number of evaluation points, for example, M =
length(location.y).
For thermal conductivity, your function must return a matrix with the 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, for example, M =
length(location.y). For details about dimensions of the matrix, see “c Coefficient for
specifyCoefficients” on page 2-91.
If parameters depend on time or temperature, ensure that your function returns a matrix of NaN
values of the correct size when state.u or state.time are NaN. Solvers check whether a problem
is time dependent by passing NaN state values and looking for returned NaN values.
2-152
Nonconstant Parameters of Finite Element Model
• Subdomain ID
Charge density, current density, magnetization, surface current density on the boundary, electric or
magnetic field on the boundary, and initial conditions get this data from the solver:
Voltage or magnetic potential on the boundary get this data from the solver:
If relative permittivity, relative permeability, or conductivity for a harmonic analysis depends on the
frequency, ensure that your function returns a matrix of NaN values of the correct size when
state.frequency is NaN. Also, if relative permeability, magnetization, or current density for a
magnetostatic analysis depends on the magnetic flux density, ensure that your function returns a
matrix of NaN values of the correct size when state.NormFluxDensity, state.u, state.ux,
state.uy, or state.uz is NaN. Solvers check whether a problem is nonlinear by passing NaN state
values and looking for returned NaN values.
When you solve an electrostatic or DC conduction problem, the output returned by the function
handle must be of the following size. Here, Np = numel(location.x) is the number of points.
When you solve a magnetostatic problem, the output returned by the function handle must be of the
following size. Here, Np = numel(location.x) is the number of points. Note that for a 3-D
magnetostatic analysis, state.u, state.ux, state.uy, and state.uz are 3-by-Np, and
state.NormFluxDensity is 1-by-Np.
• 1-by-Np if a function specifies the nonconstant relative permeability or the initial magnetic flux
• 1-by-Np or Np-by-1 for a 2-D model and 3-by-Np or Np-by-3 for a 3-D model if a function specifies
the nonconstant current density
• 1-by-Np for a 2-D model and 3-by-Np for a 3-D model if a function specifies the nonconstant
magnetic potential on the boundary or the initial magnetic potential
• 2-by-Np for a 2-D model and 3-by-Np for a 3-D model if a function specifies the nonconstant
magnetization
When you solve a harmonic problem, the output returned by the function handle must be of the
following size. Here, Np = numel(location.x) is the number of points.
• 1-by-Np if a function specifies the nonconstant relative permittivity, relative permeability, and
conductivity
• 2-by-Np for a 2-D geometry and 3-by-Np for a 3-D geometry if a function specifies the nonconstant
electric or magnetic field
2-153
2 Setting Up Your PDE
• 2-by-Np or Np-by-2 for a 2-D geometry and 3-by-Np or Np-by-3 for a 3-D geometry if a function
specifies the nonconstant current density and the field type is electric
• 1-by-Np or Np-by-1 for a 2-D geometry and 3-by-Np or Np-by-3 for a 3-D geometry if a function
specifies the nonconstant current density and the field type is magnetic
2-154
Rectangular, Triangular, Trapezoidal, and Harmonic Loads
Define a trapezoidal pulse function, trapezoidalLoad, to model a trapezoidal load. This function
accepts the load magnitude, the location and state structure arrays, and the function specifying
the pulse parameters that define the start, rise, fall, and end times. Because the function depends on
time, it must return a matrix of NaN of the correct size when state.time is NaN. Solvers check
whether a problem is nonlinear or time-dependent by passing NaN state values and looking for
returned NaN values.
function Tn = trapezoidalLoad(load,location,state,T)
if isnan(state.time)
Tn = NaN*(location.nx);
return
end
if isa(load,"function_handle)
load = load(location,state);
else
load = load(:);
end
% Four time-points that define a trapezoidal pulse
2-155
2 Setting Up Your PDE
The setUpTrapezoid helper function accepts the name-value arguments StartTime, RiseTime,
FallTime, and EndTime and processes these parameters for use in the trapezoidalLoad function.
Pass the output of this function as the last argument of trapezoidalLoad. The default StartTime,
RiseTime, and FallTime values are 0, while the default EndTime value is Inf.
function T = setUpTrapezoid(opts)
arguments
opts.StartTime double {mustBeScalarOrEmpty,mustBeReal} = []
opts.RiseTime double {mustBeScalarOrEmpty,mustBeReal} = []
opts.FallTime double {mustBeScalarOrEmpty,mustBeReal} = []
opts.EndTime double {mustBeScalarOrEmpty,mustBeReal} = []
end
if isempty(opts.StartTime)
opts.StartTime = 0;
end
if isempty(opts.RiseTime)
opts.RiseTime = 0;
end
if isempty(opts.FallTime)
opts.FallTime = 0;
end
if isempty(opts.EndTime) && (opts.FallTime ~= 0)
opts.EndTime = opts.StartTime + opts.RiseTime + opts.FallTime;
elseif isempty(opts.EndTime) && (opts.FallTime == 0)
opts.EndTime = Inf;
end
T = [opts.StartTime;
opts.StartTime + opts.RiseTime;
opts.EndTime - opts.FallTime;
opts.EndTime];
end
load = 5e6;
T = setUpTrapezoid(StartTime=1, ...
RiseTime=0.5, ...
FallTime=0.5, ...
EndTime=3);
pressurePulse = @(location,state) ...
trapezoidalLoad(load,location,state,T);
model.FaceLoad(1) = faceLoad(Pressure=pressurePulse);
2-156
Rectangular, Triangular, Trapezoidal, and Harmonic Loads
For rectangular and triangular pulses, use the same helper functions and specify start, rise, fall, and
end times as follows:
Harmonic Load
Model a harmonic load by specifying its magnitude, frequency, and phase.
Define a sinusoidal load function, sinusoidalLoad, to model a harmonic load. This function accepts
the load magnitude (amplitude), the location and state structure arrays, frequency, and phase.
Because the function depends on time, it must return a matrix of NaN of the correct size when
state.time is NaN. Solvers check whether a problem is nonlinear or time-dependent by passing NaN
state values and looking for returned NaN values.
function Tn = sinusoidalLoad(load,location,state,Frequency,Phase)
if isnan(state.time)
Tn = NaN*(location.nx);
return
end
if isa(load,"function_handle")
load = load(location,state);
else
load = load(:);
end
% Transient model excited with harmonic load
Tn = load.*sin(Frequency.*state.time + Phase);
end
As an example, apply a sinusoidal pressure load on face 1 by using the sinusoidalLoad function.
2-157
2 Setting Up Your PDE
Pressure = 5e7;
Frequency = 25;
Phase = 0;
pressurePulse = @(location,state) ...
sinusoidalLoad(Pressure,location,state,Frequency,Phase);
model.FaceLoad(1) = faceLoad(Pressure=pressurePulse);
2-158
View, Edit, and Delete Boundary Conditions
A PDE model stores boundary conditions in its BoundaryConditions property. To obtain the
boundary conditions stored in the PDE model called model, use this syntax:
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-159
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.
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-160
View, Edit, and Delete Boundary Conditions
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: []
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 =
2-161
2 Setting Up Your PDE
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-128
2-162
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.
2-163
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:
figure
pdemesh(mesh_default)
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-164
Generate Mesh
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)
mesh_Hmin =
FEMesh with properties:
figure
pdemesh(mesh_Hmin)
2-165
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 =
FEMesh with properties:
figure
pdemesh(mesh_HminHmax)
2-166
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 =
FEMesh with properties:
figure
pdemesh(mesh_Hgrad)
2-167
2 Setting Up Your PDE
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")
hold on
plot(mesh_quadratic.Nodes(1,:), ...
mesh_quadratic.Nodes(2,:), ...
"ok","MarkerFaceColor","g")
2-168
Generate Mesh
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.
2-169
2 Setting Up Your PDE
2-170
Find Mesh Elements and Nodes by Location
Partial Differential Equation Toolbox™ allows you to find mesh elements and nodes by their geometric
location or proximity to a particular point or node. This example works with a group of elements and
nodes located within the specified bounding disk.
thermalmodel = createpde("thermal","steadystate");
importGeometry(thermalmodel,"PlateHolePlanar.stl");
pdegplot(thermalmodel,"FaceLabels","on", ...
"EdgeLabels","on")
thermalProperties(thermalmodel,"ThermalConductivity",1);
∘ ∘
Apply a constant temperature of 20 C to the left edge and a constant temperature of −10 Cto the
right edge. All other edges are insulated by default.
thermalBC(thermalmodel,"Edge",4,"Temperature",20);
thermalBC(thermalmodel,"Edge",1,"Temperature",-10);
2-171
2 Setting Up Your PDE
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
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-172
Find Mesh Elements and Nodes by Location
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.2872
T_max
T_max = 12.2395
Find the IDs of the nodes corresponding to the minimal and maximal temperatures. Plot these nodes
on the mesh plot.
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")
2-173
2 Setting Up Your PDE
Now highlight the elements within the specified radius on the mesh plot using a green marker.
figure
pdemesh(thermalmodel)
hold on
pdemesh(mesh.Nodes,mesh.Elements(:,Er), ...
"EdgeColor","green")
2-174
Find Mesh Elements and Nodes by Location
figure
pdeplot(mesh.Nodes,mesh.Elements(:,Er), ...
"XYData",thermalresults.Temperature)
2-175
2 Setting Up Your PDE
2-176
Assess Quality of Mesh Elements
Partial Differential Equation Toolbox™ uses the finite element method to solve PDE problems. This
method discretizes a geometric domain into a collection of simple shapes that make up a mesh. The
quality of the mesh is crucial for obtaining an accurate approximation of a solution.
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.
As mesh elements become distorted, numeric approximations of a solution typically become less
accurate. Refining a mesh using smaller elements produces better shaped elements and, therefore,
more accurate results. However, it also can be computationally expensive.
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)
2-177
2 Setting Up Your PDE
mesh = generateMesh(model,Hmax=10);
Q = meshQuality(mesh);
figure
pdemesh(mesh,FaceAlpha=0.5)
hold on
pdemesh(mesh.Nodes,mesh.Elements(:,elemIDs), ...
FaceColor="blue",EdgeColor="blue")
2-178
Assess Quality of Mesh Elements
Determine how much of the total mesh volume belongs to elements with quality values less than 0.5.
Return the result as a percentage.
mv03_percent = volume(mesh,elemIDs)/volume(mesh)*100
mv03_percent = 0.0892
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");
figure
pdemesh(mesh,FaceAlpha=0.5)
hold on
pdemesh(mesh.Nodes,mesh.Elements(:,elemIDs), ...
FaceColor="blue",EdgeColor="blue")
2-179
2 Setting Up Your PDE
2-180
Mesh Data as [p,e,t] Triples
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-184.
• 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-181
2 Setting Up Your PDE
• 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-182
Mesh Data as [p,e,t] Triples
2-183
2 Setting Up Your PDE
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 the quadratic geometric
order by default, and provides the option to switch to the linear geometric order. A mesh always
consists of elements of the same order. The toolbox does not support mixed meshes.
triangular elements 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.
Tetrahedral elements 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-184
Mesh Data
The center nodes in quadratic meshes are always added at half-distance between corners. For
geometries with curved surfaces and edges, center nodes might not appear on the edge or surface
itself.
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-185
3
Solving PDEs
• “von Mises Effective Stress and Displacements: PDE Modeler App” on page 3-3
• “Clamped Square Isotropic Plate with Uniform Pressure Load” on page 3-6
• “Deflection of Piezoelectric Actuator” on page 3-10
• “Dynamics of Damped Cantilever Beam” on page 3-20
• “Dynamic Analysis of Clamped Beam” on page 3-27
• “Reduced-Order Modeling Technique for Beam with Point Load” on page 3-32
• “Modal and Frequency Response Analysis for Single Part of Kinova Gen3 Robotic Arm”
on page 3-39
• “Thermal Stress Analysis of Jet Engine Turbine Blade” on page 3-51
• “Finite Element Analysis of Electrostatically Actuated MEMS Device” on page 3-59
• “Deflection Analysis of Bracket” on page 3-74
• “Deflection Analysis of Bracket” on page 3-85
• “Vibration of Square Plate” on page 3-95
• “Structural Dynamics of Tuning Fork” on page 3-100
• “Modal Superposition Method for Structural Dynamics Problem” on page 3-112
• “Stress Concentration in Plate with Circular Hole” on page 3-115
• “Thermal Deflection of Bimetallic Beam” on page 3-123
• “Axisymmetric Thermal and Structural Analysis of Disc Brake” on page 3-132
• “Heat Transfer in Orthotropic Material Plate due to Laser Beam” on page 3-144
• “Thermal and Structural Analysis of Disc Brake” on page 3-154
• “Electrostatic Potential in Air-Filled Frame” on page 3-166
• “Electrostatic Potential in Air-Filled Frame” on page 3-168
• “Electrostatic Potential in Air-Filled Frame: PDE Modeler App” on page 3-171
• “Electrostatic Analysis of Transformer Bushing Insulator” on page 3-173
• “Magnetic Flux Density in H-Shaped Magnet” on page 3-179
• “Magnetic Flux Density in Electromagnet” on page 3-184
• “Linear Elasticity Equations” on page 3-194
• “Magnetic Field in Two-Pole Electric Motor” on page 3-200
• “Magnetic Field in Two-Pole Electric Motor: PDE Modeler App” on page 3-205
• “Helmholtz Equation on Disk with Square Hole” on page 3-209
• “Electrostatics and Magnetostatics” on page 3-215
• “DC Conduction” on page 3-217
• “Harmonic Electromagnetics” on page 3-218
• “Current Density Between Two Metallic Conductors” on page 3-220
• “Skin Effect in Copper Wire with Circular Cross Section: PDE Modeler App” on page 3-223
3 Solving PDEs
• “Current Density Between Two Metallic Conductors: PDE Modeler App” on page 3-231
• “Heat Transfer Between Two Squares Made of Different Materials: PDE Modeler App”
on page 3-234
• “Temperature Distribution in Heat Sink” on page 3-238
• “Nonlinear Heat Transfer in Thin Plate” on page 3-249
• “Poisson's Equation on Unit Disk: PDE Modeler App” on page 3-257
• “Poisson's Equation on Unit Disk” on page 3-263
• “Scattering Problem” on page 3-271
• “Scattering Problem: PDE Modeler App” on page 3-276
• “Magnetic Flux Density in H-Shaped Magnet with Nonlinear Relative Permeability” on page 3-280
• “Minimal Surface Problem” on page 3-286
• “Minimal Surface Problem: PDE Modeler App” on page 3-292
• “Poisson's Equation with Point Source and Adaptive Mesh Refinement” on page 3-294
• “Heat Transfer in Block with Cavity: PDE Modeler App” on page 3-299
• “Heat Transfer in Block with Cavity” on page 3-302
• “Heat Transfer in Block with Cavity” on page 3-306
• “Heat Transfer Problem with Temperature-Dependent Properties” on page 3-310
• “Heat Conduction in Multidomain Geometry with Nonuniform Heat Flux” on page 3-318
• “Inhomogeneous Heat Equation on Square Domain” on page 3-325
• “Heat Distribution in Circular Cylindrical Rod” on page 3-329
• “Thermal Analysis of Disc Brake” on page 3-335
• “Heat Distribution in Circular Cylindrical Rod: PDE Modeler App” on page 3-343
• “Wave Equation on Square Domain” on page 3-346
• “Wave Equation on Square Domain: PDE Modeler App” on page 3-350
• “Eigenvalues and Eigenmodes of L-Shaped Membrane” on page 3-353
• “Eigenvalues and Eigenmodes of L-Shaped Membrane: PDE Modeler App” on page 3-358
• “L-Shaped Membrane with Rounded Corner: PDE Modeler App” on page 3-361
• “Eigenvalues and Eigenmodes of Square” on page 3-364
• “Eigenvalues and Eigenmodes of Square: PDE Modeler App” on page 3-369
• “Vibration of Circular Membrane” on page 3-372
• “Solution and Gradient Plots with pdeplot and pdeplot3D” on page 3-376
• “2-D Solution and Gradient Plots with MATLAB Functions” on page 3-385
• “3-D Solution and Gradient Plots with MATLAB Functions” on page 3-391
• “Solve Poisson Equation on Unit Disk Using Physics-Informed Neural Networks” on page 3-403
• “Reduced-Order Model for Thermal Behavior of Battery” on page 3-411
• “Battery Module Cooling Analysis and Reduced-Order Thermal Model” on page 3-418
• “Dimensions of Solutions, Gradients, and Fluxes” on page 3-429
3-2
von Mises Effective Stress and Displacements: PDE Modeler App
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.
• For convenience, first specify the Neumann boundary condition g1 = g2 = 0, q11 = q12 =
q21 = q22 = 0 (no normal stress) for all boundaries. Use Edit > Select All to select all
boundaries.
• For the two clamped boundaries at the inset in the lower left (edges 4 and 5), specify the
Dirichlet boundary condition with zero displacements: h11 = 1, h12 = 0, h21 = 0, h22 =
1, r1 = 0, r2 = 0. Use Shift+click to select several boundaries.
• For the rounded cut (edge 7), specify the Neumann boundary condition: g1 = 0.5*nx, g2 =
0.5*ny, q11 = q12 = q21 = q22 = 0.
8
Specify the coefficients by selecting PDE > PDE Specification or clicking the button on
the toolbar. Specify E = 196E3 and nu = 0.31. The material is homogeneous, so the same
values E and nu apply to the entire 2-D domain. Because there are no volume forces, specify Kx
= Ky = 0. The elliptic type of PDE for plane stress does not use density, so you can specify any
value. For example, specify pho = 0.
3-4
von Mises Effective Stress and Displacements: PDE Modeler App
9 Initialize the mesh by selecting Mesh > Initialize Mesh. Refine the mesh by selecting Mesh >
Refine Mesh.
10 Refining the mesh in areas where the gradient of the solution (the stress) is large. To do this,
select Solve > Parameters. In the resulting dialog box, select Adaptive mode. Use the default
adaptation options: the Worst triangles triangle selection method with the Worst triangle
fraction set to 0.5.
11
Solve the PDE by selecting Solve > Solve PDE or clicking the button on the toolbar.
12 Plot the von Mises effective stress using color. Plot the displacement vector field (u,v) using a
deformed mesh. To do this:
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-5
3 Solving PDEs
This example shows how to calculate the deflection of a structural plate under a pressure loading.
The partial differential equation for a thin isotropic plate with a pressure loading is
∇2 (D ∇2 w) = − p,
3
Eh
D= ,
12(1 − ν2)
and E is the modulus of elasticity, ν is Poisson's ratio, h is the plate thickness, w is the transverse
deflection of the plate, and p is the pressure load.
The boundary conditions for the clamped boundaries are w = 0 and w′ = 0, where w′ is the derivative
of w in a direction normal to the boundary.
Partial Differential Equation Toolbox™ cannot directly solve this fourth-order plate equation. Convert
the fourth-order equation to these two second-order partial differential equations, where v is the new
dependent variable.
∇2 w = v
D ∇2 v = − p
You cannot directly specify boundary conditions for both w and w′ in this second-order system.
Instead, specify that w′ is 0, and define v′ so that w also equals 0 on the boundary. To specify these
conditions, use stiff "springs" distributed along the boundary. The springs apply a transverse shear
force to the plate edge. Define the shear force along the boundary due to these springs as
n ⋅ D ∇v = − kw, where n is the normal to the boundary, and k is the stiffness of the springs. This
expression is a generalized Neumann boundary condition supported by the toolbox. The value of k
must be large enough so that w is approximately 0 at all points on the boundary. It also must be small
enough to avoid numerical errors due to an ill-conditioned stiffness matrix.
The toolbox uses the dependent variables u1 and u2 instead of w and v. Rewrite the two second-order
partial differential equations using variables u1 and u2:
− ∇2 u1 + u2 = 0
−D ∇2 u2 = p
model = createpde(2);
len = 10;
gdm = [3 4 0 len len 0 0 0 len len]';
3-6
Clamped Square Isotropic Plate with Uniform Pressure Load
g = decsg(gdm,'S1',('S1')');
geometryFromEdges(model,g);
figure
pdegplot(model,"EdgeLabels","on")
ylim([-1,11])
axis equal
title("Geometry With Edge Labels Displayed")
PDE coefficients must be specified using the format required by the toolbox. For details, see
The c coefficient in this example is a tensor, which can be represented as a 2-by-2 matrix of 2-by-2
blocks:
c(1) c(2) ⋅ ⋅
⋅ c(3) ⋅ ⋅
⋅ ⋅ c(4) c(5)
⋅ ⋅ ⋅ c(6)
3-7
3 Solving PDEs
This matrix is further flattened into a column vector of six elements. The entries in the full 2-by-2
matrix (defining the coefficient a) and the 2-by-1 vector (defining the coefficient f) follow directly from
the definition of the two-equation system.
D = E*thick^3/(12*(1 - nu^2));
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);
k = 1e7;
bOuter = applyBoundaryCondition(model,"neumann","Edge",(1:4),...
"g",[0 0],"q",[0 0; k 0]);
Generate a mesh.
generateMesh(model);
res = solvepde(model);
u = res.NodalSolution;
numNodes = size(model.Mesh.Nodes,2);
figure
pdeplot(model,"XYData",u(:,1),"Contour","on")
title("Transverse Deflection")
3-8
Clamped Square Isotropic Plate with Uniform Pressure Load
numNodes = size(model.Mesh.Nodes,2);
wMax = min(u(1:numNodes,1))
wMax = -0.2762
Compare the result with the deflection at the plate center computed analytically.
wMax = -.0138*pres*len^4/(E*thick^3)
wMax = -0.2760
3-9
3 Solving PDEs
In this example, the model is a two-layer cantilever beam, with both layers made of the same
polyvinylidene fluoride (PVDF) material. The polarization direction points down (negative y-direction)
in the top layer and points up in the bottom layer. The typical length to thickness ratio is 100. When
you apply a voltage between the lower and upper surfaces of the beam, the beam deflects in the y-
direction because one layer shortens and the other layer lengthens.
−∇ ⋅ σ = f
Here, σ is the stress tensor, and f is the body force vector. Gauss's Law describes the electrostatic
behavior of the solid:
∇⋅D=ρ
D is the electric displacement, and ρ is the distributed free charge. Combine these two PDE systems
into this single system:
σ f
−∇ ⋅ =
D −ρ
3-10
Deflection of Piezoelectric Actuator
For a 2-D analysis, σ has the components σ11, σ22, and σ12 = σ21, and D has the components D1 and
D2.
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 2-D analysis of an orthotropic piezoelectric
material under plane stress conditions, you can write these equations as
Ci j are the elastic coefficients, ℰ i are the electrical permittivities, and ei j are the piezoelectric stress
coefficients. The piezoelectric stress coefficients in these equations conform to conventional notation
in piezoelectric materials where the z-direction (the third direction) aligns with the "poled" direction
of the material. For the 2-D analysis, align the "poled" direction with the y-axis. Write the strain
vector in terms of the x-displacement u and y-displacement v:
∂u
ϵ11 ∂x
∂v
ϵ22 =
∂y
γ12
∂u ∂v
+
∂y ∂x
∂ϕ
E1 ∂x
= −
E2 ∂ϕ
∂y
You can substitute the strain-displacement equations and electric field equations into the constitutive
equations and get a system of equations for the stresses and electrical displacements in terms of
displacement and electrical potential derivatives. Substituting the resulting equations into the PDE
system equations yields a system of equations that involve the divergence of the displacement and
electrical potential derivatives. As the next step, arrange these equations to match the form required
by the toolbox.
− ∇ ⋅ c ⊗ ∇u + au = f
or in a tensor form:
∂ ∂u j
− c + ai ju j = f i
∂xk i jkl ∂xl
where repeated indices imply summation. For the 2-D piezoelectric system in this example, the
system vector u is
3-11
3 Solving PDEs
u
u= v
ϕ
∂u
∂x
∂u
∂y
∂v
∂x
∇u =
∂v
∂y
∂ϕ
∂x
∂ϕ
∂y
For details on specifying the coefficients in the format required by the toolbox, see:
The c coefficient in this example is a tensor. You can represent it as a 3-by-3 matrix of 2-by-2 blocks:
To map terms of constitutive equations to the form required by the toolbox, write the c tensor and the
solution gradient in this form:
∂u
∂x
c1111 c1112 c1211 c1212 c1311 c1312 ∂u
∂y
c1121 c1122 c1221 c1222 c1321 c1322
∂v
c2111 c2112 c2211 c2212 c2311 c2312 ∂x
c2121 c2122 c2221 c2222 c2321 c2322 ∂v
∂y
c3111 c3112 c3211 c3212 c3311 c3312
∂ϕ
c3121 c3122 c3221 c3222 c3321 c3322
∂x
∂ϕ
∂y
3-12
Deflection of Piezoelectric Actuator
From this equation, you can map the traditional constitutive coefficients to the form required for the
c matrix. The minus sign in the equations for the electric field is incorporated into the c matrix to
match the toolbox's convention.
∂u
∂x
C11 ⋅ ⋅ C12 e11 e31 ∂u
∂y
⋅ G12 G12 ⋅ e14 e34
∂v
⋅ G12 G12 ⋅ e14 e34 ∂x
C21 ⋅ ⋅ C22 e13 e33 ∂v
∂y
e11 e14 e14 e13 −ℰ 1 ⋅
∂ϕ
e31 e34 e34 e33 ⋅ −ℰ 2 ∂x
∂ϕ
∂y
Beam Geometry
Create a PDE model. The equations have three components: two components due to linear elasticity
and one component due to electrostatics. Therefore, the model must have three equations.
model = createpde(3);
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-13
3 Solving PDEs
Material Properties
Specify the material properties of the beam layers. The material in both layers is polyvinylidene
fluoride (PVDF), a thermoplastic polymer with piezoelectric behavior.
relPermittivity = 12;
pzeE = c2d*pzeD;
D_const_stress = [relPermittivity 0;
0 relPermittivity]*permittivityFreeSpace;
3-14
Deflection of Piezoelectric Actuator
9
The parameters of the elastic equations are of the order of 10 while the electric parameters are of
−11
the order of 10 . To avoid constructing an ill-conditioned matrix, rescale the last equation so that
the coefficients are larger. Note that before any post-processing involving the c coefficient (for
example, when you evaluate a flux of PDE solution), you must revert the scaling changes to the c
matrix.
cond_scaling = 1e5;
c33 = cond_scaling*[D_const_strain(1,1)
D_const_strain(2,1)
D_const_strain(1,2)
D_const_strain(2,2)];
ctop = [c11(:); c21(:); -c31(:);
c12(:); c22(:); -c32(:);
-c13(:); -c23(:); -c33(:)];
cbot = [c11(:); c21(:); c31(:);
c12(:); c22(:); c32(:);
c13(:); c23(:); -c33(:)];
If you problem includes a current source for the third equation, scale the f coefficient: f = [0 0
cond_scaling*value_f]'. Otherwise, specify it as follows.
f = [0 0 0]';
Specify coefficients.
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);
Boundary Conditions
Set the voltage (solution component 3) on the top of the beam (edge 1) to 100 volts.
voltTop = applyBoundaryCondition(model,"mixed", ...
"Edge",1,...
"u",100,...
"EquationIndex",3);
Specify that the bottom of the beam (edge 2) is grounded by setting the voltage to 0.
voltBot = applyBoundaryCondition(model,"mixed", ...
"Edge",2,...
3-15
3 Solving PDEs
"u",0,...
"EquationIndex",3);
Specify that the left side (edges 6 and 7) is clamped by setting the x- and y-displacements (solution
components 1 and 2) to 0.
The stress and charge on the right side of the beam are zero. Accordingly, use the default boundary
condition for edges 3 and 4.
msh = generateMesh(model,"Hmax",5e-4);
result = solvepde(model)
result =
StationaryResults with properties:
Access the solution at the nodal locations. The first column contains the x-deflection. The second
column contains the y-deflection. The third column contains the electrical potential.
rs = result.NodalSolution;
feTipDeflection = min(rs(:,2));
fprintf("Finite element tip deflection is: %12.4e\n",feTipDeflection);
tipDeflection = -3*d31*100*L^2/(8*H2^2);
fprintf("Analytical tip deflection is: %12.4e\n",tipDeflection);
3-16
Deflection of Piezoelectric Actuator
3-17
3 Solving PDEs
3-18
Deflection of Piezoelectric Actuator
References
1 Hwang, Woo-Seok, and Hyun Chul Park. "Finite Element Modeling of Piezoelectric Sensors and
Actuators." AIAA Journal 31, no.5 (May 1993): 930-937.
2 Pieford, V. "Finite Element Modeling of Piezoelectric Active Structures." PhD diss., Universite
Libre De Bruxelles, 2001.
3-19
3 Solving PDEs
This example shows how to include damping in the transient analysis of a simple cantilever beam.
The damping model is basic viscous damping distributed uniformly through the volume of the beam.
The beam is deformed by applying an external load at the tip of the beam and then released at time
t = 0. This example does not use any additional loading, so the displacement of the beam decreases
as a function of time due to the damping. The example uses plane-stress modal, static, and transient
analysis models in its three-step workflow:
1 Perform modal analysis to compute the fundamental frequency of the beam and to speed up
computations for the transient analysis.
2 Find the static solution of the beam with a vertical load at the tip to use as an initial condition for
a transient model.
3 Perform the transient analysis with and without damping.
The 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.
Modal Analysis
modelM = createpde("structural","modal-planestress");
Create the geometry and include it in the model. Suppose, the beam is 5 inches long and 0.1 inches
thick.
width = 5;
height = 0.1;
gdm = [3;4;0;width;width;0;0;0;height;height];
g = decsg(gdm,'S1',('S1')');
geometryFromEdges(modelM,g);
figure;
pdegplot(modelM,"EdgeLabels","on");
axis equal
title("Geometry With Edge Labels Displayed")
3-20
Dynamics of Damped Cantilever Beam
Define a maximum element size so that there are five elements through the beam thickness. Generate
a mesh.
hmax = height/5;
msh = generateMesh(modelM,"Hmax",hmax);
Specify Young's modulus, Poisson's ratio, and the mass density of steel.
E = 3.0e7;
nu = 0.3;
rho = 0.3/386;
structuralProperties(modelM,"YoungsModulus",E, ...
"PoissonsRatio",nu, ...
"MassDensity",rho);
structuralBC(modelM,"Edge",4,"Constraint","fixed");
Solve the problem for the frequency range from 0 to 1e5. The recommended approach is to use a
value that is slightly smaller than the expected lowest frequency. Thus, use -0.1 instead of 0.
res = solve(modelM,"FrequencyRange",[-0.1,1e5]')
res =
ModalStructuralResults with properties:
3-21
3 Solving PDEs
modeID = 1:numel(res.NaturalFrequencies);
Express the resulting frequencies in Hz by dividing them by 2π. Display the frequencies in a table.
tmodalResults = table(modeID.',res.NaturalFrequencies/(2*pi));
tmodalResults.Properties.VariableNames = {'Mode','Frequency'};
disp(tmodalResults)
Mode Frequency
____ _________
1 126.94
2 794.05
3 2216.8
4 4325.3
5 7110.7
6 9825.9
7 10551
8 14623
Compute the analytical fundamental frequency (Hz) using the beam theory.
I = height^3/12;
freqAnalytical = 3.516*sqrt(E*I/(width^4*rho*height))/(2*pi)
freqAnalytical = 126.9498
freqNumerical = res.NaturalFrequencies(1)/(2*pi)
freqNumerical = 126.9416
longestPeriod = 1/freqNumerical
longestPeriod = 0.0079
Plot the y-component of the solution for the lowest beam frequency.
figure;
pdeplot(modelM,"XYData",res.ModeShapes.uy(:,1))
title("Lowest Frequency Vibration Mode")
axis equal
3-22
Dynamics of Damped Cantilever Beam
The beam is deformed by applying an external load at its tip and then released at time t = 0. Find the
initial condition for the transient analysis by using the static solution of the beam with a vertical load
at the tip.
modelS = createpde("structural","static-planestress");
Use the same geometry and mesh that you used for the modal analysis.
geometryFromEdges(modelS,g);
modelS.Mesh = msh;
Specify the same values for Young's modulus, Poisson's ratio, and the mass density of the material.
structuralProperties(modelS,"YoungsModulus",E, ...
"PoissonsRatio",nu, ...
"MassDensity",rho);
structuralBC(modelS,"Edge",4,"Constraint","fixed");
Apply the static vertical load on the right side of the beam.
3-23
3 Solving PDEs
structuralBoundaryLoad(modelS,"Edge",2,"SurfaceTraction",[0;1]);
Solve the static model. The resulting static solution serves as an initial condition for transient
analysis.
Rstatic = solve(modelS);
Transient Analysis
Perform the transient analysis of the cantilever beam with and without damping. Use the modal
superposition method to speed up computations.
modelT = createpde("structural","transient-planestress");
Use the same geometry and mesh that you used for the modal analysis.
geometryFromEdges(modelT,g);
modelT.Mesh = msh;
Specify the same values for Young's modulus, Poisson's ratio, and the mass density of the material.
structuralProperties(modelT,"YoungsModulus",E, ...
"PoissonsRatio",nu, ...
"MassDensity",rho);
structuralBC(modelT,"Edge",4,"Constraint","fixed");
structuralIC(modelT,Rstatic)
ans =
NodalStructuralICs with properties:
Solve the undamped transient model for three full periods corresponding to the lowest vibration
mode.
tlist = 0:longestPeriod/100:3*longestPeriod;
resT = solve(modelT,tlist,"ModalResults",res);
intrpUt = interpolateDisplacement(resT,[5;0.05]);
The displacement at the tip is a sinusoidal function of time with amplitude equal to the initial y-
displacement. This result agrees with the solution to the simple spring-mass system.
plot(resT.SolutionTimes,intrpUt.uy)
grid on
title("Undamped Solution")
3-24
Dynamics of Damped Cantilever Beam
xlabel("Time")
ylabel("Tip of beam displacement")
zeta = 0.03;
omega = 2*pi*freqNumerical;
structuralDamping(modelT,"Zeta",zeta);
resT = solve(modelT,tlist,"ModalResults",res);
intrpUt = interpolateDisplacement(resT,[5;0.05]);
The y-displacement at the tip is a sinusoidal function of time with amplitude exponentially decreasing
with time.
figure
hold on
plot(resT.SolutionTimes,intrpUt.uy)
plot(tlist,intrpUt.uy(1)*exp(-zeta*omega*tlist),"Color","r")
grid on
title("Damped Solution")
xlabel("Time")
ylabel("Tip of beam displacement")
3-25
3 Solving PDEs
3-26
Dynamic Analysis of Clamped Beam
This example shows how to analyze the dynamic behavior of a beam under a uniform pressure load
and clamped at both ends.
This example uses the Imperial system of units. If you replace them with values specified in the
metric system, ensure that you specify all values using the same system.
In this example, the pressure load is suddenly applied at time equal to zero. The pressure magnitude
is high enough to produce deflections on the same order as the beam thickness. Accurate prediction
of this type of behavior requires geometrically nonlinear elasticity equations. This example solves the
clamped beam elasticity problem using both linear and nonlinear formulations of elasticity equations.
One approach to handling the large deflections is to consider the elasticity equations in the deformed
position. However, the toolbox uses the equations based on the original geometry. Therefore, you
must use a Lagrangian formulation of nonlinear elasticity where stresses, strains, and coordinates
refer to the original geometry. The Lagrangian formulation of the equilibrium equations is
ρü − ∇ ⋅ (F ⋅ S) = f
where ρ is the material density, u is the displacement vector, F is the deformation gradient, S is the
second Piola-Kirchoff stress tensor, and f is the body force vector. You also can write this equation in
the tensor form:
∂ ∂ui
ρüi − + δik Sk j = f i
∂x j ∂xk
Although this formulation accounts for large deflections, it assumes that the strains remain small, so
that linear elastic constitutive relations apply. For the 2-D plane stress case, you can write the
constitutive relations in matrix form:
E
C11 = C22 =
1 − ν2
Eν
C12 =
1 − ν2
E
G12 =
2(1 + ν)
3-27
3 Solving PDEs
where E is the Young's modulus, and ν is the Poisson's ratio. For more details about the Lagrangian
formulation for nonlinear elasticity, see [1] on page 3-31.
These equations completely define the geometrically nonlinear plane stress problem. This example
uses Symbolic Math Toolbox™ to define the c coefficient in the form required by Partial Differential
Equation Toolbox™. The c coefficient is a function cCoefficientLagrangePlaneStress. You can
use it with any geometric nonlinear plane stress analysis of a model made from an isotropic material.
You can find it under matlab/R20XXx/examples/pde/main.
Linear Solution
model = createpde(2);
Because the beam geometry and loading are symmetric about the beam center, you can simplify the
model by considering only the right half of the beam.
l2 = blength/2;
h2 = height/2;
Create the geometry from the edges and include it in the model.
pg = geometryFromEdges(model,g);
3-28
Dynamic Analysis of Clamped Beam
figure
pdegplot(g,"EdgeLabels","on")
axis([-.1 1.1*l2 -5*h2 5*h2])
Derive the equation coefficients using the material properties. For the linear case, the c coefficient
matrix is constant.
Apply the boundary conditions. From the symmetry condition, the x-displacement equals zero at the
left edge.
Because the beam is clamped, the x- and y-displacements equal zero along the right edge.
3-29
3 Solving PDEs
Generate a mesh.
generateMesh(model);
Interpolate the solution at the geometry center for the y-component (component 2) at all solution
times.
xc = 1.25;
yc = 0;
u4Linear = interpolateSolution(result,xc,yc,2,1:length(tlist));
Nonlinear Solution
Specify the coefficients for the nonlinear case. The cCoefficientLagrangePlaneStress function
takes the isotropic material properties and location and state structures, and returns a c-matrix for a
nonlinear plane stress analysis. It assumes that strains are small, that is, E and ν are independent of
the solution.
c = @(location,state)cCoefficientLagrangePlaneStress(E,gnu, ...
location,state);
specifyCoefficients(model,"m",rho,"d",0,"c", c,"a",0,"f",f);
Interpolate the solution at the geometry center for the y-component (component 2) at all solution
times.
u4NonLinear = interpolateSolution(result,xc,yc,2,1:length(tlist));
Solution Plots
Plot the y-deflection at the center of the beam as a function of time. The nonlinear analysis yields
substantially smaller displacements than the linear analysis. This "stress stiffening" effect also results
in the higher oscillation frequency from the nonlinear analysis.
figure
plot(tlist,u4Linear(:),tlist,u4NonLinear(:))
legend("Linear","Nonlinear")
title("Deflection at Beam Center")
3-30
Dynamic Analysis of Clamped Beam
xlabel("Time, seconds")
ylabel("Deflection, inches")
grid on
References
3-31
3 Solving PDEs
This example shows how to eliminate degrees of freedom (DoFs) that are not on the boundaries of
interest by using the Craig-Bampton reduced-order modeling technique. The example also uses the
smaller dimension superelement to analyze the dynamics of the system. For comparison, the example
also performs a direct transient analysis on the original structure.
modelT = createpde("structural","transient-solid");
gm = multicuboid(0.05,0.003,0.003);
modelT.Geometry = gm;
figure
pdegplot(modelT,"FaceLabels","on","FaceAlpha",0.5)
view([71 4])
figure
pdegplot(modelT,"EdgeLabels","on","FaceAlpha",0.5)
view([71 4])
3-32
Reduced-Order Modeling Technique for Beam with Point Load
Specify Young's modulus, Poisson's ratio, and the mass density of the material.
structuralProperties(modelT,"YoungsModulus",210E9, ...
"PoissonsRatio",0.3, ...
"MassDensity",7800);
structuralBC(modelT,"Edge",[2 8 11 12],"Constraint","fixed");
figure
pdegplot(modelT,"VertexLabels","on","FaceAlpha",0.5)
view([78 2.5])
3-33
3 Solving PDEs
Generate a mesh.
generateMesh(modelT);
structuralBoundaryLoad(modelT,"Vertex",loadedVertex, ...
"Force",[0;0;10],"Frequency",6000);
tlist = 0:0.00005:3E-3;
RT = solve(modelT,tlist);
Define superelement interfaces using the fixed and loaded boundaries. In this case, the reduced order
model retains the degrees of freedom (DoFs) on the fixed face and the loaded vertex while
condensing all other DoFs in favor of modal DoFs. For better performance, use the set of edges
bounding face 5 instead of using the entire face.
structuralSEInterface(modelT,"Edge",[2 8 11 12]);
structuralSEInterface(modelT,"Vertex",loadedVertex);
3-34
Reduced-Order Modeling Technique for Beam with Point Load
rom = reduce(modelT,"FrequencyRange",[-0.1,5e5]);
Next, use the reduced order model to simulate the transient dynamics. Use the ode15s function
directly to integrate the reduced system ODE. Working with the reduced model requires indexing into
the reduced system matrices rom.K and rom.M. First, construct mappings of indices of K and M to
loaded and fixed DoFs by using the data available in rom.
DoFs correspond to translational displacements. If the number of mesh points in a model is Nn, then
the toolbox assigns the IDs to the DoFs as follows: the first 1 to Nn are x-displacements, Nn+1 to 2*Nn
are y-displacements, and 2Nn+1 to 3*Nn are z-displacements. The reduced model object rom contains
these IDs for the retained DoFs in rom.RetainedDoF.
Create a function that returns DoF IDs given node IDs and the number of nodes.
Knowing the DoF IDs for the given node IDs, use the intersect function to find the required
indices.
numNodes = size(rom.Mesh.Nodes,2);
loadedNode = findNodes(rom.Mesh,"region","Vertex",loadedVertex);
loadDoFs = getDoF(loadedNode,numNodes);
[~,loadNodeROMIds,~] = intersect(rom.RetainedDoF,loadDoFs);
In the reduced matrices rom.K and rom.M, generalized modal DoFs appear after the retained DoFs.
Because fixed-end DoFs are not a part of the ODE system, the indices for the ODE DoFs in reduced
matrices are as follows.
odeDoFs = [loadNodeROMIds;fixedIntModeIds];
The relevant components of rom.K and rom.M for time integration are:
Kconstrained = rom.K(odeDoFs,odeDoFs);
Mconstrained = rom.M(odeDoFs,odeDoFs);
numODE = numel(odeDoFs);
Now you have a second-order system of ODEs. To use ode15s, convert this into a system of first-
order ODEs by applying linearization. Such a first-order system is twice the size of the second-order
system.
The specified concentrated force load in the full system is along the z-direction, which is the third
DoF in the ODE system. Accounting for the linearization to obtain the first-order system gives the
loaded ODE DoF.
loadODEDoF = numODE + 3;
Specify the mass matrix and the Jacobian for the ODE solver.
3-35
3 Solving PDEs
odeoptions = odeset;
odeoptions = odeset(odeoptions,"Jacobian",-Kode);
odeoptions = odeset(odeoptions,"Mass",Mode);
u0 = zeros(2*numODE,1);
Solve the reduced system by using ode15s and the helper function CMSODEf, which is defined at the
end of this example.
Compute the values of the ODE variable and the time derivatives.
[displ,vel] = deval(sol,tlist);
Plot the z-displacement at the loaded vertex and compare it to the third DoF in the solution of the
reduced ODE system.
figure
plot(tlist,RT.Displacement.uz(loadedVertex,:))
hold on
plot(tlist,displ(3,:),"r*")
title("Z-Displacement at Loaded Vertex")
legend("full model","rom")
3-36
Reduced-Order Modeling Technique for Beam with Point Load
Knowing the solution in terms of the interface DoFs and modal DoFs, you can reconstruct the solution
for the full model. The reconstructSolution function requires the displacement, velocity, and
acceleration at all DoFs in rom. Construct the complete solution vector, including the zero values at
the fixed DoFs.
u = zeros(size(rom.K,1),numel(tlist));
ut = zeros(size(rom.K,1),numel(tlist));
utt = zeros(size(rom.K,1),numel(tlist));
u(odeDoFs,:) = displ(1:numODE,:);
ut(odeDoFs,:) = vel(1:numODE,:);
utt(odeDoFs,:) = vel(numODE+1:2*numODE,:);
For comparison, compute the displacement in the interior at the center of the beam using the full and
reconstructed solutions.
coordCenter = [0;0;0];
iDispRT = interpolateDisplacement(RT, coordCenter);
iDispRTrom = interpolateDisplacement(RTrom, coordCenter);
figure
plot(tlist,iDispRT.uz,"k")
hold on
plot(tlist,iDispRTrom.uz,"g*")
title("Z-Displacement at Geometric Center")
legend("full model","rom")
3-37
3 Solving PDEs
function f = CMSODEf(t,u,Kode,Fode,loadedVertex)
Fode(loadedVertex) = 10*sin(6000*t);
f = -Kode*u +Fode;
end
3-38
Modal and Frequency Response Analysis for Single Part of Kinova Gen3 Robotic Arm
This example shows how to analyze the shoulder link of a Kinova® Gen3 Ultra lightweight robotic
arm for possible deformation under pressure.
Robotic arms perform precise manipulations in a wide variety of applications from factory automation
to medical surgery. Typically, robotic arms consist of several links connected in a serial chain, with a
base attached to a tabletop or the ground and an end-effector attached at the tip. These links must be
structurally strong to avoid any vibrations when the rotors are moving with a load on them.
Loads at the tips of a robotic arm cause pressure on the joints of each link. The direction of pressure
depends on the direction of the load.
This example computes deformations of the shoulder link under applied pressure by performing a
modal analysis and frequency response analysis simulation. You can find the helper function
animateSixLinkModes.m and the geometry file Gen3Shoulder.stl under matlab/R20XXx/
examples/pde/main.
Modal Analysis
Assuming that one end of the robotic arm is fixed, find the natural frequencies and mode shapes.
To perform unconstrained modal analysis of a structure, you must specify the geometry, mesh, and
material properties. First, import the geometry of the shoulder part of the robotic arm.
importGeometry(model,"Gen3Shoulder.stl");
Generate a mesh.
generateMesh(model);
pdemesh(model)
3-39
3 Solving PDEs
Specify Young's modulus, Poisson's ratio, and the mass density of the material in consistent units.
Typically, the material used for the link is carbon fiber reinforced plastic. Assume that the material is
homogeneous.
E = 1.5e11;
nu = 0.3;
rho = 2000;
structuralProperties(model,"YoungsModulus",E, ...
"PoissonsRatio",nu, ...
"MassDensity",rho);
Identify faces for applying boundary constraints and loads by plotting the geometry with the face
labels.
pdegplot(model,"FaceLabels","on")
view([-1 2])
title("Shoulder Link Geometry with Face Labels")
3-40
Modal and Frequency Response Analysis for Single Part of Kinova Gen3 Robotic Arm
The shoulder link is fixed on one end (face 3) and connected to a moving link on the other end (face
4). Apply the fixed boundary condition on face 3.
structuralBC(model,"Face",3,"Constraint","fixed");
Solve the model for a chosen frequency range. Specify the lower frequency limit below zero so that
all modes with frequencies near zero, if any, appear in the solution.
RF = solve(model,"FrequencyRange",[-1,10000]*2*pi);
modeID = 1:numel(RF.NaturalFrequencies);
Express the resulting frequencies in Hz by dividing them by 2π. Display the frequencies in a table.
tmodalResults = table(modeID.',RF.NaturalFrequencies/2/pi);
tmodalResults.Properties.VariableNames = {'Mode','Frequency'};
disp(tmodalResults);
Mode Frequency
____ _________
1 1932.7
2 2636.8
3 4938.9
4 5100
5 7755.5
3-41
3 Solving PDEs
6 8009
7 9154.8
The best way to visualize the mode shapes is to animate the harmonic motion at their respective
frequencies. The animateSixLinkModes function animates the first six modes. The resulting plot
shows the areas of dominant deformation under load.
frames = animateSixLinkModes(RF);
movie(figure("units","normalized","outerposition",[0 0 1 1]),frames,5,30)
Simulate the dynamics of the shoulder under pressure loading on a face, assuming that the attached
link applies an equal and opposite amount of pressure on the halves of the face. Analyze the
frequency response and deformation of a point in the face.
3-42
Modal and Frequency Response Analysis for Single Part of Kinova Gen3 Robotic Arm
fmodel = createpde("structural","frequency-solid");
Import the same geometry for the shoulder part that you used for the modal analysis.
importGeometry(fmodel,"Gen3Shoulder.stl");
Generate a mesh.
mesh = generateMesh(fmodel);
structuralProperties(fmodel,"YoungsModulus",E, ...
"PoissonsRatio",nu, ...
"MassDensity",rho);
The shoulder link is fixed on one end (face 3) and connected to a moving link on the other end (face
4). Apply the fixed boundary condition on face 3.
structuralBC(fmodel,"Face",3,"Constraint","fixed");
Estimate the pressure that the moving link applies on face 4 when the arm carries a load. This figure
shows two halves of face 4 divided at the center along the y-coordinate.
3-43
3 Solving PDEs
Use the pressFcnFR function to apply the boundary load on face 4. This function applies a push and
a twist pressure signal. The push pressure component is uniform. The twist pressure component
applies positive pressure on the left side and negative pressure on the right side of the face. For the
definition of the pressFcnFR function, see Pressure Function on page 3-49. This function does not
have an explicit dependency on frequency. Therefore, in the frequency domain, this pressure load
acts across all frequencies of the solution.
structuralBoundaryLoad(fmodel, ...
"Face",4, ...
"Pressure", ...
@(region,state)pressFcnFR(region,state), ...
"Vectorized","on");
Define the frequency list for the solution as 0 to 3500 Hz with 200 steps.
flist = linspace(0,3500,200)*2*pi;
Solve the model using the modal frequency response solver by specifying the modal results object RF
as one of the inputs.
R = solve(fmodel,flist,"ModalResults",RF);
3-44
Modal and Frequency Response Analysis for Single Part of Kinova Gen3 Robotic Arm
Plot the frequency response at a point on the loaded face. A point on face 4 located at maximum
negative pressure loading is (0.003; 0.0436; 0.1307). Interpolate the displacement to this point
and plot the result.
figure
plot(R.SolutionFrequencies/2/pi,abs(queryPointDisp.uy))
title("Transverse Displacement at a Point on a Loaded Face")
xlabel("Frequency (Hz)")
ylabel("Y-Displacement")
xlim([0.0000 3500])
The peak of the response occurs near 2700 Hz, which is close to the second mode of vibration. A
smaller response also occurs at the first mode close to 1950 Hz.
Find the peak response frequency index by using the max function with two output arguments. The
second output argument provides the index of the peak frequency.
[M,I] = max(abs(queryPointDisp.uy))
M = 5.0847e-04
I = 151
3-45
3 Solving PDEs
R.SolutionFrequencies(152)/2/pi
ans = 2.6558e+03
Plot the deformation at the peak response frequency. The applied load is such that it predominantly
excites the opening mode and the bending mode of the shoulder.
RD = struct();
RD.ux = R.Displacement.ux(:,I);
RD.uy = R.Displacement.uy(:,I);
RD.uz = R.Displacement.uz(:,I);
figure("units","normalized","outerposition",[0 0 1 1]);
subplot(2,2,1)
pdeplot3D(fmodel,"ColorMapData",R.Displacement.ux(:,I), ...
"Deformation",RD,"DeformationScaleFactor",1);
title("x-Displacement")
subplot(2,2,2)
pdeplot3D(fmodel,"ColorMapData",R.Displacement.uy(:,I), ...
"Deformation",RD,"DeformationScaleFactor",1);
title("y-Displacement")
subplot(2,2,3)
pdeplot3D(fmodel,"ColorMapData",R.Displacement.uz(:,I), ...
"Deformation",RD,"DeformationScaleFactor",1);
title("z-Displacement")
subplot(2,2,4)
pdeplot3D(fmodel,"ColorMapData",R.Displacement.Magnitude(:,I), ...
"Deformation",RD,"DeformationScaleFactor",1);
title("Magnitude")
3-46
Modal and Frequency Response Analysis for Single Part of Kinova Gen3 Robotic Arm
clf
You also can plot the same results by using the Visualize PDE Results Live Editor task. First, create
a new live script by clicking the New Live Script button in the File section on the Home tab.
On the Live Editor tab, select Task > Visualize PDE Results. This action inserts the task into your
script.
3-47
3 Solving PDEs
Plot the components and the magnitude of the displacement at the peak response frequency. To plot
the x-displacement, follow these steps. To plot the y- and z-displacements and the magnitude, follow
the same steps, but set Component to Y, Z, and Magnitude, respectively.
1 In the Select results section of the task, select R from the drop-down menu.
2 In the Specify data parameters section of the task, set Type to Displacement, Component to
X, and Frequency to 2655.7789 Hz.
3 In the Specify visualization parameters section of the task, clear the Deformation check box.
% Data to
meshData = R.Mesh;
nodalData = R.Displacement.ux(:,152);
deformationData = [R.Displacement.ux(:,152) ...
R.Displacement.uy(:,152) ...
R.Displacement.uz(:,152)];
phaseData = cospi(0) + 1i*sinpi(0);
3-48
Modal and Frequency Response Analysis for Single Part of Kinova Gen3 Robotic Arm
"DeformationScaleFactor",0, ...
"ColorLimits",[-7.414e-05 7.414e-05]);
Pressure Function
Define a pressure function, pressFcnFR, to calculate a push and a twist pressure signal. The push
pressure component is uniform. The twist pressure component applies positive pressure on the left
side and negative pressure on the right side of the face. The value of the twist pressure loading
increases in a parabolic distribution from the minimum at point C to the positive peak at L and to the
negative peak at R. The twist pressure factor for the parabolic distribution obtained in pressFcnFR
is multiplied with a sinusoidal function with a magnitude of 0.1 MPa. The uniform push pressure
value is 10 kPa.
3-49
3 Solving PDEs
function p = pressFcnFR(region,~)
meanY = mean(region.y);
absMaxY = max(abs(region.y));
scaleFactor = zeros(size(region.y));
p = 10E3 + 0.1E6*scaleFactor;
end
3-50
Thermal Stress Analysis of Jet Engine Turbine Blade
This example shows how to compute the thermal stress and deformation of a turbine blade in its
steady-state operating condition. The blade has interior cooling ducts. The cool air flowing through
the ducts maintains the temperature of the blade within the limit for its material. This feature is
common in modern blades.
A turbine is a component of the jet engine. It is responsible for extracting energy from the high-
temperature and high-pressure gas produced in the combustion chamber and transforming it into
rotational motion to produce thrust. The turbine is a radial array of blades typically made of nickel
alloys. These alloys resist the extremely high temperatures of the gases. At such temperatures, the
material expands significantly, producing mechanical stress in the joints and significant deformations
of several millimeters. To avoid mechanical failure and friction between the tip of the blade and the
turbine casing, the blade design must account for the stress and deformations.
1 Perform structural analysis accounting only for pressure of the surrounding gases while ignoring
thermal effects.
2 Compute the thermal stress while ignoring the pressure.
3 Combine the pressure and thermal stress.
Pressure Loading
The blade experiences high pressure from the surrounding gases. Compute the stress caused only by
this pressure.
smodel = createpde("structural","static-solid");
importGeometry(smodel,"Blade.stl");
figure
pdegplot(smodel,"FaceLabels","on","FaceAlpha",0.5)
3-51
3 Solving PDEs
msh = generateMesh(smodel,"Hmax",0.01);
Specify Young's modulus, Poisson's ratio, and the coefficient of thermal expansion for nickel-based
alloy (NIMONIC 90).
E = 227E9; % in Pa
CTE = 12.7E-6; % in 1/K
nu = 0.27;
structuralProperties(smodel,"YoungsModulus",E, ...
"PoissonsRatio",nu, ...
"CTE",CTE);
Specify that the face of the root that is in contact with other metal is fixed.
structuralBC(smodel,"Face",3,"Constraint","fixed");
Specify the pressure load on the pressure and suction sides of the blade. This pressure is due to the
high-pressure gas surrounding these sides of the blade.
p1 = 5e5; %in Pa
p2 = 4.5e5; %in Pa
3-52
Thermal Stress Analysis of Jet Engine Turbine Blade
Plot the von Mises stress and the displacement. Specify a deformation scale factor of 100 to better
visualize the deformation.
figure
pdeplot3D(smodel,"ColorMapData",Rs.VonMisesStress, ...
"Deformation",Rs.Displacement, ...
"DeformationScaleFactor",100)
view([116,25]);
The maximum stress is around 100 Mpa, which is significantly below the elastic limit.
Thermal Stress
Determine the temperature distribution and compute the stress and deformation due to thermal
expansion only. This part of the example ignores the pressure.
Import the same geometry and use the same mesh as for the structural analysis.
importGeometry(tmodel,"Blade.stl");
tmodel.Mesh = msh;
3-53
3 Solving PDEs
Assuming that the blade is made of nickel-based alloy (NIMONIC 90), specify the thermal
conductivity.
Convective heat transfer between the surrounding fluid and the faces of the blade defines the
boundary conditions for this problem. The convection coefficient is greater where the gas velocity is
higher. Also, the gas temperature is different around different faces. The temperature of the interior
∘ ∘
cooling air is 150 C, while the temperature on the pressure and suction sides is 1000 C.
% Interior cooling
thermalBC(tmodel,"Face",[15 12 14], ...
"ConvectionCoefficient",30, ...
"AmbientTemperature",150);
% Pressure side
thermalBC(tmodel,"Face",11, ...
"ConvectionCoefficient",50, ...
"AmbientTemperature",1000);
% Suction side
thermalBC(tmodel,"Face",10, ...
"ConvectionCoefficient",40, ...
"AmbientTemperature",1000);
% Tip
thermalBC(tmodel,"Face",13, ...
"ConvectionCoefficient",20, ...
"AmbientTemperature",1000);
% Base (exposed to hot gases)
thermalBC(tmodel,"Face",1, ...
"ConvectionCoefficient",40, ...
"AmbientTemperature",800);
% Root in contact with hot gases
thermalBC(tmodel,"Face",[6 9 8 2 7], ...
"ConvectionCoefficient",15, ...
"AmbientTemperature",400);
The boundary condition for the faces of the root in contact with other metal is a thermal contact that
can be modeled as convection with a very large coefficient (around 1000 W / m2K for metal-metal
contact).
Rt = solve(tmodel);
Plot the temperature distribution. The temperature between the tip and the root ranges from around
∘ ∘ ∘
820 C to 330 C. The exterior gas temperature is 1000 C. The interior cooling is efficient: it
significantly lowers the temperature.
figure
pdeplot3D(tmodel,"ColorMapData",Rt.Temperature)
view([130,-20]);
3-54
Thermal Stress Analysis of Jet Engine Turbine Blade
Now, create a static structural model to compute the stress and deformation due to thermal
expansion.
tsmodel = createpde("structural","static-solid");
Import the same geometry, and use the same mesh and structural properties of the material as for the
structural analysis.
importGeometry(tsmodel,"Blade.stl");
tsmodel.Mesh = msh;
structuralProperties(tsmodel,"YoungsModulus",E, ...
"PoissonsRatio",nu, ...
"CTE",CTE);
structuralBC(tsmodel,"Face",3,"Constraint","fixed");
Rts = solve(tsmodel);
3-55
3 Solving PDEs
Plot the von Mises stress and the displacement. Specify a deformation scale factor of 100 to better
visualize the deformation. The stress concentrates in the constrained root because it cannot freely
expand, and also in the junction between the blade and the root.
figure("units","normalized","outerposition",[0 0 1 1]);
pdeplot3D(tsmodel,"ColorMapData",Rts.VonMisesStress, ...
"Deformation",Rts.Displacement, ...
"DeformationScaleFactor",100)
clim([0, 200e6])
view([116,25]);
Evaluate the displacement at the tip. In the design of the cover, this displacement must be taken into
account to avoid friction between the cover and the blade.
max(Rts.Displacement.Magnitude)
ans = 0.0015
3-56
Thermal Stress Analysis of Jet Engine Turbine Blade
Compute the stress and deformations caused by the combination of thermal and pressure effects.
Use the same model as for the thermal stress analysis. Add the pressure load on the pressure and
suction sides of the blade. This pressure is due to the high-pressure gas surrounding these sides of
the blade.
% Pressure side
structuralBoundaryLoad(tsmodel,"Face",11, ...
"Pressure",p1);
% Suction side
structuralBoundaryLoad(tsmodel,"Face",10, ...
"Pressure",p2);
Rc = solve(tsmodel);
Plot the von Mises stress and the displacement. Specify a deformation scale factor of 100 to better
visualize the deformation.
figure("units","normalized","outerposition",[0 0 1 1]);
pdeplot3D(tsmodel,"ColorMapData",Rc.VonMisesStress, ...
"Deformation",Rc.Displacement, ...
"DeformationScaleFactor",100)
clim([0, 200e6])
view([116,25]);
3-57
3 Solving PDEs
Evaluate the maximum stress and maximum displacement. The displacement is almost the same as
for the thermal stress analysis, while the maximum stress, 854 MPa, is significantly higher.
max(Rc.VonMisesStress)
ans = 9.3920e+08
max(Rc.Displacement.Magnitude)
ans = 0.0015
3-58
Finite Element Analysis of Electrostatically Actuated MEMS Device
This example shows a simple approach to the coupled electromechanical finite element analysis of an
electrostatically actuated micro-electromechanical (MEMS) device. For simplicity, this example uses
the relaxation-based algorithm rather than the Newton method to couple the electrostatic and
mechanical domains.
MEMS Devices
MEMS devices typically consist of movable thin beams or electrodes with a high aspect ratio that are
suspended over a fixed electrode.
Actuation, switching, and other signal and information processing functions can use the electrode
deformation caused by the application of voltage between the movable and fixed electrodes. FEM
provides a convenient tool for characterizing the inner workings of MEMS devices, and can predict
temperatures, stresses, dynamic response characteristics, and possible failure mechanisms. One of
the most common MEMS switches is the series of cantilever beams suspended over a ground
electrode.
3-59
3 Solving PDEs
This example uses the following geometry to model a MEMS switch. The top electrode is 150 μm in
length and 2 μm in thickness. Young’s modulus E is 170 GPa, and Poisson’s ratio υ is 0.34. The bottom
electrode is 50 μm in length and 2 μm in thickness, and is located 100 μm from the leftmost end of
the top electrode. The gap between the top and bottom electrodes is 2 μm.
3-60
Finite Element Analysis of Electrostatically Actuated MEMS Device
A voltage applied between the top electrode and the ground plane induces electrostatic charges on
the surface of the conductors, which in turn leads to electrostatic forces acting normal to the surface
of the conductors. Because the ground plane is fixed, the electrostatic forces deform only the top
electrode. When the beam deforms, the charge redistributes on the surface of the conductors. The
resultant electrostatic forces and the deformation of the beam also change. This process continues
until the system reaches a state of equilibrium.
For simplicity, this example uses the relaxation-based algorithm rather than the Newton method to
couple the electrostatic and mechanical domains. The example follows these steps:
1. Solve the electrostatic FEA problem in the nondeformed geometry with the constant potential V0
on the movable electrode.
2. Compute the load and boundary conditions for the mechanical solution by using the calculated
values of the charge density along the movable electrode. The electrostatic pressure on the movable
electrode is given by
1 2
P= | D| ,
2ϵ
where |D| is the magnitude of the electric flux density and ϵ is the electric permittivity next to the
movable electrode.
3. Compute the deformation of the movable electrode by solving the mechanical FEA problem.
4. Update the charge density along the movable electrode by using the calculated displacement of the
movable electrode,
G
|Ddef x | ≈ | D0 x | ,
G − v(x)
where |Ddef x | is the magnitude of the electric flux density in the deformed electrode, |D0 x | is the
magnitude of the electric flux density in the undeformed electrode, G is the distance between the
movable and fixed electrodes in the absence of actuation, and v x is the displacement of the movable
electrode at position x along its axis.
5. Repeat steps 2–4 until the electrode deformation values in the last two iterations converge.
Electrostatic Analysis
In the electrostatic analysis part of this example, you compute the electric potential around the
electrodes.
First, create the cantilever switch geometry by using the constructive solid geometry (CSG) modeling
approach. The geometry for electrostatic analysis consists of three rectangles represented by a
matrix. Each column of the matrix describes a basic shape.
3-61
3 Solving PDEs
Create a name for each basic shape. Specify the names as a matrix whose columns contain the names
of the corresponding columns in the basic shape matrix.
ns = char('rect_domain','rect_movable','rect_fixed');
ns = ns';
Create a formula describing the unions and intersections of the basic shapes.
sf = 'rect_domain-(rect_movable+rect_fixed)';
dl = decsg(gd,sf,ns);
model = createpde;
geometryFromEdges(model,dl);
pdegplot(model,"EdgeLabels","on","FaceLabels","on")
xlabel("x-coordinate, meters")
ylabel("y-coordinate, meters")
axis([-2e-4,2e-4,-4e-5,4e-5])
axis square
3-62
Finite Element Analysis of Electrostatically Actuated MEMS Device
Set constant potential values of 20 V to the movable electrode and 0 V to the fixed electrode and
domain boundary.
V0 = 0;
V1 = 20;
applyBoundaryCondition(model,"dirichlet", ...
"Edge",[4,8,9,10],"u",V0);
applyBoundaryCondition(model,"dirichlet", ...
"Edge",[1,2,5,6],"u",V0);
applyBoundaryCondition(model,"dirichlet", ...
"Edge",[3,7,11,12],"u",V1);
− ∇ ⋅ (ϵ ∇V) = ρ,
where ϵ is the coefficient of permittivity and ρ is the charge density. 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.
specifyCoefficients(model,"m",0,"d",0,"c",1,"a",0,"f",0);
hmax = 5e-6;
generateMesh(model,"Hmax",hmax);
pdeplot(model)
xlabel("x-coordinate, meters")
ylabel("y-coordinate, meters")
axis([-2e-4, 2e-4,-4e-5, 4e-5])
axis square
3-63
3 Solving PDEs
results = solvepde(model);
u = results.NodalSolution;
figure
pdeplot(model,"XYData",results.NodalSolution, ...
"ColorMap","jet");
title("Electric Potential");
xlabel("x-coordinate, meters")
ylabel("y-coordinate, meters")
axis([-2e-4,2e-4,-4e-5,4e-5])
axis square
3-64
Finite Element Analysis of Electrostatically Actuated MEMS Device
You also can plot the electric potential in the exterior domain by using the Visualize PDE Results
Live Editor task. First, create a new live script by clicking the New Live Script button in the File
section on the Home tab.
On the Live Editor tab, select Task > Visualize PDE Results. This action inserts the task into your
script.
3-65
3 Solving PDEs
1 In the Select results section of the task, select results from the drop-down list.
2 In the Specify data parameters section of the task, set Type to Nodal solution.
3-66
Finite Element Analysis of Electrostatically Actuated MEMS Device
Mechanical Analysis
In the mechanical analysis part of this example, you compute the deformation of the movable
electrode.
structuralmodel = createpde("structural","static-planestress");
Create the movable electrode geometry and include it in the model. Plot the geometry.
dl = decsg(rect_movable);
geometryFromEdges(structuralmodel,dl);
pdegplot(structuralmodel,"EdgeLabels","on")
xlabel("x-coordinate, meters")
ylabel("y-coordinate, meters")
axis([-1e-4,1e-4,-1e-5,1e-5])
axis square
3-67
3 Solving PDEs
Specify the structural properties: Young's modulus E is 170 GPa and Poisson's ratio ν is 0.34.
structuralProperties(structuralmodel,"YoungsModulus",170e9, ...
"PoissonsRatio",0.34);
Specify the pressure as a boundary load on the edges. The pressure tends to draw the conductor into
the field regardless of the sign of the surface charge. For the definition of the
CalculateElectrostaticPressure function, see Electrostatic Pressure Function on page 3-71.
pressureFcn = @(location,state) - ...
CalculateElectrostaticPressure(results,[],location);
structuralBoundaryLoad(structuralmodel,"Edge",[1,2,4], ...
"Pressure",pressureFcn, ...
"Vectorized","on");
Generate a mesh.
hmax = 1e-6;
generateMesh(structuralmodel,"Hmax",hmax);
pdeplot(structuralmodel);
xlabel("x-coordinate, meters")
ylabel("y-coordinate, meters")
axis([-1e-4, 1e-4,-1e-5, 1e-5])
axis square
3-68
Finite Element Analysis of Electrostatically Actuated MEMS Device
R = solve(structuralmodel);
pdeplot(structuralmodel,"XYData",R.VonMisesStress, ...
"Deformation",R.Displacement, ...
"DeformationScaleFactor",10, ...
"ColorMap","jet");
3-69
3 Solving PDEs
Repeatedly update the charge density along the movable electrode and solve the model until the
electrode deformation values converge.
olddisp = 0;
while abs((maxdisp-olddisp)/maxdisp) > 1e-10
% Impose boundary conditions
pressureFcn = @(location,state) - ...
CalculateElectrostaticPressure(results,R,location);
bl = structuralBoundaryLoad(structuralmodel, ...
"Edge",[1,2,4], ...
"Pressure",pressureFcn, ...
"Vectorized","on");
% Solve the equations
R = solve(structuralmodel);
olddisp = maxdisp;
maxdisp = max(abs(R.Displacement.uy));
delete(bl)
end
3-70
Finite Element Analysis of Electrostatically Actuated MEMS Device
pdeplot(structuralmodel,"XYData",R.VonMisesStress, ...
"Deformation",R.Displacement, ...
"DeformationScaleFactor",10, ...
"ColorMap","jet");
maxdisp = max(abs(R.Displacement.uy));
fprintf('Finite element maximal tip deflection is: %12.4e\n', maxdisp);
References
[1] Sumant, P. S., N. R. Aluru, and A. C. Cangellaris. “A Methodology for Fast Finite Element Modeling
of Electrostatically Actuated MEMS.” International Journal for Numerical Methods in Engineering.
Vol 77, Number 13, 2009, 1789-1808.
3-71
3 Solving PDEs
1 2
P= | D| ,
2ϵ
where |D | = ϵ | E| is the magnitude of the electric flux density, ϵ is the electric permittivity next to the
movable electrode, and E is the magnitude of the electric field. The electric field E is the gradient of
the electric potential V :
E = − ∇V.
Solve the mechanical FEA to compute the deformation of the movable electrode. Using the calculated
displacement of the movable electrode, update the charge density along the movable electrode.
G
|Ddef x | ≈ | D0 x | ,
G − v(x)
where |Ddef x | is the magnitude of the electric flux density in the deformed electrode, |D0 x | is the
magnitude of the electric flux density in the undeformed electrode, G is the distance between the
movable and fixed electrodes in the absence of actuation, and v x is the displacement of the movable
electrode at position x along its axis. Initially, the movable electrode is undeformed, v x = 0, and
therefore, Ddef x ≈ D0 x .
3-72
Finite Element Analysis of Electrostatically Actuated MEMS Device
vdisp = abs(intrpDisp.uy);
G = 2e-6; % Gap 2 micron
absD = absD0.*G./(G-vdisp);
end
end
3-73
3 Solving PDEs
This example shows how to analyze a 3-D mechanical part under an applied load using finite element
analysis (FEA) and determine the maximal deflection.
The first step in solving a linear elasticity problem is to create a structural analysis model. This model
is a container that holds the geometry, structural material properties, damping parameters, body
loads, boundary loads, boundary constraints, superelement interfaces, initial displacement and
velocity, and mesh.
model = createpde("structural","static-solid");
Import Geometry
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");
figure
pdegplot(model,"FaceLabels","on")
view(30,30);
title("Bracket with Face Labels")
3-74
Deflection Analysis of Bracket
figure
pdegplot(model,"FaceLabels","on")
view(-134,-32)
title("Bracket with Face Labels, Rear View")
3-75
3 Solving PDEs
structuralProperties(model,"YoungsModulus",200e9, ...
"PoissonsRatio",0.3);
The problem has two boundary conditions: the back face (face 4) is fixed, and the front face (face 8)
has an applied load. All other boundary conditions, by default, are free boundaries.
structuralBC(model,"Face",4,"Constraint","fixed");
structuralBoundaryLoad(model,"Face",8,"SurfaceTraction",[0;0;-1e4]);
Generate Mesh
generateMesh(model);
figure
pdeplot3D(model)
title("Mesh with Quadratic Tetrahedral Elements");
3-76
Deflection Analysis of Bracket
Calculate Solution
result =
StaticStructuralResults with properties:
Examine Solution
Visualize the displacement components and the von Mises stress by using the Visualize PDE
Results Live Editor task. The maximal deflections are in the z-direction. Because the bracket and the
3-77
3 Solving PDEs
load are symmetric, the x-displacement and z-displacement are symmetric, and the y-displacement is
antisymmetric with respect to the center line.
First, create a new live script by clicking the New Live Script button in the File section on the
Home tab.
On the Live Editor tab, select Task > Visualize PDE Results. This action inserts the task into your
script.
To plot the z-displacement, follow these steps. To plot the x- and y-displacements, follow the same
steps, but set Component to X and Y, respectively.
1 In the Select results section of the task, select result from the drop-down list.
2 In the Specify data parameters section of the task, set Type to Displacement and Component
to Z.
3 In the Specify visualization parameters section of the task, clear the Deformation check box.
Here, the blue color represents the lowest displacement value, and the red color represents the
highest displacement value. The bracket load causes face 8 to dip down, so the maximum z-
displacement appears blue.
3-78
Deflection Analysis of Bracket
To plot the von Mises stress, in the Specify data parameters section of the task, set Type to Stress
and Component to von Mises.
3-79
3 Solving PDEs
You also can plot the results, such as the displacement components and the von Mises stress, at the
MATLAB® command line by using the pdeplot3D function.
figure
pdeplot3D(model,"ColorMapData",result.Displacement.ux)
title("x-displacement")
colormap("jet")
3-80
Deflection Analysis of Bracket
figure
pdeplot3D(model,"ColorMapData",result.Displacement.uy)
title("y-displacement")
colormap("jet")
3-81
3 Solving PDEs
figure
pdeplot3D(model,"ColorMapData",result.Displacement.uz)
title("z-displacement")
colormap("jet")
3-82
Deflection Analysis of Bracket
figure
pdeplot3D(model,"ColorMapData",result.VonMisesStress)
title("von Mises stress")
colormap("jet")
3-83
3 Solving PDEs
3-84
Deflection Analysis of Bracket
The first step in solving this linear elasticity problem is to create an femodel object for structural
analysis with a geometry representing a simple bracket.
Plot Geometry
Plot the front and rear views of the geometry with face labels.
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")
3-85
3 Solving PDEs
model.MaterialProperties = ...
materialProperties(YoungsModulus=200e9, ...
PoissonsRatio=0.3);
The problem has two boundary conditions: the back face (face 4) is fixed, and the front face (face 8)
has an applied load. All other boundary conditions, by default, are free boundaries.
model.FaceBC(4) = faceBC(Constraint="fixed");
model.FaceLoad(8) = faceLoad(SurfaceTraction=[0;0;-1e4]);
Generate Mesh
Generate a mesh and assign the result to the model. This assignment updates the mesh stored in the
Geometry property of the model. Plot the mesh.
model = generateMesh(model);
figure
pdemesh(model);
title("Mesh with Quadratic Tetrahedral Elements")
3-86
Deflection Analysis of Bracket
Calculate Solution
result = solve(model)
result =
Examine Solution
minUz = min(result.Displacement.uz);
fprintf("Maximal deflection in the z-direction is %g meters.",minUz)
Visualize the displacement components and the von Mises stress by using the Visualize PDE
Results Live Editor task. The maximal deflections are in the z-direction. Because the bracket and the
load are symmetric, the x-displacement and z-displacement are symmetric, and the y-displacement is
antisymmetric with respect to the center line.
3-87
3 Solving PDEs
First, create a new live script by clicking the New Live Script button in the File section on the
Home tab.
On the Insert tab, select Task > Visualize PDE Results. This action inserts the task into your
script.
To plot the z-displacement, follow these steps. To plot the x- and y-displacements, follow the same
steps, but set Component to X and Y, respectively.
1 In the Select results section of the task, select result from the drop-down list.
2 In the Specify data parameters section of the task, set Type to Displacement and
Component to Z.
3 In the Specify visualization parameters section of the task, clear the Deformation check box.
Here, the blue color represents the lowest displacement value, and the red color represents the
highest displacement value. The bracket load causes face 8 to dip down, so the maximum z-
displacement appears blue.
3-88
Deflection Analysis of Bracket
To plot the von Mises stress, in the Specify data parameters section of the task, set Type to Stress
and Component to von Mises.
3-89
3 Solving PDEs
3-90
Deflection Analysis of Bracket
You also can plot the results, such as the displacement components and the von Mises stress, at the
MATLAB® command line by using the pdeplot3D function.
figure
pdeplot3D(result.Mesh,ColorMapData=result.Displacement.ux);
title("x-displacement")
colormap("jet")
figure
pdeplot3D(result.Mesh,ColorMapData=result.Displacement.uy)
title("y-displacement")
colormap("jet")
3-91
3 Solving PDEs
figure
pdeplot3D(result.Mesh,ColorMapData=result.Displacement.uz)
title("z-displacement")
colormap("jet")
3-92
Deflection Analysis of Bracket
figure
pdeplot3D(result.Mesh,ColorMapData=result.VonMisesStress)
title("von Mises stress")
colormap("jet")
3-93
3 Solving PDEs
3-94
Vibration of Square Plate
This example shows how to calculate the vibration modes and frequencies of a 3-D simply supported,
square, elastic 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-95
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 z-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.
generateMesh(model,"Hmin",1.3);
figure
pdeplot3D(model);
title("Mesh with Quadratic Tetrahedral Elements");
3-96
Vibration of Square Plate
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]);
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 3.809e-05
0 1.447e-05
0 2.5238e-05
3-97
3 Solving PDEs
45.897 44.914
109.44 109.83
109.44 109.87
167.89 168.81
193.59 193.74
206.19 207.53
206.19 207.54
You see good agreement between the computed and published frequencies.
Plot the third component (z-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-98
Vibration of Square Plate
Reference
[1] National Agency for Finite Element Methods and Standards. The Standard NAFEMS Benchmarks.
United Kingdom: NAFEMS, October 1990.
3-99
3 Solving PDEs
This example shows how to perform modal and transient analysis of a tuning fork.
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 the tines. The lack of bending at the base enables easy handling of the
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 a symmetric
mode shape is about 6.25 times the fundamental frequency. Therefore, a properly excited tuning fork
vibrates with a dominant frequency corresponding to the 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.
You can find the helper functions animateSixTuningForkModes and tuningForkFFT and the
geometry file TuningFork.stl at matlab/R20XXx/examples/pde/main.
Find natural frequencies and mode shapes for the fundamental mode and the next several modes of a
tuning fork. Show the lack of bending effect on the fork handle at the fundamental frequency.
First, create a finite element model for modal analysis of a solid tuning fork.
pdegplot(model);
3-100
Structural Dynamics of Tuning Fork
To perform unconstrained modal analysis of a structure, it is enough to specify the geometry, mesh,
and material properties. First, specify Young's modulus, Poisson's ratio, and the mass density to
model linear elastic material behavior. Specify all physical properties in consistent units.
E = 210e9;
nu = 0.3;
rho = 8000;
model.MaterialProperties = materialProperties(YoungsModulus=E, ...
PoissonsRatio=nu, ...
MassDensity=rho);
Generate a mesh.
model = generateMesh(model,Hmax=0.001);
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=[-Inf,4000]*2*pi);
modeID = 1:numel(RF.NaturalFrequencies);
Express the resulting frequencies in Hz by dividing them by 2π. Display the frequencies in a table.
3-101
3 Solving PDEs
tmodalResults = table(modeID.',RF.NaturalFrequencies/(2*pi));
tmodalResults.Properties.VariableNames = {'Mode','Frequency'};
disp(tmodalResults);
Mode Frequency
____ _________
1 0.011986
2 0.0072377
3 0.0058197
4 0.0031717
5 0.0072558
6 0.013357
7 460.43
8 706.3
9 1911.6
10 2105.6
11 2906.6
12 3814.6
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. You can use the Visualize PDE Results Live Editor task to animate the data. Specify
the results to visualize as RF and the type as Mode shapes. Specify the mode as the first flexible mode
(the seventh mode in the list) and select Animate.
% Data to
meshData = RF.Mesh;
nodalData = RF.ModeShapes.Magnitude(:,7);
deformationData = [RF.ModeShapes.ux(:,7) ...
RF.ModeShapes.uy(:,7) ...
RF.ModeShapes.uz(:,7)];
phaseData = cospi(0) + 1i*sinpi(0);
3-102
Structural Dynamics of Tuning Fork
"DeformationData",deformationData*phaseData, ...
"DeformationScaleFactor",0.00016521, ...
"AxesVisible",false, ...
"ColorbarVisible",false, ...
"ColorLimits",[0 19.48]);
% Animate
for ii = 0:0.01:2
phaseData = cospi(ii) + 1i*sinpi(ii);
resultViz.NodalData = abs(real(nodalData*phaseData));
resultViz.DeformationData = deformationData*phaseData;
pause(0.01)
end
frames = animateSixTuningForkModes(RF);
3-103
3 Solving PDEs
movie(figure("units","normalized","outerposition",[0 0 1 1]),frames,5,30)
In the first mode, the 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 around 2907 Hz.
This frequency is about 6 times greater than the fundamental frequency of 460 Hz.
Simulate the dynamics of a tuning fork being gently and quickly struck on one of its tines. Analyze the
vibration of the tines over time and the axial vibration of the handle.
First, switch the analysis type for the model object to transient structural.
model.AnalysisType = "structuralTransient";
Generate a coarser mesh to speed up computations. Specify the Hface name-value argument to
generate a finer mesh for small faces.
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(model,FaceLabels="on");
view(-50,15)
title("Geometry with Face Labels")
3-104
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 the tines and the handle (faces 21 and 22).
model.FaceBC([21,22]) = faceBC(Constraint="fixed");
Approximate an impulse loading on a face of 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 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 the modal analysis.
T7 = 2*pi/RF.NaturalFrequencies(7);
Specify the pressure loading on a tine as a short rectangular pressure pulse by using the
trapezoidalLoad function. For details, see Trapezoidal Pulse Load on page 3-109.
P = 5e6;
T = setUpTrapezoid(EndTime=T7/300);
pressurePulse = @(location,state) trapezoidalLoad(P,location,state,T);
model.FaceLoad(11) = faceLoad(Pressure=pressurePulse);
Solve the transient model for 50 periods of the fundamental mode. Sample the dynamics 60 times per
period of the fundamental mode.
ncycle = 50;
samplingFrequency = 60/T7;
3-105
3 Solving PDEs
tlist = linspace(0,ncycle*T7,ncycle*T7*samplingFrequency);
R = solve(model,tlist);
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(model.Geometry.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")
Perform a fast Fourier transform (FFT) of 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,samplingFrequency);
figure
plot(fTip,PTip)
title(["Single-Sided Amplitude Spectrum","of Tip Vibration"])
xlabel("f (Hz)")
ylabel("|P1(f)|")
xlim([0,4000])
3-106
Structural Dynamics of Tuning Fork
Transverse vibration of the 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 = model.Mesh.findNodes("region",Face=6);
baseDisp = R.Displacement.ux(baseNodes(1),:);
figure
plot(R.SolutionTimes,baseDisp)
title("Axial Displacement at End of Handle")
xlim([0,0.1])
ylabel("x-Displacement")
xlabel("Time")
3-107
3 Solving PDEs
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,samplingFrequency);
figure
plot(fBase,PBase)
title(["Single-Sided Amplitude Spectrum","of Base Vibration"])
xlabel("f (Hz)")
ylabel("|P1(f)|")
xlim([0,4000])
3-108
Structural Dynamics of Tuning Fork
function Tn = trapezoidalLoad(load,location,state,T)
if isnan(state.time)
Tn = NaN*(location.nx);
return
end
if isa(load,"function_handle")
load = load(location,state);
else
load = load(:);
end
% Four time-points that define a trapezoidal pulse
T1 = T(1); % Start time
T2 = T(2); % Rise time
T3 = T(3); % Fall time
T4 = T(4); % End time
3-109
3 Solving PDEs
The setUpTrapezoid helper function accepts the name-value arguments StartTime, RiseTime,
FallTime, and EndTime and processes these parameters for use in the trapezoidalLoad function.
Pass the output of this function as the last argument of trapezoidalLoad. The default StartTime,
RiseTime, and FallTime values are 0, while the default EndTime value is Inf.
function T = setUpTrapezoid(opts)
arguments
opts.StartTime double {mustBeScalarOrEmpty,mustBeReal} = []
opts.RiseTime double {mustBeScalarOrEmpty,mustBeReal} = []
opts.FallTime double {mustBeScalarOrEmpty,mustBeReal} = []
opts.EndTime double {mustBeScalarOrEmpty,mustBeReal} = []
end
if isempty(opts.StartTime)
opts.StartTime = 0;
end
if isempty(opts.RiseTime)
opts.RiseTime = 0;
3-110
Structural Dynamics of Tuning Fork
end
if isempty(opts.FallTime)
opts.FallTime = 0;
end
if isempty(opts.EndTime) && (opts.FallTime ~= 0)
opts.EndTime = opts.StartTime + opts.RiseTime + opts.FallTime;
elseif isempty(opts.EndTime) && (opts.FallTime == 0)
opts.EndTime = Inf;
end
T = [opts.StartTime;
opts.StartTime + opts.RiseTime;
opts.EndTime - opts.FallTime;
opts.EndTime];
end
3-111
3 Solving PDEs
This example shows how to solve a structural dynamics problem by using modal analysis results.
Solve for the transient response at the center of a 3-D beam under a harmonic load on one of its
corners. Compare the direct integration results with the results obtained by modal superposition.
Modal Analysis
modelM = createpde("structural","modal-solid");
Create the geometry and include it in the model. Plot the geometry and display the edge and vertex
labels.
gm = multicuboid(0.05,0.003,0.003);
modelM.Geometry=gm;
pdegplot(modelM,"EdgeLabels","on","VertexLabels","on");
view([95 5])
Generate a mesh.
msh = generateMesh(modelM);
Specify Young's modulus, Poisson's ratio, and the mass density of the material.
3-112
Modal Superposition Method for Structural Dynamics Problem
structuralProperties(modelM,"YoungsModulus",210E9, ...
"PoissonsRatio",0.3, ...
"MassDensity",7800);
Specify minimal constraints on one end of the beam to prevent rigid body modes. For example,
specify that edge 4 and vertex 7 are fixed boundaries.
structuralBC(modelM,"Edge",4,"Constraint","fixed");
structuralBC(modelM,"Vertex",7,"Constraint","fixed");
Solve the problem for the frequency range from 0 to 500000. The recommended approach is to use a
value that is slightly smaller than the expected lowest frequency. Thus, use -0.1 instead of 0.
Rm = solve(modelM,"FrequencyRange",[-0.1,500000]);
Transient Analysis
modelD = createpde("structural","transient-solid");
Use the same geometry and mesh as for the modal analysis.
modelD.Geometry = gm;
modelD.Mesh = msh;
Specify the same values for Young's modulus, Poisson's ratio, and the mass density of the material.
structuralProperties(modelD,"YoungsModulus",210E9, ...
"PoissonsRatio",0.3, ...
"MassDensity",7800);
Specify the same minimal constraints on one end of the beam to prevent rigid body modes.
structuralBC(modelD,"Edge",4,"Constraint","fixed");
structuralBC(modelD,"Vertex",7,"Constraint","fixed");
Apply a sinusoidal force on the corner opposite the constrained edge and vertex.
structuralBoundaryLoad(modelD,"Vertex",5, ...
"Force",[0,0,10], ...
"Frequency",7600);
structuralIC(modelD,"Velocity",[0;0;0],"Displacement",[0;0;0]);
modelD.SolverOptions.RelativeTolerance = 1E-5;
modelD.SolverOptions.AbsoluteTolerance = 1E-9;
tlist = linspace(0,0.004,120);
Rd = solve(modelD,tlist);
3-113
3 Solving PDEs
tlist = linspace(0,0.004,120);
Rdm = solve(modelD,tlist,"ModalResults",Rm);
intrpUd = interpolateDisplacement(Rd,0,0,0.0015);
intrpUdm = interpolateDisplacement(Rdm,0,0,0.0015);
Compare the direct integration results with the results obtained by modal superposition.
plot(Rd.SolutionTimes,intrpUd.uz,"bo")
hold on
plot(Rdm.SolutionTimes,intrpUdm.uz,"rx")
grid on
legend("Direct integration", "Modal superposition")
xlabel("Time");
ylabel("Center of beam displacement")
3-114
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.
Define the combined GDM, name-space matrix, and set formula to construct decomposed geometry
using decsg.
geometryFromEdges(model,g);
figure
pdegplot(model,"EdgeLabel","on");
axis([-1.2*totalLength 1.2*totalLength -1.2*width 1.2*width])
title("Geometry with Edge Labels")
3-115
3 Solving PDEs
figure
pdegplot(model,"VertexLabels","on");
axis([-1.2*totalLength 1.2*totalLength -1.2*width 1.2*width])
title("Geometry with Vertex Labels")
3-116
Stress Concentration in Plate with Circular Hole
Specify 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 left edge (edge 3) to zero to resist the applied load. Set
the y-component of displacement at the bottom left corner (vertex 3) to zero to restraint the rigid
body motion.
structuralBC(model,"Edge",3,"XDisplacement",0);
structuralBC(model,"Vertex",3,"YDisplacement",0);
Apply the surface traction with a non-zero x-component on the right edge of the plate.
structuralBoundaryLoad(model,"Edge",1,"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);
3-117
3 Solving PDEs
figure
pdemesh(model)
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-118
Stress Concentration in Plate with Circular Hole
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];
Then interpolate stress values at these points by using interpolateStress. This function returns a
structure array with its fields containing interpolated stress values.
stressHole = interpolateStress(R,CircleCoordinates);
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")
3-119
3 Solving PDEs
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.
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);
3-120
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]);
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-121
3 Solving PDEs
3-122
Thermal Deflection of Bimetallic Beam
This example shows how to solve a coupled thermo-elasticity problem. Thermal expansion or
contraction in mechanical components and structures occurs due to temperature changes in the
operating environment. Thermal stress is a secondary manifestation: the structure experiences
stresses when structural constraints prevent free thermal expansion or contraction of the component.
Deflection of a bimetallic beam is a common physics experiment. A typical bimetallic beam consists of
two materials bonded together. The coefficients of thermal expansion (CTE) of these materials are
significantly different.
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]);
structuralmodel.Geometry = gm;
figure
pdegplot(structuralmodel)
3-123
3 Solving PDEs
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 into the left end of
the beam and rotate the geometry.
figure
pdegplot(structuralmodel,"CellLabels","on")
axis([-L/2 -L/3 -W/2 W/2 0 2*H])
view([0 0])
zticks([])
3-124
Thermal Deflection of Bimetallic Beam
Now, display the cell label for the top cell. To see the cell label clearly, zoom into the right end of the
beam and rotate the geometry.
figure
pdegplot(structuralmodel,"CellLabels","on")
axis([L/3 L/2 -W/2 W/2 0 2*H])
view([0 0])
zticks([])
3-125
3 Solving PDEs
Specify Young's modulus, Poisson's ratio, and the 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);
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.
3-126
Thermal Deflection of Bimetallic 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([])
Apply the temperature change as a thermal load. Use a reference temperature of 25 degrees Celsius
and an operating temperature of 125 degrees Celsius. Thus, the temperature change for this model is
100 degrees Celsius.
structuralBodyLoad(structuralmodel,"Temperature",125);
structuralmodel.ReferenceTemperature = 25;
Plot the deflected shape of the bimetallic beam with the magnitude of displacement as the colormap
data.
figure
pdeplot3D(structuralmodel,"ColorMapData",R.Displacement.Magnitude, ...
3-127
3 Solving PDEs
"Deformation",R.Displacement, ...
"DeformationScaleFactor",2)
title("Deflection of Invar-Copper Beam")
You also can plot the deflected shape of the bimetallic beam with the magnitude of displacement as
the colormap data by using the Visualize PDE Results Live Editor task. First, create a new live
script by clicking the New Live Script button in the File section on the Home tab.
On the Live Editor tab, select Task > Visualize PDE Results. This action inserts the task into your
script.
3-128
Thermal Deflection of Bimetallic Beam
1 In the Select results section of the task, select R from the drop-down list.
2 In the Specify data parameters section of the task, set Type to Displacement and Component
to Magnitude.
3-129
3 Solving PDEs
Compute the deflection analytically, based on beam theory. The deflection of the beam is
6Δ T αc − αi L2 Ec Ei
δ= K1
, where K1 = 14 + Ei
+ Ec
, Δ T is the temperature difference, αc and αi are the
coefficients of thermal expansion of copper and invar, Ec and Ei are Young's modulus of copper and
invar, and L is the length of the beam.
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-130
Thermal Deflection of Bimetallic Beam
3-131
3 Solving PDEs
This example shows a quasistatic axisymmetric thermal stress analysis workflow by reproducing the
results of the simplified disc brake model discussed in [1] on page 3-143. Disc brakes absorb
mechanical energy through friction and transform it into thermal energy, which then dissipates. The
example uses a simplified model of a disc brake in a single braking process from a constant initial
angular speed to a standstill. The workflow has two steps:
1 Transient thermal analysis to compute the temperature distribution in the disc using the heat
flux from brake pads
2 Quasistatic structural analysis to compute thermal stresses at several solution times using
previously obtained temperature distribution to specify thermal loads
The resulting plots show the temperature distribution, radial stress, hoop stress, and von Mises stress
for the corresponding solution times.
Based on the assumptions used in [1] on page 3-143, the example reduces the analysis domain to a
rectangular region corresponding to the axisymmetric section of the annular disc. Because of the
geometric and load symmetry of the disc, the example models only half the thickness of the disc and
the effect of one pad. In the following figure, the left edge corresponds to the inner radius of the disc
rd. The right edge corresponds to the outer radius of the disc Rd and also coincides with the outer
radius of the pad Rp. The disc experiences pressure from the pad, which generates the heat flux.
Instead of modeling the pad explicitly, include its effect in the thermal analysis by specifying this heat
flux as a boundary condition from the inner radius of the pad rp to the outer radius of the pad Rp.
modelT = createpde("thermal","transient-axisymmetric");
3-132
Axisymmetric Thermal and Structural Analysis of Disc Brake
Create a geometry with two adjacent rectangles. The top edge of the longer rectangle (on the right)
represents the disc-pad contact region.
geometryFromEdges(modelT,g);
figure
pdegplot(modelT,"EdgeLabels","on","FaceLabels","on")
Generate a mesh. To match the mesh used in [1] on page 3-143, use the linear geometric order
instead of the default quadratic order.
generateMesh(modelT,"Hmax",0.5E-04,"GeometricOrder","linear");
3-133
3 Solving PDEs
rhod = 7100;
cpd = Kd/rhod/alphad;
thermalProperties(modelT,"ThermalConductivity",Kd, ...
"MassDensity",rhod, ...
"SpecificHeat",cpd);
Specify the heat flux boundary condition to account for the pad region. For the definition of the qFcn
function, see Heat Flux Function on page 3-141.
thermalBC(modelT,"Edge",6,"HeatFlux",@qFcn);
thermalIC(modelT,20);
Solve the model for the times used in [1] on page 3-143.
Plot the temperature variation with time at three key radial locations. The resulting plot is
comparable to the plot obtained in [1] on page 3-143.
iTRd = interpolateTemperature(Rt,[0.1135;0],1:numel(Rt.SolutionTimes));
iTrp = interpolateTemperature(Rt,[0.0765;0],1:numel(Rt.SolutionTimes));
iTrd = interpolateTemperature(Rt,[0.066;0],1:numel(Rt.SolutionTimes));
figure
plot(tlist,iTRd)
hold on
plot(tlist,iTrp)
plot(tlist,iTrd)
title("Temperature Variation with Time at Key Radial Locations")
legend("R_d","r_p","r_d")
xlabel("t, s")
ylabel("T,^{\circ}C")
3-134
Axisymmetric Thermal and Structural Analysis of Disc Brake
model = createpde("structural","static-axisymmetric");
Assign the geometry and mesh used for the thermal model.
model.Geometry = modelT.Geometry;
model.Mesh = modelT.Mesh;
structuralProperties(model,"YoungsModulus",99.97E9, ...
"PoissonsRatio",0.29, ...
"CTE",1.08E-5);
structuralBC(model,"Edge",[3,4],"ZDisplacement",0);
Specify the reference temperature that corresponds to the state of zero thermal stress of the model.
model.ReferenceTemperature = 20;
Specify the thermal load by using the transient thermal results Rt. The solution times are the same as
in the thermal model analysis. For each solution time, solve the corresponding static structural
analysis problem and plot the temperature distribution, radial stress, hoop stress, and von Mises
3-135
3 Solving PDEs
stress. For the definition of the plotResults function, see Plot Results Function on page 3-142. The
results are comparable to figure 5 from [1] on page 3-143.
for n = 2:numel(Rt.SolutionTimes)
structuralBodyLoad(model,"Temperature",Rt,"TimeStep",n);
R = solve(model);
plotResults(model,R,modelT,Rt,n);
end
3-136
Axisymmetric Thermal and Structural Analysis of Disc Brake
3-137
3 Solving PDEs
3-138
Axisymmetric Thermal and Structural Analysis of Disc Brake
3-139
3 Solving PDEs
3-140
Axisymmetric Thermal and Structural Analysis of Disc Brake
This helper function computes the transient value of the heat flux from the pad to the disc. It uses the
empirical formula from [1] on page 3-143.
function q = qFcn(r,s)
alphad = 1.44E-5; % Diffusivity of disc
Kd = 51; % Conductivity of disc
rhod = 7100; % Density of disc
cpd = Kd/rhod/alphad; % Specific heat capacity of disc
3-141
3 Solving PDEs
This helper function plots the temperature distribution, radial stress, hoop stress, and von Mises
stress.
function plotResults(model,R,modelT,Rt,tID)
figure
subplot(2,2,1)
pdeplot(modelT,"XYData",Rt.Temperature(:,tID), ...
"ColorMap","jet","Contour","on")
xt = xticks;
yt = yticks;
xticklabels(100*xt);
yticklabels(100*yt);
xlabel("x,cm")
ylabel("y,cm")
title({'Temperature'; ...
['max = ' num2str(max(Rt.Temperature(:,tID))) '^{\circ}C']}, ...
FontSize=10)
subplot(2,2,2)
pdeplot(model,"XYData",R.Stress.srr, ...
"ColorMap","jet","Contour","on")
xt = xticks;
yt = yticks;
xticklabels(100*xt);
yticklabels(100*yt);
xlabel("x,cm")
ylabel("y,cm")
title({'Radial Stress'; ...
['min = ' num2str(min(R.Stress.srr)/1E6,'%3.2f') ' MPa']
['max = ' num2str(max(R.Stress.srr)/1E6,'%3.2f') ' MPa']}, ...
FontSize=10)
subplot(2,2,3)
pdeplot(model,"XYData",R.Stress.sh, ...
"ColorMap","jet","Contour","on")
xt = xticks;
yt = yticks;
xticklabels(100*xt);
yticklabels(100*yt);
xlabel("x,cm")
ylabel("y,cm")
title({'Hoop Stress'; ...
['min = ' num2str(min(R.Stress.sh)/1E6,'%3.2f') ' MPa']
['max = ' num2str(max(R.Stress.sh)/1E6,'%3.2f') ' MPa']}, ...
FontSize=10)
subplot(2,2,4)
pdeplot(model,"XYData",R.VonMisesStress, ...
"ColorMap","jet","Contour","on")
xt = xticks;
yt = yticks;
xticklabels(100*xt);
yticklabels(100*yt);
xlabel("x,cm")
ylabel("y,cm")
title({'Von Mises Stress'; ...
3-142
Axisymmetric Thermal and Structural Analysis of Disc Brake
References
[1] Adamowicz, Adam. "Axisymmetric FE Model to Analysis of Thermal Stresses in a Brake Disc."
Journal of Theoretical and Applied Mechanics 53, issue 2 (April 2015): 357–370. https://doi.org/
10.15632/jtam-pl.53.2.357.
3-143
3 Solving PDEs
Find the temperature distribution on a square plate made of orthotropic material. A laser beam hits
the middle of the plate and generates a heat flux. This example shows how to
• Specify an orthotropic thermal conductivity that also depends on the temperature using a
conductivity matrix and a function handle.
• Define a heat flux pulse of a Gaussian shape using a function handle. The example shows a
function modeling a beam with the steady amplitude that is switched off after a particular time, as
well as a function modeling the beam with its amplitude gradually decaying over time.
L = 0.4; % m
W = 0.4; % m
H = 0.03; % m
g = multicuboid(L,W,H);
figure
pdegplot(g,FaceLabels="on",FaceAlpha=0.3)
Create a finite element analysis model with the plate geometry for transient thermal analysis.
model = femodel(AnalysisType="thermalTransient",Geometry=g);
3-144
Heat Transfer in Orthotropic Material Plate due to Laser Beam
Generate a mesh.
model = generateMesh(model);
Specify the heat flux boundary condition on top of the plate. First, specify a heat flux as a short pulse
created by the laser beam by using the heatFluxSteady function. See Heat Flux Functions on page
3-152.
model.FaceLoad(2) = faceLoad(Heat = @heatFluxSteady);
3-145
3 Solving PDEs
First, assume that the plate is made of an isotropic material with the thermal conductivity 50
W /(m ⋅ K).
K = 50;
Specify the material properties. The mass density of the plate is 1960 kg/m3, and the specific heat is
710 J/(kg ⋅ K).
model.MaterialProperties = ...
materialProperties(ThermalConductivity=K, ...
MassDensity=1960, ...
SpecificHeat=710);
Solve the thermal problem for the times between 0 and 2 seconds.
t = 0:0.1:2;
Rt_iso = solve(model,t);
Plot the results using the Visualize PDE Results Live Editor task. First, create a new live script by
clicking the New Live Script button in the File section on the Home tab.
On the Live Editor tab, select Task > Visualize PDE Results. This action inserts the task into your
script.
1 In the Select results section of the task, select Rt_iso from the drop-down list.
2 In the Specify data parameters section of the task, set Type to Temperature.
3 Select the Animate checkbox to see how the temperature changes over time.
3-146
Heat Transfer in Orthotropic Material Plate due to Laser Beam
For orthotropic thermal conductivity, create a vector of thermal conductivity components kx,ky, and
kz.
kx = 50; % W/(m*K)
ky = 50; % W/(m*K)
3-147
3 Solving PDEs
kz = 500; % W/(m*K)
K = [kx;ky;kz];
model.MaterialProperties = ...
materialProperties(ThermalConductivity=K, ... % W/(m*K)
MassDensity=1960, ... % kg/(m^3)
SpecificHeat=710); % J/(kg*K)
Rt_ortho = solve(model,t);
Plot the results using the Visualize PDE Results Live Editor task.
1 In the Select results section of the task, select Rt_ortho from the drop-down list.
2 In the Specify data parameters section of the task, set Type to Temperature.
3 Select the Animate checkbox to see how the temperature changes over time.
3-148
Heat Transfer in Orthotropic Material Plate due to Laser Beam
For orthotropic thermal conductivity that also depends on temperature, create a vector of thermal
conductivity components kx,ky, and kz and use it in a function handle to account for temperature
dependency.
kx = 50; % W/(m*K)
ky = 50; % W/(m*K)
kz = 500; % W/(m*K)
K = @(location,state) [kx;ky;kz] - 0.005*state.u;
model.MaterialProperties = ...
materialProperties(ThermalConductivity=K, ... % W/(m*K)
MassDensity=1960, ... % kg/(m^3)
SpecificHeat=710); % J/(kg*K)
Rt_ortho_t = solve(model,t);
Plot the results using the Visualize PDE Results Live Editor task.
1 In the Select results section of the task, select Rt_ortho_t from the drop-down list.
2 In the Specify data parameters section of the task, set Type to Temperature.
3-149
3 Solving PDEs
3 Select the Animate checkbox to see how the temperature changes over time.
Now specify a heat flux as a pulse with the amplitude gradually decaying over time by using the
heatFluxTimeDependent function. See Heat Flux Functions on page 3-152.
3-150
Heat Transfer in Orthotropic Material Plate due to Laser Beam
Visualize the heat flux for all time steps by creating an animation. Keep a fixed vertical scale by
scaling all plots to use the maximum amplitude 350000000W /m2 as a colorbar upper limit.
state.time = t;
flux = heatFluxTimeDependent(location,state);
figure
for index = 1:length(t)
contourf(x,y,flux(:,:,index),100,LineStyle="none")
colorbar
clim([0 350000000])
xlabel("x")
ylabel("y")
M(index) = getframe;
end
Rt = solve(model,t);
Plot the results using the Visualize PDE Results Live Editor task.
1 In the Select results section of the task, select Rt from the drop-down list.
2 In the Specify data parameters section of the task, set Type to Temperature.
3 Select the Animate checkbox to see how the temperature changes over time.
3-151
3 Solving PDEs
Create a function representing a Gaussian heat flux with the center at (x0,y0) and the maximum
amplitude 350000000W /m2. The heat flux has a steady amplitude for 0.03 seconds, then it switches
off.
3-152
Heat Transfer in Orthotropic Material Plate due to Laser Beam
x0 = 0;
y0 = 0;
sx = 0.1; % standard deviation along x
sy = 0.05; % standard deviation along y
Create a function representing a Gaussian heat flux with the center at (x0,y0) and with the amplitude
350000000W /m2 amplitude gradually decaying over time.
3-153
3 Solving PDEs
This example shows a quasistatic axisymmetric thermal stress analysis workflow by reproducing the
results of the simplified disc brake model discussed in [1] on page 3-165. Disc brakes absorb
mechanical energy through friction and transform it into thermal energy, which then dissipates. The
example uses a simplified model of a disc brake in a single braking process from a constant initial
angular speed to a standstill. The workflow has two steps:
1 Transient thermal analysis to compute the temperature distribution in the disc using the heat
flux from brake pads
2 Quasistatic structural analysis to compute thermal stresses at several solution times using
previously obtained temperature distribution to specify thermal loads
The resulting plots show the temperature distribution, radial stress, hoop stress, and von Mises stress
for the corresponding solution times.
Based on the assumptions used in [1] on page 3-165, the example reduces the analysis domain to a
rectangular region corresponding to the axisymmetric section of the annular disc. Because of the
geometric and load symmetry of the disc, the example models only half the thickness of the disc and
the effect of one pad. In the following figure, the left edge corresponds to the inner radius of the disc
rd. The right edge corresponds to the outer radius of the disc Rd and also coincides with the outer
radius of the pad Rp. The disc experiences pressure from the pad, which generates the heat flux.
Instead of modeling the pad explicitly, include its effect in the thermal analysis by specifying this heat
flux as a boundary condition from the inner radius of the pad rp to the outer radius of the pad Rp.
Create a geometry with two adjacent rectangles. The top edge of the longer rectangle (on the right)
represents the disc-pad contact region.
R1 = [3,4, [ 66, 76.5, 76.5, 66, -5.5, -5.5, 0, 0]/1000]';
R2 = [3,4, [76.5, 113.5, 113.5, 76.5, -5.5, -5.5, 0, 0]/1000]';
3-154
Thermal and Structural Analysis of Disc Brake
figure
pdegplot(g,EdgeLabels="on",FaceLabels="on");
Create a finite element analysis model with the disc brake geometry for transient axisymmetric
thermal analysis.
model = femodel(AnalysisType="thermalTransient",Geometry=g);
model.PlanarType = "axisymmetric";
model.Geometry = geometryFromEdges(g);
Generate a mesh. To match the mesh used in [1] on page 3-165, use the linear geometric order
instead of the default quadratic order.
3-155
3 Solving PDEs
Specify the heat flux boundary condition to account for the pad region. For the definition of the qFcn
function, see Heat Flux Function on page 3-163.
model.EdgeLoad(6) = edgeLoad(Heat=@qFcn);
model.FaceIC=faceIC(Temperature=20);
Solve the model for the times used in [1] on page 3-165.
Plot the temperature variation with time at three key radial locations. The resulting plot is
comparable to the plot obtained in [1] on page 3-165.
iTRd = interpolateTemperature(Rt,[0.1135;0],1:numel(Rt.SolutionTimes));
iTrp = interpolateTemperature(Rt,[0.0765;0],1:numel(Rt.SolutionTimes));
iTrd = interpolateTemperature(Rt,[0.066;0],1:numel(Rt.SolutionTimes));
figure
plot(tlist,iTRd)
hold on
plot(tlist,iTrp)
plot(tlist,iTrd)
title("Temperature Variation with Time at Key Radial Locations")
legend("R_d","r_p","r_d")
xlabel("t, s")
ylabel("T,^{\circ}C")
3-156
Thermal and Structural Analysis of Disc Brake
Switch the analysis type for the femodel object to static structural.
model.AnalysisType = "structuralStatic";
Specify the reference temperature that corresponds to the state of zero thermal stress of the model.
model.ReferenceTemperature = 20;
Specify the thermal load by using the transient thermal results Rt. The solution times are the same as
in the thermal model analysis. For each solution time, solve the corresponding static structural
analysis problem and plot the temperature distribution, radial stress, hoop stress, and von Mises
stress. For the definition of the plotResults function, see Plot Results Function on page 3-164. The
results are comparable to figure 5 from [1] on page 3-165.
for n = 2:numel(Rt.SolutionTimes)
Rt_step = filterByIndex(Rt,n);
3-157
3 Solving PDEs
model.FaceLoad = faceLoad(Temperature=Rt_step);
R = solve(model);
plotResults(R,Rt,n);
end
3-158
Thermal and Structural Analysis of Disc Brake
3-159
3 Solving PDEs
3-160
Thermal and Structural Analysis of Disc Brake
3-161
3 Solving PDEs
3-162
Thermal and Structural Analysis of Disc Brake
This helper function computes the transient value of the heat flux from the pad to the disc. It uses the
empirical formula from [1] on page 3-165.
function q = qFcn(x,s)
alphad = 1.44E-5; % Diffusivity of disc
Kd = 51; % Conductivity of disc
rhod = 7100; % Density of disc
cpd = Kd/rhod/alphad; % Specific heat capacity of disc
3-163
3 Solving PDEs
This helper function plots the temperature distribution, radial stress, hoop stress, and von Mises
stress.
function plotResults(R,Rt,tID)
figure
subplot(2,2,1)
pdeplot(Rt.Mesh,XYData=Rt.Temperature(:,tID), ...
ColorMap="jet",Contour="on")
xt = xticks;
yt = yticks;
xticklabels(100*xt);
yticklabels(100*yt);
xlabel("x,cm")
ylabel("y,cm")
title({'Temperature'; ...
['max = ' num2str(max(Rt.Temperature(:,tID))) '^{\circ}C']}, ...
FontSize=10)
subplot(2,2,2)
pdeplot(R.Mesh,XYData=R.Stress.srr, ...
ColorMap="jet",Contour="on")
xt = xticks;
yt = yticks;
xticklabels(100*xt);
yticklabels(100*yt);
xlabel("x,cm")
ylabel("y,cm")
title({'Radial Stress'; ...
['min = ' num2str(min(R.Stress.srr)/1E6,'%3.2f') ' MPa'];
['max = ' num2str(max(R.Stress.srr)/1E6,'%3.2f') ' MPa']}, ...
FontSize=10)
subplot(2,2,3)
pdeplot(R.Mesh,XYData=R.Stress.sh, ...
ColorMap="jet",Contour="on")
xt = xticks;
yt = yticks;
xticklabels(100*xt);
yticklabels(100*yt);
xlabel("x,cm")
ylabel("y,cm")
title({'Hoop Stress'; ...
['min = ' num2str(min(R.Stress.sh)/1E6,'%3.2f') ' MPa'];
['max = ' num2str(max(R.Stress.sh)/1E6,'%3.2f') ' MPa']}, ...
FontSize=10)
subplot(2,2,4)
pdeplot(R.Mesh,XYData=R.VonMisesStress, ...
ColorMap="jet",Contour="on")
xt = xticks;
yt = yticks;
xticklabels(100*xt);
yticklabels(100*yt);
xlabel("x,cm")
ylabel("y,cm")
title({'Von Mises Stress'; ...
3-164
Thermal and Structural Analysis of Disc Brake
References
[1] Adamowicz, Adam. "Axisymmetric FE Model to Analysis of Thermal Stresses in a Brake Disc."
Journal of Theoretical and Applied Mechanics 53, issue 2 (April 2015): 357–370. https://doi.org/
10.15632/jtam-pl.53.2.357.
3-165
3 Solving PDEs
Here, ρ is the space charge density, and ε is the absolute dielectric permittivity of the material. The
toolbox uses the relative permittivity of the material εr, such that ε = εrε0, where ε0 is the absolute
permittivity of the vacuum. The relative permittivity for air is 1.00059. Note that the permittivity of
the air does not affect the result in this example as long as the coefficient is constant.
Assuming that there is no charge in the domain, Poisson's equation simplifies to the Laplace equation:
ΔV = 0. For this example, use these boundary conditions:
Create a finite element analysis model for electrostatic analysis. Include a geometry of a frame.
model = femodel(AnalysisType="electrostatic", ...
Geometry="Frame.STL");
3-166
Electrostatic Potential in Air-Filled Frame
model.VacuumPermittivity = 8.8541878128e-12;
model.MaterialProperties = ...
materialProperties(RelativePermittivity=1.00059);
Generate the mesh. This assignment updates the mesh stored in the Geometry property of the
model.
model = generateMesh(model);
Solve the model. Plot the electric potential distribution using the Contour parameter to display
equipotential lines.
R = solve(model);
u = R.ElectricPotential;
pdeplot(model.Mesh,XYData=u,Contour="on")
3-167
3 Solving PDEs
This example shows how to find the electrostatic potential in an air-filled annular quadrilateral frame.
− ∇ ⋅ ε ∇V = ρ .
Here, ρ is the space charge density, and ε is the absolute dielectric permittivity of the material. The
toolbox uses the relative permittivity of the material εr , such that ε = εr ε0, where ε0 is the absolute
permittivity of the vacuum. The relative permittivity for air is 1.00059. Note that the permittivity of
the air does not affect the result in this example as long as the coefficient is constant.
Assuming that there is no charge in the domain, the Poisson equation simplifies to the Laplace
equation: ΔV = 0 . For this example, use the following boundary conditions:
emagmodel = createpde("electromagnetic","electrostatic");
importGeometry(emagmodel,"Frame.STL");
pdegplot(emagmodel,"EdgeLabels","on")
3-168
Electrostatic Potential in Air-Filled Frame
emagmodel.VacuumPermittivity = 8.8541878128E-12;
electromagneticProperties(emagmodel,"RelativePermittivity",1.00059);
electromagneticBC(emagmodel,"Voltage",1000,"Edge",[1 2 4 6]);
electromagneticBC(emagmodel,"Voltage",0,"Edge",[3 5 7 8]);
generateMesh(emagmodel);
Solve the model. Plot the electric potential using the Contour parameter to display equipotential
lines.
R = solve(emagmodel);
u = R.ElectricPotential;
pdeplot(emagmodel,"XYData",u,"Contour","on")
3-169
3 Solving PDEs
3-170
Electrostatic Potential in Air-Filled Frame: PDE Modeler App
–∇ · (ε∇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:
• 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 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.
3-171
3 Solving PDEs
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-172
Electrostatic Analysis of Transformer Bushing Insulator
This example shows how to compute the electric field intensity in a bushing insulator of a
transformer. Bushing insulators must withstand large electric fields due to the potential difference
between the ground and the high-voltage conductor. This example uses a 3-D electrostatic model to
compute the voltage distribution and electric field intensity in the bushing.
3-173
3 Solving PDEs
model = createpde("electromagnetic","electrostatic");
gmBushing = importGeometry("TransformerBushing.stl");
pdegplot(gmBushing)
Model the surrounding air as a cuboid, and position the cuboid to contain the bushing at its center.
gmAir = multicuboid(1,0.4,0.4);
gmAir.translate([0.25,0.125,-0.07]);
gmModel = addCell(gmAir,gmBushing);
pdegplot(gmModel,"CellLabels","on","FaceAlpha",0.25)
3-174
Electrostatic Analysis of Transformer Bushing Insulator
model.Geometry = gmModel;
model.VacuumPermittivity = 8.8541878128E-12;
electromagneticProperties(model,"Cell",1,"RelativePermittivity",1);
electromagneticProperties(model,"Cell",2,"RelativePermittivity",5);
Before specifying boundary conditions, identify the face IDs by plotting the geometry with the face
labels. To see the IDs more clearly, rotate the geometry.
pdegplot(gmModel,"FaceLabels","on","FaceAlpha",0.2)
view([55 5])
3-175
3 Solving PDEs
Specify the voltage boundary condition on the inner walls of the bushing exposed to conductor.
electromagneticBC(model,"Face",12,"Voltage",10E3);
Specify the grounding boundary condition on the surface in contact with the oil tank.
electromagneticBC(model,"Face",9,"Voltage",0);
generateMesh(model);
R = solve(model)
R =
ElectrostaticResults with properties:
elemsBushing = findElements(model.Mesh,"Region","Cell",2);
pdeplot3D(model.Mesh.Nodes, ...
model.Mesh.Elements(:,elemsBushing), ...
"ColorMapData",R.ElectricPotential);
3-176
Electrostatic Analysis of Transformer Bushing Insulator
3-177
3 Solving PDEs
3-178
Magnetic Flux Density in H-Shaped Magnet
This example shows how to solve a 2-D magnetostatic model for a ferromagnetic frame with an H-
shaped cavity. This setup generates a uniform magnetic field due to the presence of two coils.
Create a geometry that consists of a rectangular frame with an H-shaped cavity, four rectangles
representing the two coils, and a unit square representing the air domain around the magnet. Specify
all dimensions in millimeters, and use the value convfactor = 1000 to convert the dimensions to
meters.
convfactor = 1000;
RS = [3;4;[-525;525;525;-525;-500;-500;500;500]/convfactor];
zeroPad = zeros(numel(RH)-numel(RS),1);
RS = [RS;zeroPad];
RC1 = [3;4;[150;250;250;150;120;120;350;350]/convfactor;
zeroPad];
RC2 = [3;4;[-150;-250;-250;-150;120;120;350;350]/convfactor;
zeroPad];
RC3 = [3;4;[150;250;250;150;-120;-120;-350;-350]/convfactor;
zeroPad];
RC4 = [3;4;[-150;-250;-250;-150;-120;-120;-350;-350]/convfactor;
zeroPad];
Create the geometry to model the air domain around the magnet.
RD = [3;4;[-1000;1000;1000;-1000;-1000; ...
-1000;1000;1000]/convfactor;zeroPad];
gd = [RS,RH,RC1,RC2,RC3,RC4,RD];
ns = char('RS','RH','RC1','RC2','RC3','RC4','RD');
g = decsg(gd,'(RS+RH+RC1+RC2+RC3+RC4)+RD',ns');
figure
pdegplot(g,"FaceLabels","on")
3-179
3 Solving PDEs
figure
pdegplot(g,"EdgeLabels","on")
3-180
Magnetic Flux Density in H-Shaped Magnet
model = createpde("electromagnetic","magnetostatic");
geometryFromEdges(model,g);
generateMesh(model,"Hface",{2,0.01},"Hmax",0.1,"Hgrad",2);
figure
pdemesh(model)
3-181
3 Solving PDEs
model.VacuumPermeability = 1.25663706212e-6;
electromagneticProperties(model,"RelativePermeability",1);
Now specify the large constant relative permeability of the ferromagnetic frame.
electromagneticProperties(model,"RelativePermeability",10000,"Face",2);
Specify the current density values on the upper and lower coils.
electromagneticSource(model,"CurrentDensity",1E6,"Face",[5,6]);
electromagneticSource(model,"CurrentDensity",-1E6,"Face",[4,7]);
Specify that the magnetic potential on the outer surface of the air domain is 0.
electromagneticBC(model,"Edge",[5,6,13,14],"MagneticPotential",0);
R = solve(model)
R =
MagnetostaticResults with properties:
3-182
Magnetic Flux Density in H-Shaped Magnet
pdeplot(model,"XYData",Bmag, ...
"FlowData",[R.MagneticFluxDensity.Bx ...
R.MagneticFluxDensity.By])
References
[1] Kozlowski, A., R. Rygal, and S. Zurek. "Large DC electromagnet for semi-industrial
thermomagnetic processing of nanocrystalline ribbon." IEEE Transactions on Magnetics 50, issue 4
(April 2014): 1-4. https://ieeexplore.ieee.org/document/6798057.
3-183
3 Solving PDEs
This example shows how to solve a 3-D magnetostatic problem for a solenoid with a finite length iron
core. Using a ferromagnetic core with high permeability, such as an iron core, inside a solenoid
increases magnetic field and flux density. In this example, you find the magnetic flux density for a
geometry consisting of a coil with a finite length core in a cylindrical air domain.
The first part of the example solves the magnetostatic problem using a 3-D model. The second part
solves the same problem using an axisymmetric 2-D model to speed up computations.
Create geometries consisting of three cylinders: a solid circular cylinder models the core, an annular
circular cylinder models the coil, and a larger circular cylinder models the air around the coil.
3-184
Magnetic Flux Density in Electromagnet
coreGm = multicylinder(0.03,0.1);
coilGm = multicylinder([0.05 0.07],0.2,"Void",[1 0]);
airGm = multicylinder(1,2);
Position the core and coil so that the finite length core is located near the top of coil.
gm = addCell(airGm,coreGm);
gm = addCell(gm,coilGm);
pdegplot(gm,"FaceAlpha",0.2,"CellLabels","on")
figure
pdegplot(gm,"FaceAlpha",0.2,"CellLabels","on")
axis([-0.1 0.1 -0.1 0.1 0.8 1.2])
3-185
3 Solving PDEs
model3D = createpde("electromagnetic","magnetostatic");
model3D.Geometry = gm;
model3D.VacuumPermeability = 1.2566370614E-6;
electromagneticProperties(model3D,"RelativePermeability",1);
electromagneticProperties(model3D,"RelativePermeability",10000, ...
"Cell",2);
Assign an excitation current using a function that defines counterclockwise current density in the
coil.
electromagneticSource(model3D,"CurrentDensity",@windingCurrent3D, ...
"Cell",3);
Specify that the magnetic potential on the outer surface of the air domain is 0.
electromagneticBC(model3D,"MagneticPotential",[0;0;0],"Face",1:3);
3-186
Magnetic Flux Density in Electromagnet
Generate a mesh where only the core and coil regions are well refined and the air domain is relatively
coarse to limit the size of the problem.
internalFaces = cellFaces(model3D.Geometry,2:3);
generateMesh(model3D,"Hface",{internalFaces,0.007});
R = solve(model3D)
R =
MagnetostaticResults with properties:
Find the mesh elements belonging to the core and the coil.
Plot the magnitude of the flux density on the core and coil.
pdeplot3D(model3D.Mesh.Nodes, ...
model3D.Mesh.Elements(:,coreAndCoilElem), ...
"ColorMapData",Bmag)
axis([-0.1 0.1 -0.1 0.1 0.8 1.2])
3-187
3 Solving PDEs
Interpolate the flux to a grid covering the portion of the geometry near the core.
x = -0.05:0.01:0.05;
z = 1.02:0.01:1.14;
y = x;
[X,Y,Z] = meshgrid(x,y,z);
intrpBcore = R.interpolateMagneticFlux(X,Y,Z);
Reshape intrpBcore.Bx, intrpBcore.By, and intrpBcore.Bz and plot the magnetic flux density
as a vector plot.
Bx = reshape(intrpBcore.Bx,size(X));
By = reshape(intrpBcore.By,size(Y));
Bz = reshape(intrpBcore.Bz,size(Z));
quiver3(X,Y,Z,Bx,By,Bz,"Color","r")
hold on
pdegplot(coreGm,"FaceAlpha",0.2);
3-188
Magnetic Flux Density in Electromagnet
Now, simplify this 3-D problem to 2-D using the symmetry around the axis of rotation.
First, create the geometry. The axisymmetric section consists of two small rectangular regions (the
core and coil) located within a large rectangular region (air).
R1 = [3,4,0.0,1,1,0.0,0,0,2,2]';
R2 = [3,4,0,0.03,0.03,0,1.025,1.025,1.125,1.125]';
R3 = [3,4,0.05,0.07,0.07,0.05,0.90,0.90,1.10,1.10]';
ns = char('R1','R2','R3');
sf = 'R1+R2+R3';
gdm = [R1, R2, R3];
g = decsg(gdm,sf,ns');
pdegplot(g,'FaceLabels','on')
3-189
3 Solving PDEs
figure
pdegplot(g,'FaceLabels','on')
axis([0 0.1 0.8 1.2])
3-190
Magnetic Flux Density in Electromagnet
Create an electromagnetic model for axisymmetric magnetostatic analysis and assign the geometry.
model2D = createpde('electromagnetic','magnetostatic-axisymmetric');
geometryFromEdges(model2D,g);
Specify the current density in the coil. For an axisymmetric model, use the constant current value.
electromagneticSource(model2D,'CurrentDensity',5E6,'Face',2);
Assign zero magnetic potential on the outer edges of the air domain as the boundary condition.
electromagneticBC(model2D,'MagneticPotential',0,'Edge',[2 8]);
Generate a mesh.
generateMesh(model2D,'Hmin',0.0004,'Hgrad',2,'Hmax',0.008);
3-191
3 Solving PDEs
R = solve(model2D);
Plot the magnitude of the flux density on the core and coil.
pdeplot(model2D,'XYData',Bmag)
xlim([0,0.05]);
ylim([1.0,1.14])
Interpolate the flux to a grid covering the portion of the geometry near the core.
x = 0:0.01:0.05;
y = 1.02:0.01:1.14;
[X,Y] = meshgrid(x,y);
intrpBcore = R.interpolateMagneticFlux(X,Y);
Reshape intrpBcore.Bx and intrpBcore.By and plot the magnetic flux density as a vector plot.
Bx = reshape(intrpBcore.Bx,size(X));
By = reshape(intrpBcore.By,size(Y));
quiver(X,Y,Bx,By,'Color','r')
3-192
Magnetic Flux Density in Electromagnet
hold on
pdegplot(model2D);
xlim([0,0.07]);
ylim([1.0,1.14])
References
[1] Thierry Lubin, Kévin Berger, Abderrezak Rezzoug. "Inductance and Force Calculation for
Axisymmetric Coil Systems Including an Iron Core of Finite Length." Progress In Electromagnetics
Research B, EMW Publishing 41 (2012): 377-396. https://hal.science/hal-00711310.
3-193
3 Solving PDEs
In this section...
“Summary of the Equations of Linear Elasticity” on page 3-194
“3D Linear Elasticity Problem” on page 3-195
“Plane Stress” on page 3-197
“Plane Strain” on page 3-198
“Axisymmetric Analysis” on page 3-198
σ = stress
f = body force
ε = strain
u = displacement
−∇ · σ = f
1
ε= ∇u + ∇uT
2
σi j = σ ji
The Voigt notation for the constitutive equation of the linear isotropic model is
The expanded form uses all the entries in σ and ε takes symmetry into account.
3-194
Linear Elasticity Equations
σ11 ε11
1−ν 0 0 0 ν 0 0 0 ν
σ12 ε12
• 1 − 2ν 0 0 0 0 0 0 0
σ13 • • 1 − 2ν 0 0 0 0 0 0 ε13
σ21 • • • 1 − 2ν 0 0 0 0 0 ε21
E
σ22 = • • • • 1−ν 0 0 0 ν ε22 (3-1)
1 + ν 1 − 2ν
σ23 • • • • • 1 − 2ν 0 0 0 ε23
σ31 • • • • • • 1 − 2ν 0 0 ε31
σ32 • • • • • • • 1 − 2ν 0 ε32
• • • • • • • • 1−ν
σ33 ε33
− ∇ · c ⊗ ∇u = f
But the equations in the summary do not have ∇u alone, it appears together with its transpose:
1
ε= ∇u + ∇uT
2
It is a straightforward exercise to convert this equation for strain ε to ∇u. In column vector form,
∂ux / ∂x
∂ux / ∂y
∂ux / ∂z
∂uy / ∂x
∇u = ∂uy / ∂y
∂uy / ∂z
∂uz / ∂x
∂uz / ∂y
∂uz / ∂z
3-195
3 Solving PDEs
1 0 0 0 0 0 0 0 0
1 1
0 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 1 0 0 0 0 ∇u ≡ A ∇u
1 1
0 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
1−ν 0 0 0 ν 0 0 0 ν
• 1 − 2ν 0 0 0 0 0 0 0
• • 1 − 2ν 0 0 0 0 0 0
• • • 1 − 2ν 0 0 0 0 0
E
σ= • • • • 1−ν 0 0 0 ν A ∇u
1 + ν 1 − 2ν
• • • • • 1 − 2ν 0 0 0
• • • • • • 1 − 2ν 0 0
• • • • • • • 1 − 2ν 0
• • • • • • • • 1−ν
1−ν 0 0 0 ν 0 0 0 ν
0 1/2 − ν 0 1/2 − ν 0 0 0 0 0
0 0 1/2 − ν 0 0 0 1/2 − ν 0 0
0 1/2 − ν 0 1/2 − ν 0 0 0 0 0
E
= ν 0 0 0 1−ν 0 0 0 ν ∇u
1 + ν 1 − 2ν
0 0 0 0 0 1/2 − ν 0 1/2 − ν 0
0 0 1/2 − ν 0 0 0 1/2 − ν 0 0
0 0 0 0 0 1/2 − ν 0 1/2 − ν 0
ν 0 0 0 ν 0 0 0 1−ν
Make the definitions
3-196
Linear Elasticity Equations
E
μ=
2(1 + ν)
Eν
λ=
(1 + ν)(1 − 2ν)
E(1 − ν)
= 2μ + λ
(1 + ν)(1 − 2ν)
2μ + λ 0 0 0 λ 0 0 0 λ
0 μ 0 μ 0 0 0 0 0
0 0 μ 0 0 0 μ 0 0
0 μ 0 μ 0 0 0 0 0
σ= λ 0 0 0 2μ + λ 0 0 0 λ ∇u ≡ c ∇u
0 0 0 0 0 μ 0 μ 0
0 0 μ 0 0 0 μ 0 0
0 0 0 0 0 μ 0 μ 0
λ 0 0 0 λ 0 0 0 2μ + λ
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 StationaryResults.
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:
ε11 1 −ν 0 σ11
1
ε22 = −ν 1 0 σ22
E
2ε12 0 0 2 + 2ν σ12
σ11 1 ν 0 ε11
E ν 1 0
σ22 = ε22
1 − ν2 1−ν
σ12 0 0 2ε12
2
1 0 0 0
1 1
0 0
2 2
ε= ∇u ≡ A ∇u
1 1
0 0
2 2
0 0 0 1
3-197
3 Solving PDEs
E Eν
0 0
1 − ν2 1 − ν2 2μ μ + λ 2λμ
σ11 0 0
E E 2μ + λ 2μ + λ
σ12 0 0
2 1+ν 2 1+ν 0 μ μ 0
= ∇u = ∇u
σ21 E E 0 μμ 0
0 0
σ22 2 1+ν 2 1+ν 2λμ 2μ μ + λ
0 0
Eν E 2μ + λ 2μ + λ
0 0
1 − ν2 1 − ν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:
1 0 0 0
1 1
0 0
2 2
ε= ∇u ≡ A ∇u
1 1
0 0
2 2
0 0 0 1
E 1−ν Eν
0 0
1 + ν 1 − 2ν 1 + ν 1 − 2ν
σ11 2μ + λ 0 0 λ
E E
σ12 0 0
2 1+ν 2 1+ν 0 μμ 0
= ∇u = ∇u
σ21 E E 0 μ μ 0
0 0
σ22 2 1+ν 2 1+ν λ 0 0 2μ + λ
Eν E 1−ν
0 0
1 + ν 1 − 2ν 1 + ν 1 − 2ν
Axisymmetric Analysis
Axisymmetric analysis speeds up simulations by simplifying 3-D solids using their symmetry around
the axis of rotation and analyzing only the 2-D axisymmetric section. Use polar coordinates r,θ,z for
radial, circumferential, and axial directions. If z is the axis of rotation, the symmetry around the z-axis
3-198
Linear Elasticity Equations
means that the stress components are independent of the θ coordinate. The stress equilibrium
equations for an axisymmetric structural mechanics are as follows:
∂σrr ∂σrz 1
+ + σrr − σθθ + f r = 0
∂r ∂z r
∂τrz ∂σzz τrz
+ + + fz = 0
∂r ∂z r
τ is the shear stress, and γ is the shear strain. Assuming isotropic conditions, the stress-strain
relation can be written as follows:
σr 1−ν ν 0 0 εr
σz ν 1−ν 0 0 εz
E
= 0 0 1−ν 0
σθ 1 + ν 1 − 2ν εθ
1 − 2ν
τrz 0 0 0 γrz
2
3-199
3 Solving PDEs
• Two ferromagnetic pieces: the stator and the rotor, made of transformer steel
• The air gap between the stator and the rotor
• The armature copper coil carrying the DC current
The magnetic permeability of air and of copper are both close to the magnetic permeability of a
vacuum, μ = μ0. The magnetic permeability of the stator and the rotor is μ = 5000μ0. 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 the y-
axis and antisymmetric with respect to the x-axis. Therefore, you can limit the domain to x ≥ 0, y ≥ 0,
with the default boundary condition
1
n⋅ ∇A = 0
μ
on the x-axis and the boundary condition A = 0 on the y-axis. Because the field outside the motor is
negligible, you can use the boundary condition A = 0 on the exterior boundary.
First, create the geometry in the PDE Modeler app. The geometry of this electric motor is a union of
five circles and two rectangles. To draw the geometry, enter the following commands in the MATLAB
Command Window:
3-200
Magnetic Field in Two-Pole Electric Motor
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')
Reduce the geometry to the first quadrant by intersecting it with a square. To do this, enter
(C1+C2+C3+C4+C5+R1+R2)*SQ1 in the Set formula field.
From the PDE Modeler app, export the geometry description matrix, set formula, and name-space
matrix to the MATLAB workspace by selecting Export Geometry Description, Set Formula,
Labels... from the Draw menu.
In the MATLAB Command Window, use the decsg function to decompose the exported geometry into
minimal regions. This command creates an AnalyticGeometry object d1. Plot the geometry d1.
[d1,bt1] = decsg(gd,sf,ns);
pdegplot(d1,"EdgeLabels","on","FaceLabels","on")
Remove unnecessary edges using the csgdel function. Specify the edges to delete as a vector of
edge IDs. Plot the resulting geometry.
3-201
3 Solving PDEs
Specify the relative permeability of the air gap and copper coil, which correspond to the faces 3 and 4
of the geometry.
electromagneticProperties(emagmodel,"RelativePermeability",1, ...
"Face",[3 4]);
Specify the relative permeability of the stator and the rotor, which correspond to the faces 1 and 2 of
the geometry.
electromagneticProperties(emagmodel,"RelativePermeability",5000, ...
"Face",[1 2]);
Apply the zero magnetic potential condition to all boundaries, except the edges along the x-axis. The
edges along the x-axis retain the default boundary condition.
3-202
Magnetic Field in Two-Pole Electric Motor
electromagneticBC(emagmodel,"MagneticPotential",0,...
"Edge",[16 9 10 11 12 13 14 15]);
generateMesh(emagmodel);
Solve the model and plot the magnetic potential. Use the Contour parameter to display equipotential
lines.
R = solve(emagmodel);
figure
pdeplot(emagmodel,"XYData",R.MagneticPotential,"Contour","on")
title "Magnetic Potential"
Add the magnetic field data to the plot. Use the FaceAlpha parameter to make the quiver plot for
magnetic field more visible.
figure
pdeplot(emagmodel,"XYData",R.MagneticPotential, ...
"FlowData",[R.MagneticField.Hx, ...
R.MagneticField.Hy], ...
"Contour","on", ...
"FaceAlpha",0.5)
title "Magnetic Potential and Field"
3-203
3 Solving PDEs
3-204
Magnetic Field in Two-Pole Electric Motor: PDE Modeler App
• 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
μmax
μ = μ0 2
+ μmin
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
μ
3-205
3 Solving PDEs
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')
4 Reduce the model to the first quadrant. To do this, enter (C1+C2+C3+C4+C5+R1+R2)*SQ1 in the
Set formula field.
3-206
Magnetic Field in Two-Pole Electric Motor: PDE Modeler App
5 Remove unnecessary subdomain borders. To do this, switch to the boundary mode by selecting
Boundary > Boundary Mode. Using Shift+click, select borders, and then select Boundary >
Remove Subdomain Border until the geometry consists of four subdomains: the rotor
(subdomain 1), the stator (subdomain 2), the air gap (subdomain 3), and the coil (subdomain 4).
The numbering of your subdomains can differ. If you do not see the numbers, select Boundary >
Show Subdomain Labels.
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 button on
the toolbar. Double-click each subdomain and specify the following coefficients:
3-207
3 Solving PDEs
10 Choose the nonlinear solver. To do this, select Solve > Parameters and check Use nonlinear
solver. Here, you also can adjust the tolerance parameter and choose to use the adaptive solver
together with the nonlinear solver.
11
Solve the PDE by selecting Solve > Solve PDE or clicking the button on the toolbar.
12 Plot the magnetic flux density B using arrows and the equipotential lines of the magnetostatic
potential A using a contour plot. To do this, select Plot > Parameters and choose the contour
and arrows plots in the resulting dialog box. Select Plot in x-y grid.
13 Using Options > Axes Limits, adjust the axes limits as needed. For example, use the Auto
check box.
The plot shows that the magnetic flux is parallel to the equipotential lines of the magnetostatic
potential.
3-208
Helmholtz Equation on Disk with Square Hole
This example shows how to solve a Helmholtz equation using the general PDEModel container and
the solvepde function. For the electromagnetic workflow that uses ElectromagneticModel and
familiar domain-specific language, see “Scattering Problem” on page 3-271.
Solve a simple scattering problem, where you compute the waves reflected by a square object
illuminated by incident waves that are coming from the left. For this problem, assume an infinite
horizontal membrane subjected to small vertical displacements U. The membrane is fixed at the
object boundary. The medium is homogeneous, and the phase velocity (propagation speed) of a wave,
α, is constant. The wave equation is
∂2 U
− α2 ▵ U = 0
∂t2
The solution U is the sum of the incident wave V and the reflected wave R:
U=V+R
When the illumination is harmonic in time, you can compute the field by solving a single steady
problem. Assume that the incident wave is a plane wave traveling in the -x direction:
The reflected wave can be decomposed into spatial and time components:
R x, y, t = r x, y e−iωt
Now you can rewrite the wave equation as the Helmholtz equation for the spatial component of the
reflected wave with the wave number k = ω/α:
2
−Δr − k r = 0
The Dirichlet boundary condition for the boundary of the object is U = 0, or in terms of the incident
and reflected waves, R = -V. For the time-harmonic solution and the incident wave traveling in the -x
direction, you can write this boundary condition as follows:
r x, y = − e−ikx
The reflected wave R travels outward from the object. The condition at the outer computational
boundary must allow waves to pass without reflection. Such conditions are usually called
nonreflecting. As x approaches infinity, R approximately satisfies the one-way wave equation
∂R
∂t
+ α ξ ⋅ ∇R = 0
This equation considers only the waves moving in the positive ξ-direction. Here, ξ is the radial
distance from the object. With the time-harmonic solution, this equation turns into the generalized
Neumann boundary condition
ξ ⋅ ∇r − ikr = 0
3-209
3 Solving PDEs
To solve the scattering problem using the programmatic workflow, first create a PDE model with a
single dependent variable.
numberOfPDE = 1;
model = createpde(numberOfPDE);
• g: A geometry specification function. For more information, see the documentation section
“Parametrized Function for 2-D Geometry Creation” on page 2-23 and the code for scatterg.m.
• k, c, a, f: The coefficients and inhomogeneous term.
g = @scatterg;
k = 60;
c = 1;
a = -k^2;
f = 0;
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")
ylim([0,1])
3-210
Helmholtz Equation on Disk with Square Hole
specifyCoefficients(model,"m",0,"d",0,"c",c,"a",a,"f",f);
Generate a mesh.
generateMesh(model,"Hmax",0.02);
figure
pdemesh(model);
axis equal
3-211
3 Solving PDEs
Solve for the complex amplitude. The real part of vector u stores an approximation to a real value
solution of the Helmholtz equation.
result = solvepde(model);
u = result.NodalSolution;
figure
pdeplot(model,"XYData",real(u),"Mesh","off");
colormap(jet)
xlabel("x")
ylabel("y")
title("Real Value Solution of Helmholtz Equation")
3-212
Helmholtz Equation on Disk with Square Hole
Using the solution to the Helmholtz equation, create an animation showing the corresponding
solution to the time-dependent wave equation.
figure
m = 10;
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)
axis tight
ax = gca;
ax.DataAspectRatio = [1 1 1];
axis off
M(j) = getframe;
end
3-213
3 Solving PDEs
3-214
Electrostatics and Magnetostatics
∇ ⋅ D = ρ,
∇ ⋅ B = 0,
∂B
∇×E= − ,
∂t
∂D
∇×H= J+ .
∂t
Here, E and H are the electric and magnetic field intensities, D and B are the electric and magnetic
flux densities, and ρ and J are the electric charge and current densities.
Electrostatics
For electrostatic problems, Maxwell's equations simplify to this form:
∇ ⋅ D = ∇ ⋅ ε E = ρ,
∇ × E = 0,
Because the electric field E is the gradient of the electric potential V, E = − ∇V ., the first equation
yields this PDE:
− ∇ ⋅ ε ∇V = ρ .
For electrostatic problems, Dirichlet boundary conditions specify the electric potential V on the
boundary.
Magnetostatics
For magnetostatic problems, Maxwell's equations simplify to this form:
∇ ⋅ B = 0,
∂ εE
∇×H= J+ = J.
∂t
Because ∇ ⋅ B = 0, there exists a magnetic vector potential A, such that B = ∇ × A. For non-
ferromagnetic materials, B = μH, where µ is the magnetic permeability of the material. Therefore,
H = μ−1 ∇ × A,
∇ × μ−1 ∇ × A = J .
∇ × ∇ × A = ∇ ∇ ⋅ A − ∇2 A
and the Coulomb gauge ∇ · A = 0, simplify the equation for A in terms of J to this PDE:
− ∇2 A = − ∇ ⋅ ∇A = μJ .
3-215
3 Solving PDEs
For magnetostatic problems, Dirichlet boundary conditions specify the magnetic potential A on the
boundary.
B = μH + μ0M .
Here, μ = μ0μr , where μr is the relative magnetic permeability of the material, and μ0 is the vacuum
permeability.
1 1
H= B − M,
μ0μr μr
1 1
∇×H= ∇× × A − M = J.
μ0μr μr
1 1
∇× ∇×A = J+ ∇× M .
μr μ0 μr
3-216
DC Conduction
DC Conduction
Direct current electrical conduction problems, such as electrolysis and computation of resistances of
grounding plates, involve a steady current passing through a conductive medium. The current density
J is related to the electric field E as follows:
J = σE,
E = − ∇V .
∂ρ
∇⋅J= − = 0,
∂t
− ∇ ⋅ σ ∇V = 0.
For DC conduction problems, Dirichlet boundary conditions specify the electric potential V on the
boundary. The Neumann boundary conditions specify the surface current density, which is the value
of the normal component of the current density n ⋅ σ ∇V on a face for a 3-D geometry or an edge
for a 2-D geometry.
3-217
3 Solving PDEs
Harmonic Electromagnetics
Maxwell's equations describe electrodynamics as:
ε ∇ ⋅ E = ρ,
∇ ⋅ H = 0,
∂H
∇×E= −μ ,
∂t
∂E
∇×H= J+ε .
∂t
Here, E and H are the electric and magnetic fields, ε and µ are the electrical permittivity and
magnetic permeability of the material, and ρ and J are the electric charge and current densities.
The time-harmonic electric and magnetic fields can be represented using these formulas:
E = Eeiωt,
H = Heiωt .
Accounting for the electric conductivity of the material and the applied current separately, you can
represent the total electric current density as the sum of the current density σE due to the electric
field and the current density of the applied current: J = σE + Ja. Here, σ is the conductivity of the
material. For a time-harmonic problem, the applied current can be defined as:
Ja = J eiωt .
∂2 E ∂E ∂ Ja
− ∇ × μ−1 ∇ × E = ε +σ + .
∂t 2 ∂t ∂t
∂
For the time-harmonic electric field and applied current, the derivative = iω, and the resulting
∂t
equation is:
Given an incident electric field Ei and a scattered electric field Es, you can compute the total electric
field E. Due to linearity, it suffices to solve the equation for the scattered field with the boundary
condition for the scattered field along the scattering object determined by
n × Ei = − n × Es .
For the time-harmonic magnetic field and applied current, Maxwell's equations can be simplified
under the assumption of zero conductivity to this form:
For the time-harmonic magnetic field, it suffices to solve the equation for the scattered field with the
boundary condition for the scattered field along the scattering object determined by
3-218
Harmonic Electromagnetics
n × Hi = − n × Hs .
3-219
3 Solving PDEs
This example shows how to find the electric potential and the components of the current density
between two circular metallic conductors. Two metallic conductors are placed on a brine-soaked
blotting paper that serves as a plane, thin conductor. The physical model for this problem is DC
conduction. The boundary conditions are:
First, create a geometry consisting of a rectangle and two circles. Start by defining a rectangle and
two circles.
R1 = [3;4
-1.2;-1.2;1.2;1.2
-0.6;0.6;0.6;-0.6];
C1 = [1;-0.6;0;0.3];
C2 = [1;0.6;0;0.3];
Append extra zeros to the circles so they have the same number of rows as the rectangle.
C1 = [C1;zeros(length(R1) - length(C1),1)];
C2 = [C2;zeros(length(R1) - length(C2),1)];
gd = [R1,C1,C2];
Create names for the rectangle and the circles, and specify the formula to create the geometry.
ns = char('R1','C1','C2');
ns = ns';
sf = 'R1 - (C1 + C2)';
g = decsg(gd,sf,ns);
model = createpde("electromagnetic","conduction");
Include the geometry in the model, and plot it with the edge labels.
geometryFromEdges(model,g);
pdegplot(model,"EdgeLabels","on")
3-220
Current Density Between Two Metallic Conductors
Specify the electric potential values on the left and right circular conductors.
electromagneticBC(model,"Edge",5:8,"Voltage",1);
electromagneticBC(model,"Edge",9:12,"Voltage",-1);
R =
ConductionResults with properties:
3-221
3 Solving PDEs
Plot the resulting electric potential and current density, and display the equipotential lines. The
current flows from the conductor with a positive potential to the conductor with a negative potential.
The conductivity σ is isotropic, and the equipotential lines are orthogonal to the current lines.
pdeplot(model,"XYData",R.ElectricPotential, ...
"Contour","on", ...
"FlowData",[R.CurrentDensity.Jx,R.CurrentDensity.Jy])
axis equal
3-222
Skin Effect in Copper Wire with Circular Cross Section: PDE Modeler App
1
−∇ · ∇Ec + jωσ − ω2ε Ec = 0
μ
describes the propagation of plane electromagnetic waves in imperfect dielectrics and good
conductors (σ » ωε). The coefficient of dielectricity is ε = 8.8*10-12 F/m. The conductivity of copper is
σ = 57 * 106 S/m. The magnetic permeability of copper is close to the magnetic permeability of a
vacuum, µ = 4π*10–7 H/m. The ω2ε-term is negligible at the line frequency (50 Hz).
Due to induction, the current density in the interior of the conductor is smaller than at the outer
surface, where it is set to JS = 1. The Dirichlet condition for the electric field is Ec = 1/σ. In this case,
the analytical solution is
J0 kr
J = JS
J0 kR
Here,
k= jωμσ,
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.
To solve this problem in the PDE Modeler app, follow these steps:
1 Draw a circle with a radius of 0.1. The circle represents a cross section of the conductor.
pdecirc(0,0.05,0.1)
2 Set the x-axis limit to [-0.2 0.2] and the y-axis limit to [-0.1 0.2]. To do this, select
Options > Axes Limits and set the corresponding ranges. Then select Options > Axes Equal.
3 Set the application mode to AC Power Electromagnetics.
4 Specify the Dirichlet boundary condition E = JS/σ = 1/σ for the boundary of the circle. To do this:
Then select PDE > PDE Specification or click the button on the toolbar. Specify the
following values:
3-223
3 Solving PDEs
The solution of the AC power electromagnetics equation is complex. When plotting the solution,
you get a warning message.
Due to the skin effect, the current density at the surface of the conductor is much higher than in
the conductor's interior.
3-224
Skin Effect in Copper Wire with Circular Cross Section: PDE Modeler App
9 Improve the accuracy of the solution close to the surface by using adaptive mesh refinement. To
do this:
3-225
3 Solving PDEs
12 These plots show the real part of the solution, but the solution vector is the full complex solution.
Plot the imaginary part of the solution. To do this:
3-226
Skin Effect in Copper Wire with Circular Cross Section: PDE Modeler App
13 Observe that the skin effect depends on the frequency of the alternating current. When you
increase or decrease the frequency, the skin "depth" increases or decreases, respectively. At high
frequencies, only a thin layer on the surface of the wire conducts the current. At very low
frequencies (approaching DC conditions), almost the entire cross section area of the wire
conducts the current.
Find the solution for the angular frequencies omega = , omega = 2*pi*50, and omega =
1E-6. Plot the real parts of the solutions in 2-D.
3-227
3 Solving PDEs
3-228
Skin Effect in Copper Wire with Circular Cross Section: PDE Modeler App
3-229
3 Solving PDEs
3-230
Current Density Between Two Metallic Conductors: PDE Modeler App
–∇ · (σ∇V) = 0
∂V
=0
∂n
The conductivity is σ = 1.
To solve this equation in the PDE Modeler app, follow these steps:
1 Model the geometry: draw the rectangle with corners at (-1.2,-0.6), (1.2,-0.6), (1.2,0.6), and
(-1.2,0.6), and two circles with a radius of 0.3 and centers at (-0.6,0) and (0.6,0). The rectangle
represents the blotting paper, and the circles represent the conductors.
• For the rectangle, use the Neumann boundary condition with g = 0 and q = 0.
• For the left circle, use the Dirichlet boundary condition with h = 1 and r = 1.
• For the right circle, use the Dirichlet boundary condition with h = 1 and r = -1.
5
Specify the coefficients by selecting PDE > PDE Specification or clicking the button on
the toolbar. Specify sigma = 1 and q = 0.
6 Initialize the mesh by selecting Mesh > Initialize Mesh.
7 Refine the mesh by selecting Mesh > Refine Mesh.
8 Improve the triangle quality by selecting Mesh > Jiggle Mesh.
9
Solve the PDE by selecting Solve > Solve PDE or clicking the button on the toolbar. The
resulting potential is zero along the y-axis, which, for this problem, is a vertical line of
antisymmetry.
3-231
3 Solving PDEs
The current flows, as expected, from the conductor with a positive potential to the conductor
with a negative potential. The conductivity σ is isotropic, and the equipotential lines are
orthogonal to the current lines.
3-232
Current Density Between Two Metallic Conductors: PDE Modeler App
3-233
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
ρC − ∇ ⋅ 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 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
• 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
3-234
Heat Transfer Between Two Squares Made of Different Materials: PDE Modeler App
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-235
3 Solving PDEs
Isothermal Lines
3-236
Heat Transfer Between Two Squares Made of Different Materials: PDE Modeler App
3-237
3 Solving PDEs
Adjust the axes limits by selecting Options > Axes Limits. Select Auto to use automatic scaling for
both axes.
3-238
Temperature Distribution in Heat Sink
Export the geometry description matrix, set formula, and name-space matrix into the MATLAB
workspace by selecting Draw > Export Geometry Description, Set Formula, Labels. This data
lets you reconstruct the geometry in the workspace.
g = decsg(gd,sf,ns);
pdegplot(g,"FaceLabels","on")
3-239
3 Solving PDEs
model = createpde("thermal","transient");
Create a 2-D geometry from the decomposed geometry matrix and assign the geometry to the
thermal model.
g = geometryFromEdges(model,g);
g = extrude(g,0.0005);
Plot the extruded geometry so that you can see the face labels on the top.
figure
pdegplot(g,"FaceLabels","on")
view([0 90])
3-240
Temperature Distribution in Heat Sink
Extrude the circular faces (faces with IDs from 15 to 26) along the z-axis by 0.005 more units. These
faces form the fins of the heat sink.
g = extrude(g,[15:26],0.005);
Assign the modified geometry to the thermal model and plot the geometry.
model.Geometry = g;
figure
pdegplot(g)
3-241
3 Solving PDEs
thermalProperties(model,"ThermalConductivity",400, ...
"MassDensity",8960, ...
"SpecificHeat",386);
model.StefanBoltzmannConstant = 5.670367e-8;
Apply the temperature boundary condition on the bottom surface of the heat sink, which consists of
13 faces.
thermalBC(model,"Face",1:13,"Temperature",1000);
Specify the convection and radiation parameters on all other surfaces of the heat sink.
thermalBC(model,"Face",14:g.NumFaces, ...
"ConvectionCoefficient",5, ...
"AmbientTemperature",300, ...
"Emissivity",0.8);
Set the initial temperature of all the surfaces to the ambient temperature.
thermalIC(model,300);
Generate a mesh.
generateMesh(model);
3-242
Temperature Distribution in Heat Sink
Solve the transient thermal problem for times between 0 and 0.0075 s with a time step of 0.0025 s.
results = solve(model,0:0.0025:0.0075);
for i = 1:length(results.SolutionTimes)
figure
pdeplot3D(model,"ColorMapData",results.Temperature(:,i))
title({['Time = ' num2str(results.SolutionTimes(i)) 's']})
end
3-243
3 Solving PDEs
3-244
Temperature Distribution in Heat Sink
3-245
3 Solving PDEs
You also can plot the same results by using the Visualize PDE Results Live Editor task. First, create
a new live script by clicking the New Live Script button in the File section on the Home tab.
On the Live Editor tab, select Task > Visualize PDE Results. This action inserts the task into your
script.
3-246
Temperature Distribution in Heat Sink
To plot the temperature distribution for each time step, follow these steps.
1 In the Select results section of the task, select results from the drop-down list.
2 In the Specify data parameters section of the task, set Type to Temperature, and set the time
steps to 1, 2, 3, and 4. These time steps correspond to the four time values that you used to solve
the problem. You also can animate the solution by selecting Animate.
3-247
3 Solving PDEs
3-248
Nonlinear Heat Transfer in Thin Plate
This example shows how to perform a heat transfer analysis of a thin plate.
The plate is square, and the temperature is fixed along the bottom edge. The other three edges are
insulated, there is no heat transfer from these edges. 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.
These example shows how to perform both a steady state and a transient analysis. In a steady state
analysis, the example computes the final temperature at different points in the plate after it has
reached an equilibrium state. In a transient analysis, the example computes the temperature in the
plate as a function of time. The transient analysis section of the example also finds how long it takes
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 face per unit area due to convection is defined as
Qc = hc(T − Ta)
where Ta is the ambient temperature, T is the temperature at a particular x and y location on the
plate surface, and hc is a specified convection coefficient.
The amount of heat transferred from each face per unit area due to radiation is defined as
Qr = ϵσ(T 4 − Ta4)
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.
∂T
ρCptz − ktz ∇2 T + 2Qc + 2Qr = 0
∂t
where ρ is the material density, Cp is the specific heat, tz is the plate thickness, and the factors of two
account for the heat transfer from both plate faces.
∂T
ρCptz − ktz ∇2 T + 2hcT + 2ϵσT 4 = 2hcTa + 2ϵσTa4
∂t
3-249
3 Solving PDEs
Problem Setup
Create a model.
model = createpde;
width = 1;
height = 1;
gdm = [3 4 0 width width 0 0 0 height height]';
g = decsg(gdm,'S1',('S1')');
geometryFromEdges(model,g);
figure;
pdegplot(model,"EdgeLabels","on");
axis([-.1 1.1 -.1 1.1]);
title("Geometry With Edge Labels Displayed")
3-250
Nonlinear Heat Transfer in Thin Plate
c = thick*k;
f = 2*hCoeff*ta + 2*emiss*stefanBoltz*ta^4;
d = thick*rho*specificHeat;
Because of the radiation boundary condition, the coefficient a is a function of the temperature u.
Apply the boundary conditions. For the insulated edges, keep the default zero Neumann boundary
condition. For the bottom edge (edge 1), use the Dirichlet boundary condition to set the temperature
to 1000 K.
applyBoundaryCondition(model,"dirichlet","Edge",1,"u",1000);
3-251
3 Solving PDEs
R = solvepde(model);
u = R.NodalSolution;
figure;
pdeplot(model,"XYData",u,"Contour","on","ColorMap","jet");
title("Temperature In The Plate, Steady State Solution")
xlabel("X-coordinate, meters")
ylabel("Y-coordinate, meters")
axis equal
3-252
Nonlinear Heat Transfer in Thin Plate
p = msh.Nodes;
plotAlongY(p,u,0);
title("Temperature As a Function of the Y-Coordinate")
xlabel("Y-coordinate, meters")
ylabel("Temperature, degrees-Kelvin")
3-253
3 Solving PDEs
Transient Solution
specifyCoefficients(model,"m",0,"d",d,"c",c,"a",a,"f",f);
endTime = 5000;
tlist = 0:50:endTime;
setInitialConditions(model,300);
Set the initial temperature on the bottom edge to the value of the constant boundary condition, 1000
K.
setInitialConditions(model,1000,"Edge",1);
model.SolverOptions.RelativeTolerance = 1.0e-3;
model.SolverOptions.AbsoluteTolerance = 1.0e-4;
3-254
Nonlinear Heat Transfer in Thin Plate
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-255
3 Solving PDEs
Summary
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-256
Poisson's Equation on Unit Disk: PDE Modeler App
This example uses the PDE Modeler app. For a programmatic workflow, see “Poisson's Equation on
Unit Disk” on page 3-263. 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:
3-257
3 Solving PDEs
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-258
Poisson's Equation on Unit Disk: PDE Modeler App
3-259
3 Solving PDEs
12
Refine the mesh by selecting Mesh > Refine Mesh or clicking the button.
3-260
Poisson's Equation on Unit Disk: PDE Modeler App
13 Compare the numerical solution to the exact solution for the refined mesh. Plot the absolute
error.
3-261
3 Solving PDEs
14 Export the mesh data and the solution to the MATLAB workspace by selecting Mesh > Export
Mesh and Solve > Export Solution, respectively.
3-262
Poisson's Equation on Unit Disk
This example shows how to numerically solve a Poisson's equation, compare the numerical solution
with the exact solution, and refine the mesh until the solutions are close.
The Poisson equation on a unit disk with zero Dirichlet boundary condition can be written as −Δu = 1
in Ω, u = 0 on δΩ, where Ω is the unit disk. The exact solution is
1 − x2 − y2
u(x, y) = .
4
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
Plot the geometry and display the edge labels for use in the boundary condition definition.
figure
pdegplot(model,"EdgeLabels","on");
axis equal
3-263
3 Solving PDEs
applyBoundaryCondition(model,"dirichlet", ...
"Edge",1:model.Geometry.NumEdges, ...
"u",0);
specifyCoefficients(model,"m",0,"d",0,"c",1,"a",0,"f",1);
hmax = 0.1;
generateMesh(model,"Hmax",hmax);
figure
pdemesh(model);
axis equal
results = solvepde(model);
u = results.NodalSolution;
pdeplot(model,"XYData",u)
title("Numerical Solution");
xlabel("x")
ylabel("y")
3-264
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-265
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
−7
vector is less than 5 ⋅ 10 .
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;
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");
3-266
Poisson's Equation on Unit Disk
xlabel("Iteration");
ylabel("Norm of Error");
figure
pdemesh(model);
axis equal
3-267
3 Solving PDEs
figure
pdeplot(model,"XYData",u)
title("Numerical Solution");
xlabel("x")
ylabel("y")
3-268
Poisson's Equation on Unit Disk
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-269
3 Solving PDEs
3-270
Scattering Problem
Scattering Problem
Solve a simple scattering problem, where you compute the waves reflected by an object illuminated
by incident waves. This example shows how to solve a scattering problem using the electromagnetic
workflow. For the general PDE workflow, see “Helmholtz Equation on Disk with Square Hole” on page
3-209.
For this problem, assume that the domain is an infinite horizontal membrane that is subjected to
small vertical displacements. The membrane is fixed at the object boundary. The medium is
homogeneous, and the phase velocity (propagation speed) of a wave, α, is constant. For this problem,
assume α=1. In this case, the frequency wave number equals the frequency, k = ω/α = ω.
To solve the scattering problem, first create an electromagnetic model for harmonic analysis.
emagmodel = createpde("electromagnetic","harmonic");
omega = 4*pi;
Represent the square surface with a diamond-shaped hole. Define a diamond in a square, place them
in one matrix, and create a set formula that subtracts the diamond from the square.
g = decsg(gd,sf,ns);
geometryFromEdges(emagmodel,g);
Include the geometry in the model and plot it with the edge labels.
figure;
pdegplot(emagmodel,"EdgeLabels","on");
xlim([-6,6])
ylim([-6,6])
3-271
3 Solving PDEs
emagmodel.VacuumPermittivity = 1;
emagmodel.VacuumPermeability = 1;
Specify the relative permittivity, relative permeability, and conductivity of the material.
electromagneticProperties(emagmodel,"RelativePermittivity",1, ...
"RelativePermeability",1, ...
"Conductivity",0);
Apply the absorbing boundary condition on the edges of the square. Specify the thickness and
attenuation rate for the absorbing region by using the Thickness, Exponent, and Scaling
arguments.
3-272
Scattering Problem
Generate a mesh.
generateMesh(emagmodel,"Hmax",0.1);
result = solve(emagmodel,"Frequency",omega);
Plot the real part of the x-component of the resulting electric field.
u = result.ElectricField;
figure
pdeplot(emagmodel,"XYData",real(u.Ex),"Mesh","off");
colormap(jet)
Interpolate the resulting electric field to a grid covering the portion of the geometry, for x and y from
-1 to 4.
v = linspace(-1,4,101);
[X,Y] = meshgrid(v);
Eintrp = interpolateHarmonicField(result,X,Y);
Reshape Eintrp.Ex and plot the x-component of the resulting electric field.
EintrpX = reshape(Eintrp.ElectricField.Ex,size(X));
figure
3-273
3 Solving PDEs
surf(X,Y,real(EintrpX),"LineStyle","none");
view(0,90)
colormap(jet)
Using the solutions for a vector of frequencies, create an animation showing the corresponding
solution to the time-dependent wave equation.
result = solve(emagmodel,"Frequency",omega/10:omega);
figure
for m = 1:length(omega/10:omega)
u = result.ElectricField;
pdeplot(emagmodel,"XYData",real(u.Ex(:,m)),"Mesh","off");
colormap(jet)
M(m) = getframe;
end
3-274
Scattering Problem
To play the animation, use the movie function. For example, to play the animation five times in a loop
with 3 frames per second, use the movie(M,5,3) command.
3-275
3 Solving PDEs
For this problem, assume an infinite horizontal membrane subjected to small vertical displacements
U. The membrane is fixed at the object boundary. The medium is homogeneous, and the phase
velocity (propagation speed) of a wave, α, is constant. The wave equation is
∂2 U
2
− α2 ΔU = 0
∂t
The solution U is the sum of the incident wave V and the reflected wave R:
U=V+R
When the illumination is harmonic in time, you can compute the field by solving a single steady
problem. Assume that the incident wave is a plane wave traveling in the –x direction:
The reflected wave can be decomposed into spatial and time components:
R x, y, t = r x, y e−iωt
Now you can rewrite the wave equation as the Helmholtz equation for the spatial component of the
reflected wave with the wave number k = ω/α:
–Δr – k2r = 0
The Dirichlet boundary condition for the boundary of the object is U = 0, or in terms of the incident
and reflected waves, R = -V. For the time-harmonic solution and the incident wave traveling in the –x
direction, you can write this boundary condition as follows:
r x, y = − e−ikx
The reflected wave R travels outward from the object. The condition at the outer computational
boundary must allow waves to pass without reflection. Such conditions are usually called
nonreflecting. As x approaches infinity, R approximately satisfies the one-way wave equation
∂R
+ αξ · ∇R = 0
∂t
This equation considers only the waves moving in the positive ξ-direction. Here, ξ is the radial
distance from the object. With the time-harmonic solution, this equation turns into the generalized
Neumann boundary condition
ξ · ∇r = ikr
To solve the scattering problem in the PDE Modeler app, follow these steps:
3-276
Scattering Problem: PDE Modeler App
2 Set the x-axis limit to [0.1 1.5] and the y-axis limit to [0 1]. To do this, select Options >
Axes Limits and set the corresponding ranges.
3 Display grid lines. To do this:
a Select Options > Grid Spacing and clear the Auto checkboxes.
b Enter X-axis linear spacing as 0.1:0.05:1.5 and Y-axis linear spacing as 0:0.05:1.
c Select Options > Grid.
4 Align new shapes to the grid lines by selecting Options > Snap.
5
Draw a square with sides of length 0.1 and a center in [0.8 0.5]. To do this, first click the
button. Then right-click the origin and drag to draw a square. Right-clicking constrains the shape
you draw so that it is a square rather than a rectangle. If the square is not a perfect square,
double-click it. In the resulting dialog box, specify the exact location of the bottom left corner
and the side length.
6 Rotate the square by 45 degrees. To do this, select Draw > Rotate... and enter 45 in the
resulting dialog box. The rotated square represents the illuminated object.
7
Draw a circle with a radius of 0.45 and a center in [0.8 0.5]. To do this, first click the
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.
8 Model the geometry by entering C1-SQ1 in the Set formula field.
9 Check that the application mode is set to Generic Scalar.
10 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.
• For the perimeter of the circle, the boundary condition is the Neumann boundary condition
with q = -ik, where the wave number k = 60 corresponds to a wavelength of about 0.1
units. Enter g = 0 and q = -60*i.
• For the perimeter of the square, the boundary condition is the Dirichlet boundary condition:
r = − v x, y = − eika ⋅ x
In this problem, because the reflected wave travels in the –x direction, the boundary condition
is r = –e–ikx. Enter h = 1 and r = -exp(-i*60*x).
11
Specify the coefficients by selecting PDE > PDE Specification or clicking the button on
the toolbar. The Helmholtz equation is a wave equation, but in Partial Differential Equation
Toolbox you can treat it as an elliptic equation with a = -k2. Specify c = 1, a = -3600, and f
= 0.
12 Initialize the mesh by selecting Mesh > Initialize Mesh.
For sufficient accuracy, you need about 10 finite elements per wavelength. The outer boundary
must be located a few object diameters away from the object itself. Refine the mesh by selecting
Mesh > Refine Mesh. Refine the mesh two more times to achieve the required resolution.
3-277
3 Solving PDEs
13
Solve the PDE by selecting Solve > Solve PDE or clicking the button on the toolbar.
The solution is complex. When plotting the solution, you get a warning message.
14 Plot the reflected waves. Change the colormap to jet by selecting Plot > Parameters and then
selecting jet from the Colormap drop-down menu.
a Export the mesh data and the solution to the MATLAB workspace by selecting Mesh >
Export Mesh and Solve > Export Solution, respectively.
b Enter the following commands in the MATLAB Command Window.
figure
maxu = max(abs(u));
m = 10;
3-278
Scattering Problem: PDE Modeler App
for j = 1:m,
uu = real(exp(-j*2*pi/10*sqrt(-1))*u);
pdeplot(p,e,t,'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;
end
movie(M);
3-279
3 Solving PDEs
Create a geometry that consists of a rectangular frame with an H-shaped cavity, four rectangles
representing the two coils, and a unit square representing the air domain around the magnet. Specify
all dimensions in millimeters, and use the value 1000 to convert the dimensions to meters.
convfactor = 1000;
RS = [3;4;[-525;525;525;-525;-500;-500;500;500]/convfactor];
zeroPad = zeros(numel(RH)-numel(RS),1);
RS = [RS;zeroPad];
RC1 = [3;4;[150;250;250;150;120;120;350;350]/convfactor;
zeroPad];
RC2 = [3;4;[-150;-250;-250;-150;120;120;350;350]/convfactor;
zeroPad];
RC3 = [3;4;[150;250;250;150;-120;-120;-350;-350]/convfactor;
zeroPad];
RC4 = [3;4;[-150;-250;-250;-150;-120;-120;-350;-350]/convfactor;
zeroPad];
Create the geometry to model the air domain around the magnet.
RD = [3;4;[-1000;1000;1000;-1000;-1000; ...
-1000;1000;1000]/convfactor;zeroPad];
gd = [RS,RH,RC1,RC2,RC3,RC4,RD];
ns = char('RS','RH','RC1','RC2','RC3','RC4','RD');
g = decsg(gd,'(RS+RH+RC1+RC2+RC3+RC4)+RD',ns');
pdegplot(g,FaceLabels="on")
3-280
Magnetic Flux Density in H-Shaped Magnet with Nonlinear Relative Permeability
figure
pdegplot(g,EdgeLabels="on")
3-281
3 Solving PDEs
figure
pdemesh(model)
3-282
Magnetic Flux Density in H-Shaped Magnet with Nonlinear Relative Permeability
mu0 = 1.25663706212e-6;
model.VacuumPermeability = mu0;
model.MaterialProperties = materialProperties(RelativePermeability=1);
Now specify the large constant relative permeability of the ferromagnetic frame.
model.MaterialProperties(2) = ...
materialProperties(RelativePermeability=10000);
Specify the current density values on the upper and lower coils.
Specify that the magnetic potential on the outer surface of the air domain is 0.
Rlin = solve(model)
Rlin =
3-283
3 Solving PDEs
Specify the data for the magnetic flux density B and the corresponding magnetic field strength H.
From the data for B and H, interpolate the H(B) dependency using the modified Akima cubic Hermite
interpolation method.
HofB = griddedInterpolant(B,H,"makima","linear");
muR = @(B) B./HofB(B)/mu0;
model.MaterialProperties(2) = ...
materialProperties(RelativePermeability= ...
@(~,s) muR(s.NormFluxDensity));
Specify the initial guess by using the results obtained by the linear solver.
model.FaceIC = faceIC(MagneticVectorPotential=Rlin);
Rnonlin = solve(model);
3-284
Magnetic Flux Density in H-Shaped Magnet with Nonlinear Relative Permeability
References
[1] Kozlowski, A., R. Rygal, and S. Zurek. "Large DC electromagnet for semi-industrial
thermomagnetic processing of nanocrystalline ribbon." IEEE Transactions on Magnetics 50,
issue 4 (April 2014): 1–4. https://ieeexplore.ieee.org/document/6798057.
3-285
3 Solving PDEs
1
−∇ ⋅ ∇u = 0
2
1 + ∇u
− ∇ ⋅ c ∇u + au = f .
1
c= , a = 0, f = 0.
2
1 + ∇u
Because the coefficient c is a function of the solution u, the minimal surface problem is a nonlinear
elliptic problem.
To solve the minimal surface problem using the programmatic workflow, first create a PDE model
with a single dependent variable.
model = createpde;
Create the geometry and include it in the model. The circleg function represents this geometry.
geometryFromEdges(model,@circleg);
pdegplot(model,"EdgeLabels","on")
axis equal
title("Geometry with Edge Labels")
3-286
Minimal Surface Problem
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);
bcMatrix = @(region,~)region.x.^2;
applyBoundaryCondition(model,"dirichlet", ...
"Edge",1:model.Geometry.NumEdges, ...
"u",bcMatrix);
generateMesh(model,"Hmax",0.1);
figure;
pdemesh(model);
axis equal
3-287
3 Solving PDEs
Solve the problem by using the solvepde function. Because the problem is nonlinear, solvepde
invokes a nonlinear solver. Observe the solver progress by setting the
SolverOptions.ReportStatistics property of the model to 'on'.
model.SolverOptions.ReportStatistics = 'on';
result = solvepde(model);
u = result.NodalSolution;
Plot the solution by using the Visualize PDE Results Live Editor task. First, create a new live script
by clicking the New Live Script button in the File section on the Home tab.
3-288
Minimal Surface Problem
On the Live Editor tab, select Task > Visualize PDE Results. This action inserts the task into your
script.
1 In the Select results section of the task, select result from the drop-down list.
2 In the Specify data parameters section of the task, set Type to Nodal solution.
3 In the Specify visualization parameters section of the task, select the Mesh check box.
3-289
3 Solving PDEs
You also can plot the solution at the MATLAB® command line by using the pdeplot function. For
example, plot the solution as a 3-D plot, using the solution values for plot heights.
figure;
pdeplot(model,"XYData",u,"ZData",u);
xlabel x
ylabel y
zlabel u(x,y)
title("Minimal Surface")
colormap jet
3-290
Minimal Surface Problem
3-291
3 Solving PDEs
1
−∇ ⋅ ∇u = 0
2
1 + ∇u
This example uses the PDE Modeler app. For the programmatic workflow, see “Minimal Surface
Problem” on page 3-286.
− ∇ ⋅ c ∇u + au = f
Therefore, for the minimal surface problem the coefficients are as follows:
1
c= , a = 0, f = 0
2
1 + ∇u
Because the coefficient c is a function of the solution u, the minimal surface problem is a nonlinear
elliptic problem.
To solve the minimal surface problem in the PDE Modeler app, follow these steps:
a
Switch to boundary mode by clicking the button or selecting Boundary > Boundary
Mode.
b Select all boundaries by selecting Edit > Select All.
c Select Boundary > Specify Boundary Conditions.
d Specify the Dirichlet boundary condition u = x2. To do this, specify h = 1, r = x.^2.
4
Specify the coefficients by selecting PDE > PDE Specification or clicking the button on
the toolbar. Specify c = 1./sqrt(1+ux.^2+uy.^2), a = 0, and f = 0.
5 Initialize the mesh by selecting Mesh > Initialize Mesh.
6 Refine the mesh by selecting Mesh > Refine Mesh.
7 Choose the nonlinear solver. To do this, select Solve > Parameters and check Use nonlinear
solver. Set the tolerance parameter to 0.001.
8
Solve the PDE by selecting Solve > Solve PDE or clicking the button on the toolbar.
9 Plot the solution in 3-D. To do this, select PlotParameters. In the resulting dialog box, select
Height (3-D plot).
3-292
Minimal Surface Problem: PDE Modeler App
3-293
3 Solving PDEs
This example shows how to solve a Poisson's equation with a delta-function point source on the unit
disk using the adaptmesh function.
−Δu = δ(x, y)
on the unit disk with zero Dirichlet boundary conditions. The exact solution expressed in polar
coordinates is
log(r)
u(r, θ) = ,
2π
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);
g = @circleg;
geometryFromEdges(model,g);
figure;
pdegplot(model,"EdgeLabels","on");
axis equal
title("Geometry With Edge Labels Displayed")
3-294
Poisson's Equation with Point Source and Adaptive Mesh Refinement
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 next iteration. circlepick
returns triangles with computed error estimates greater a given tolerance. The tolerance is provided
to circlepick using the "par" parameter.
3-295
3 Solving PDEs
figure;
pdemesh(p,e,t);
axis equal
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-296
Poisson's Equation with Point Source and Adaptive Mesh Refinement
figure;
pdeplot(p,e,t,"XYData",u,"ZData",u,"Mesh","off");
3-297
3 Solving PDEs
3-298
Heat Transfer in Block with Cavity: PDE Modeler App
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 − Δu = 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-299
3 Solving PDEs
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.
9
Specify the coefficients by selecting PDE > PDE Specification or clicking the 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.
3-300
Heat Transfer in Block with Cavity: PDE Modeler App
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:
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).
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-301
3 Solving PDEs
This example shows how to solve for the heat distribution in a 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 −10W /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 first step in solving a heat transfer problem is to create a thermal analysis model. This is a
container that holds the geometry, thermal material properties, internal heat sources, temperature on
the boundaries, heat fluxes through the boundaries, mesh, and initial conditions.
thermalmodel = createpde("thermal","transient");
Import Geometry
Add the block geometry to the thermal model by using the geometryFromEdges function. The
geometry description file for this problem is called crackg.m.
geometryFromEdges(thermalmodel,@crackg);
pdegplot(thermalmodel,"EdgeLabels","on")
ylim([-1,1])
axis equal
3-302
Heat Transfer in Block with Cavity
Specify the thermal conductivity, mass density, and specific heat of the material.
thermalProperties(thermalmodel,"ThermalConductivity",1,...
"MassDensity",1,...
"SpecificHeat",1);
Specify the temperature on the left edge as 100, and constant heat flow to the exterior through the
right edge as -10. The toolbox uses the default insulating boundary condition for all other
boundaries.
thermalBC(thermalmodel,"Edge",6,"Temperature",100);
thermalBC(thermalmodel,"Edge",1,"HeatFlux",-10);
Generate Mesh
3-303
3 Solving PDEs
pdemesh(thermalmodel)
title("Mesh with Quadratic Triangular Elements")
Calculate Solution
thermalresults =
TransientThermalResults with properties:
3-304
Heat Transfer in Block with Cavity
[qx,qy] = evaluateHeatFlux(thermalresults);
Plot the solution at the final time step, t = 5.0 seconds, with isothermal lines using a contour plot, and
plot the heat flux vector field using arrows.
pdeplot(thermalmodel,"XYData",thermalresults.Temperature(:,end), ...
"Contour","on",...
"FlowData",[qx(:,end),qy(:,end)], ...
"ColorMap","hot")
3-305
3 Solving PDEs
Consider a block containing a rectangular crack or cavity. The left side of the block is heated to 100
degrees Celsius. At the right side of the block, heat flows from the block to the surrounding air at a
constant rate of –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 first step in solving this heat transfer problem is to create an femodel object for thermal
analysis with a geometry representing a block with a cavity.
model = femodel(AnalysisType="thermalTransient", ...
Geometry=@crackg);
Plot Geometry
Specify the thermal conductivity, mass density, and specific heat of the material.
3-306
Heat Transfer in Block with Cavity
model.MaterialProperties = ...
materialProperties(ThermalConductivity=1, ...
MassDensity=1, ...
SpecificHeat=1);
Specify the temperature on the left edge as 100 and constant heat flow to the exterior through the
right edge as -10. The toolbox uses the default insulating boundary condition for all other
boundaries.
model.EdgeBC(6) = edgeBC(Temperature=100);
model.EdgeLoad(1) = edgeLoad(Heat=-10);
Generate Mesh
Generate a mesh and assign the result to the model. This assignment updates the mesh stored in the
Geometry property of the model. Plot the mesh.
model = generateMesh(model);
figure
pdemesh(model);
title("Mesh with Quadratic Triangular Elements")
3-307
3 Solving PDEs
tlist = 0:0.5:5;
Calculate Solution
results = solve(model,tlist)
results =
[qx,qy] = evaluateHeatFlux(results);
Plot the solution at the final time step, t = 5.0 seconds, with isothermal lines using a contour plot, and
plot the heat flux vector field using arrows.
figure
pdeplot(results.Mesh,XYData=results.Temperature(:,end), ...
Contour="on",...
FlowData=[qx(:,end),qy(:,end)], ...
ColorMap="hot")
3-308
Heat Transfer in Block with Cavity
3-309
3 Solving PDEs
This example shows how to solve the heat equation with a temperature-dependent thermal
conductivity. The example shows an idealized thermal analysis of a rectangular block with a
rectangular cavity in the center.
The partial differential equation for transient conduction heat transfer is:
∂T
ρCp − ∇ ⋅ (k ∇T) = f
∂t
where T is the temperature, ρ is the material density, Cp is the specific heat, and k is the thermal
conductivity. f 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.
figure
pdegplot(thermalmodelS,"EdgeLabels","on");
axis([-.9 .9 -.9 .9]);
title("Block Geometry With Edge Labels Displayed")
3-310
Heat Transfer Problem with Temperature-Dependent Properties
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",6,"Temperature",100);
thermalBC(thermalmodelS,"Edge",1,"HeatFlux",-10);
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-311
3 Solving PDEs
R = solve(thermalmodelS);
T = R.Temperature;
figure
pdeplot(thermalmodelS,"XYData",T,"Contour","on","ColorMap","hot");
axis equal
title("Temperature, Steady State Solution")
3-312
Heat Transfer Problem with Temperature-Dependent Properties
thermalmodelT = createpde("thermal","transient");
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. You can find the helper function
transientBCHeatedBlock under matlab/R20XXx/examples/pde/main.
thermalBC(thermalmodelT,"Edge",6,"Temperature",@transientBCHeatedBlock);
On the right edge, there is a prescribed heat flux out of the block.
thermalBC(thermalmodelT,"Edge",1,"HeatFlux",-10);
3-313
3 Solving PDEs
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.
msh = generateMesh(thermalmodelT,"Hmax",0.2);
figure
pdeplot(thermalmodelT);
axis equal
title("Block With Finite Element Mesh Displayed")
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.
Call this function to get a node near the center of the right edge.
3-314
Heat Transfer Problem with Temperature-Dependent Properties
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")
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.
3-315
3 Solving PDEs
R = solve(thermalmodelS);
T = R.Temperature;
figure
pdeplot(thermalmodelS,"XYData",T,"Contour","on","ColorMap","hot");
axis equal
title("Temperature, Steady State Solution")
Use the same timespan tlist = 0:.1:5 as for the linear case.
thermalIC(thermalmodelT,0);
R = solve(thermalmodelT,tlist);
T = R.Temperature;
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.
3-316
Heat Transfer Problem with Temperature-Dependent Properties
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-317
3 Solving PDEs
This example shows how to perform a 3-D transient heat conduction analysis of a hollow sphere made
of three different layers of material.
The physical properties and geometry of this problem are described in Singh, Jain, and Rizwan-uddin
(see Reference), 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 y value has a nonuniform
heat flux defined by
2 2 2 2
qouter = θ (π − θ) ϕ (π − ϕ)
0 ≤ θ ≤ π, 0 ≤ ϕ ≤ π .
θ 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");
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.
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")
3-318
Heat Conduction in Multidomain Geometry with Nonuniform Heat Flux
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 the 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, ...
"SpecificHeat",1);
thermalProperties(thermalmodel,"Cell",2,"ThermalConductivity",2, ...
"MassDensity",1, ...
"SpecificHeat",0.5);
thermalProperties(thermalmodel,"Cell",3,"ThermalConductivity",4, ...
"MassDensity",1, ...
"SpecificHeat",4/9);
Specify boundary conditions. The innermost face has a temperature of zero at all times.
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,~] = cart2sph(region.x,region.y,region.z);
3-319
3 Solving PDEs
Qflux = zeros(size(region.x));
end
[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-320
Heat Conduction in Multidomain Geometry with Nonuniform Heat Flux
thermalBC(thermalmodel,"Face",4, ...
"HeatFlux",@externalHeatFlux, ...
"Vectorized","on");
thermalIC(thermalmodel,0);
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))
clim([Tmin,Tmax])
view(130,10)
title(["Temperature at Time " num2str(tlist(i))]);
M(i) = getframe;
end
3-321
3 Solving PDEs
To see a movie of the contours when running this example on your computer, execute the following
line:
movie(M,2)
Visualize the temperature contours on the cross-section. First, define a rectangular grid of points on
the y − z plane where x = 0.
[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.
tIndex = [2,3,5,7,9,11];
varNames = {'Time_index','Time_step'};
index_step = table(tIndex.',tlist(tIndex).','VariableNames',varNames);
disp(index_step);
Time_index Time_step
__________ _________
2 2
3 5
5 15
7 25
9 35
11 45
3-322
Heat Conduction in Multidomain Geometry with Nonuniform Heat Flux
TG = interpolateTemperature(R,XG,YG,ZG,tIndex);
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
clim([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)
plot(ylayer4,zlayer4,"k","LineWidth",1.5)
end
3-323
3 Solving PDEs
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-324
Inhomogeneous Heat Equation on Square Domain
This example shows how to solve the heat equation with a source term.
∂u
− Δu = 1
∂t
This equation is solved on a square domain with a discontinuous initial condition and zero
temperatures on the boundaries.
thermalmodel = createpde("thermal","transient");
Create a square geometry centered at x = 0 and y = 0 with sides of length 2. Include a circle of
radius 0.4 concentric with the square.
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);
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")
3-325
3 Solving PDEs
thermalBC(thermalmodel,"Edge",1:4,"Temperature",0);
The discontinuous initial value is 1 inside the circle and zero outside. Specify zero initial temperature
everywhere.
thermalIC(thermalmodel,0);
thermalIC(thermalmodel,1,"Face",2);
msh = generateMesh(thermalmodel);
figure;
pdemesh(thermalmodel);
axis equal
3-326
Inhomogeneous Heat Equation on Square Domain
nframes = 20;
tlist = linspace(0,0.1,nframes);
thermalmodel.SolverOptions.ReportStatistics ='on';
result = solve(thermalmodel,tlist);
97 successful steps
0 failed attempts
196 function evaluations
1 partial derivatives
21 LU decompositions
195 solutions of linear systems
T = result.Temperature;
figure
Tmax = max(max(T));
Tmin = min(min(T));
for j = 1:nframes
pdeplot(thermalmodel,"XYData",T(:,j),"ZData",T(:,j));
axis([-1 1 -1 1 0 1]);
Mv(j) = getframe;
end
3-327
3 Solving PDEs
3-328
Heat Distribution in Circular Cylindrical Rod
This example shows how to simplify a 3-D axisymmetric thermal problem to a 2-D problem using the
symmetry around the axis of rotation of the body.
This example analyzes heat transfer in a rod with a circular cross section. There is a heat source at
the bottom of the rod and a fixed temperature at the top. The outer surface of the rod exchanges heat
with the environment because of convection. In addition, the rod itself generates heat because of
radioactive decay. The goal is to find the temperature in the rod as a function of time.
The model geometry, material properties, and boundary conditions must all be symmetric about the
axis of rotation. The toolbox assumes that the axis of rotation is the vertical axis passing through r =
0.
Steady-State Solution
First, compute the steady-state solution. If the final time in the transient analysis is sufficiently large,
the transient solution at the final time must be close to the steady state solution. By comparing these
two results, you can check the accuracy of the transient analysis.
thermalmodel = createpde("thermal","steadystate-axisymmetric");
The 2-D model is a rectangular strip whose x-dimension extends from the axis of symmetry to the
outer surface and y-dimension extends over the actual length of the rod (from -1.5 m to 1.5 m).
Create the geometry by specifying the coordinates of its four corners.
geometryFromEdges(thermalmodel,g);
figure
pdegplot(thermalmodel,"EdgeLabels","on")
axis equal
3-329
3 Solving PDEs
thermalProperties(thermalmodel,"ThermalConductivity",k);
internalHeatSource(thermalmodel,q);
Define the boundary conditions. There is no heat transferred in the direction normal to the axis of
symmetry (edge 1). You do not need to change the default boundary condition for this edge. Edge 2 is
kept at a constant temperature T = 100 °C.
thermalBC(thermalmodel,"Edge",2,"Temperature",100);
Specify the convection boundary condition on the outer boundary (edge 3). The surrounding
temperature at the outer boundary is 100 °C, and the heat transfer coefficient is 50 W/ m ⋅∘ C .
thermalBC(thermalmodel,"Edge",3,...
"ConvectionCoefficient",50,...
"AmbientTemperature",100);
3-330
Heat Distribution in Circular Cylindrical Rod
The heat flux at the bottom of the rod (edge 4) is 5000 W/m2.
thermalBC(thermalmodel,"Edge",4,"HeatFlux",5000);
msh = generateMesh(thermalmodel);
figure
pdeplot(thermalmodel)
axis equal
result = solve(thermalmodel);
T = result.Temperature;
figure
pdeplot(thermalmodel,"XYData",T,"Contour","on")
axis equal
title("Steady-State Temperature")
3-331
3 Solving PDEs
Transient Solution
thermalmodel.AnalysisType = "transient-axisymmetric";
Specify the thermal conductivity, mass density, and specific heat of the material.
thermalProperties(thermalmodel,"ThermalConductivity",k,...
"MassDensity",rho,...
"SpecificHeat",cp);
thermalIC(thermalmodel,0);
Compute the transient solution for solution times from t = 0 to t = 50000 seconds.
tfinal = 50000;
tlist = 0:100:tfinal;
result = solve(thermalmodel,tlist);
T = result.Temperature;
figure
pdeplot(thermalmodel,"XYData",T(:,end),"Contour","on")
3-332
Heat Distribution in Circular Cylindrical Rod
axis equal
title(sprintf(['Transient Temperature' ...
' at Final Time (%g seconds)'],tfinal))
Find the temperature at the bottom surface of the rod: first, at the center axis and then on the outer
surface.
Tcenter = interpolateTemperature(result,[0.0;-1.5],1:numel(tlist));
Touter = interpolateTemperature(result,[0.2;-1.5],1:numel(tlist));
Plot 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 °C. When the surface temperature of
the rod is less than 100 °C, the environment heats the rod. The outer surface is slightly warmer than
the inner axis. When the surface temperature is greater than 100 °C, the environment cools the rod.
The outer surface becomes cooler than the interior of the rod.
figure
plot(tlist,Tcenter)
hold on
plot(tlist,Touter,"--")
title("Temperature at the Bottom as a Function of Time")
xlabel("Time, s")
ylabel("Temperature, C")
grid on
legend("Center Axis","Outer Surface","Location","SouthEast")
3-333
3 Solving PDEs
3-334
Thermal Analysis of Disc Brake
This example analyses the temperature distribution of a disc brake. Disc brakes absorb the
translational mechanical energy through friction and transform it into the thermal energy, which then
dissipates. The transient thermal analysis of a disc brake is critical because the friction and braking
performance decreases at high temperatures. Therefore, disc brakes must not exceed a given
temperature limit during operation.
• Perform a highly detailed simulation of the brake pad moving around the disc. Because the
computational cost is high, this part of the example only simulates one half revolution (25 ms).
• Simulate full braking when the car goes from 100 km/h to 0 km/h in 2.75 seconds, and then
remains stopped for 2.25 more seconds in order to allow the heat in the disc to dissipate.
The example uses a vehicle model in Simscape™ Driveline™ to obtain the time dependency of the
dissipated power.
Simulate a circular brake pad moving around the disc. This detailed simulation over a short timescale
models the heat source as a point moving around the disc.
model = createpde("thermal","transient");
importGeometry(model,"brake_disc.stl");
figure
pdegplot(model,"FaceLabels","on");
view([-5 -47])
3-335
3 Solving PDEs
Generate a fine mesh with a small target maximum element edge length. The resulting mesh has
more than 130000 nodes (degrees of freedom).
generateMesh(model,"Hmax",0.005);
figure
pdemesh(model)
view([0,90])
3-336
Thermal Analysis of Disc Brake
thermalProperties(model,"ThermalConductivity",100, ...
"MassDensity",8000, ...
"SpecificHeat",500);
Specify the boundary conditions. All the faces are exposed to air, so there will be free convection.
thermalBC(model,"Face",1:model.Geometry.NumFaces, ...
"ConvectionCoefficient",10, ...
"AmbientTemperature",30);
Model the moving heat source by using a function handle that defines the thermal load as a function
of space and time. For the definition of the movingHeatSource function, see the Heat Source
Functions section at the bottom of this page.
thermalBC(model,"Face",11,"HeatFlux",@movingHeatSource);
thermalBC(model,"Face",4,"HeatFlux",@movingHeatSource);
thermalIC(model,30);
3-337
3 Solving PDEs
figure("units","normalized","outerposition",[0 0 1 1])
pdeplot3D(model,"ColorMapData",R1.Temperature(:,end))
The animation function visualizes the solution for all time steps. To play the animation, use this
command:
animation(model,R1)
Because the heat diffusion time is much longer than the period of a revolution, you can simplify the
heat source for the long simulation.
Now find the disc temperatures for a longer period of time. Because the heat does not have time to
diffuse during a revolution, it is reasonable to approximate the heat source with a static heat source
in the shape of the path of the brake pad.
Compute the heat flow applied to the disc as a function of time. To do this, use a Simscape Driveline™
model of a four-wheeled, 2000 kg vehicle that brakes from 100 km/h to 0 km/h in approximately 2.75
s.
driveline_model = "DrivelineVehicle_isothermal";
open_system(driveline_model);
3-338
Thermal Analysis of Disc Brake
M = 2000; % kg
V0 = 27.8; % m/s, which is around 100 km/h
P = 277; % bar
simOut = sim(driveline_model);
heatFlow = simOut.simlog.Heat_Flow_Rate_Sensor.Q.series.values;
tout = simOut.tout;
Obtain the time-dependent heat flow by using the results from the Simscape Driveline model.
drvln = struct();
drvln.tout = tout;
drvln.heatFlow = heatFlow;
Generate a mesh.
generateMesh(model);
Specify the boundary condition as a function handle. For the definition of the ringHeatSource
function, see the Heat Source Functions section at the bottom of this page.
thermalBC(model,"Face",11, ...
"HeatFlux",@(r,s)ringHeatSource(r,s,drvln));
thermalBC(model,"Face",4, ...
"HeatFlux",@(r,s)ringHeatSource(r,s,drvln));
3-339
3 Solving PDEs
tlist = linspace(0,5,250);
R2 = solve(model,tlist);
figure("units","normalized","outerposition",[0 0 1 1])
pdeplot3D(model,"ColorMapData",R2.Temperature(:,end))
The animation function visualizes the solution for all time steps. To play the animation, use the
following command:
animation(model,R2)
Find the maximum temperature of the disc. The maximum temperature is low enough to ensure that
the braking pad performs as expected.
Tmax = max(max(R2.Temperature))
Tmax = 52.2895
function F = movingHeatSource(region,state)
% Parameters ---------
3-340
Thermal Analysis of Disc Brake
theta = 2*pi/T*state.time;
xs = xc + R*cos(theta);
ys = yc + R*sin(theta);
x = region.x;
y = region.y;
if isnan(state.time)
F = nan(1,numel(x));
end
end
function F = ringHeatSource(region,state,driveline)
% Parameters ---------
x = region.x;
y = region.y;
if isnan(state.time)
F = nan(1,numel(x));
end
3-341
3 Solving PDEs
if state.time < Tf
rad = sqrt((x - xc).^2 + (y - yc).^2);
end
3-342
Heat Distribution in Circular Cylindrical Rod: PDE Modeler App
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
ρC − ∇ · 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.
Since the problem is axisymmetric, it is convenient to write this equation in a cylindrical coordinate
system.
∂u 1 ∂ ∂u 1 ∂ ∂u ∂ ∂u
ρC − kr − 2 k − k =q
∂t r ∂r ∂r r ∂θ ∂θ ∂z ∂z
Here r, θ, and z are the three coordinate variables of the cylindrical system. Because the problem is
axisymmetric, ∂u/ ∂θ = 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
ρrC − kr − kr = qr
∂t ∂r ∂r ∂z ∂z
∂u
ρyC − ∇ · ky ∇u = qy
∂t
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.
3-343
3 Solving PDEs
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 form n · c ∇u + qu = g, and Dirichlet
boundary conditions must be in the form hu = r. Also, because both sides of the equation are
multiplied by r = y, multiply coefficients for the boundary conditions by y.
• For the left end, use the Neumann condition n · k ∇u = HF_lef t = 5000. Specify g =
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
n · k ∇u = h_outer T _outer − u = 50 100 − u . Specify g = 50*y*100 and q = 50*y.
• The cylinder axis r = 0 is not a boundary in the original problem, but in the 2-D treatment it
has become one. Use the artificial Neumann boundary condition for the axis, n · k ∇u = 0.
Specify g = 0 and q = 0.
3
Specify the coefficients by selecting PDE > PDE Specification or click the 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 Refine the mesh by selecting Mesh > Refine Mesh.
6 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.
7
Solve the equation by selecting Solve > Solve PDE or clicking the button on the toolbar.
8 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-344
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.
• 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-345
3 Solving PDEs
This example shows how to solve the wave equation using the solvepde function.
∂2 u
− ∇ ⋅ ∇u = 0 .
∂t2
To express this in toolbox form, note that the solvepde function solves problems of the form
∂2 u
m − ∇ ⋅ (c ∇u) + au = f .
∂t2
c = 1;
a = 0;
f = 0;
m = 1;
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-346
Wave Equation on Square Domain
specifyCoefficients(model,"m",m,"d",0,"c",c,"a",a,"f",f);
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);
generateMesh(model);
figure
pdemesh(model);
ylim([-1.1 1.1]);
axis equal
xlabel x
ylabel y
3-347
3 Solving PDEs
• πx
u(x, 0) = arctan cos .
2
• ∂u πy
= 3sin(πx)exp sin .
∂t t=0 2
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);
This choice avoids putting energy into the higher vibration modes and permits a reasonable time step
size.
n = 31;
tlist = linspace(0,5,n);
model.SolverOptions.ReportStatistics ='on';
result = solvepde(model,tlist);
3-348
Wave Equation on Square Domain
1 partial derivatives
106 LU decompositions
927 solutions of linear systems
u = result.NodalSolution;
Create an animation to visualize the solution for all time steps. 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 z-
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");
axis([-1 1 -1 1 umin umax]);
xlabel x
ylabel y
zlabel u
M(i) = getframe;
end
3-349
3 Solving PDEs
∂2 u
− Δu = 0
∂t2
To solve this problem in the PDE Modeler app, follow these steps:
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.
7
Specify the coefficients by selecting PDE > PDE Specification or clicking the button on
the toolbar. Select the Hyperbolic type of PDE, and specify c = 1, a = 0, f = 0, and d = 1.
8 Initialize the mesh by selecting Mesh > Initialize Mesh. Refine the mesh by selecting Mesh >
Refine Mesh.
9 Set the solution times. To do this, select Solve > Parameters. Create linearly spaced time vector
from 0 to 5 seconds by setting the solution time to linspace(0,5,31).
10 In the same dialog box, specify initial conditions for the wave equation. For a well-behaved
solution, the initial values must match the boundary conditions. If the initial time is t = 0, then
the following initial values that satisfy the boundary conditions: atan(cos(pi/2*x)) for u(0)
and 3*sin(pi*x).*exp(sin(pi/2*y)) for ∂u/∂t,
The inverse tangent function and exponential function introduce more modes into the solution.
3-350
Wave Equation on Square Domain: PDE Modeler App
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-351
3 Solving PDEs
3-352
Eigenvalues and Eigenmodes of L-Shaped Membrane
This example shows how to calculate eigenvalues and eigenvectors. The eigenvalue problem is
−Δu = λu. This example computes all eigenmodes with eigenvalues smaller than 100.
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);
applyBoundaryCondition(model,"dirichlet", ...
"Edge",1:model.Geometry.NumEdges, ...
"u",0);
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];
generateMesh(model,"Hmax",0.05);
results = solvepdeeig(model,r);
length(results.Eigenvalues)
ans = 19
Plot the first eigenmode and compare it to the MATLAB's membrane function.
u = results.Eigenvectors;
pdeplot(model,"XYData",u(:,1),"ZData",u(:,1));
3-353
3 Solving PDEs
figure
membrane(1,20,9,9)
3-354
Eigenvalues and Eigenmodes of L-Shaped Membrane
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-355
3 Solving PDEs
figure
membrane(12,20,9,9)
3-356
Eigenvalues and Eigenmodes of L-Shaped Membrane
3-357
3 Solving PDEs
–Δ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 L-Shaped Membrane” on page 3-353.
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 by selecting Options > Application.
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 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 = λ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-358
Eigenvalues and Eigenmodes of L-Shaped Membrane: 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 12th
eigenfunction in the specified range.
3-359
3 Solving PDEs
3-360
L-Shaped Membrane with Rounded Corner: PDE Modeler App
–Δu = λu
on an L-shaped membrane with a rounded inner corner. The boundary condition is the Dirichlet
condition u = 0.
To solve this problem in the PDE Modeler app, follow these steps:
1 Draw an L-shaped membrane as a polygon with the corners (0,0), (–1,0), (–1,–1), (1,–1), (1,1), and
(0,1) by using the pdepoly function.
pdecirc(-0.5,0.5,0.5,'C1')
pderect([-0.5 0 0.5 0],'SQ1')
3 Model the geometry with the rounded corner by entering P1+SQ1-C1 in the Set formula field.
4 Check that the application mode is set to Generic Scalar.
5 Remove unnecessary subdomain borders by selecting Boundary > Remove All Subdomain
Borders.
6 Use the default Dirichlet boundary condition u = 0 for all boundaries. To check the boundary
condition, 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.
7
Specify the coefficients by selecting PDE > PDE Specification or clicking the button on
the toolbar. This is an eigenvalue problem, so select the Eigenmodes as the type of PDE. The
general eigenvalue PDE is described by − ∇ ⋅ c ∇u + au = λdu. Thus, for this problem, use the
default coefficients c = 1, a = 0, and d = 1.
8 Specify the maximum edge size for the mesh by selecting Mesh > Parameters. Set the
maximum edge size value to 0.05.
9 Initialize the mesh by selecting Mesh > Initialize Mesh.
10 Specify the eigenvalue range by selecting Solve > Parameters. In the resulting dialog box, use
the default eigenvalue range [0 100].
11
Solve the PDE by selecting Solve > Solve PDE or clicking the button on the toolbar. By
default, the app plots the first eigenfunction as a color plot.
3-361
3 Solving PDEs
3-362
L-Shaped Membrane with Rounded Corner: PDE Modeler App
3-363
3 Solving PDEs
This example shows how to compute the eigenvalues and eigenmodes of a square domain.
The eigenvalue PDE problem is −Δu = λu. 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
Specify the zero Neumann boundary condition for the upper and lower boundary.
applyBoundaryCondition(model,"neumann","Edge",[1,3],"g",0,"q",0);
∂u 3
Specify the generalized Neumann condition − u = 0 for the right boundary.
∂n 4
3-364
Eigenvalues and Eigenmodes of Square
applyBoundaryCondition(model,"neumann","Edge",2,"g",0,"q",-3/4);
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];
generateMesh(model,"Hmax",0.05);
results = solvepdeeig(model,r);
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-365
3 Solving PDEs
pdeplot(model,"XYData",u(:,length(l)));
3-366
Eigenvalues and Eigenmodes of Square
u(x, y) = f (x)g(y) .
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
π2 4π2 9π2
0, , , ,...
4 4 4
It is possible to trace the preceding eigenvalues in the eigenvalues of the solution. Looking at a plot
of the first eigenmode, you can see that it is made up of the first eigenmodes in the x and y directions.
The second eigenmode is made up of the first eigenmode in the x direction and the second eigenmode
in the y direction.
Look at the difference between the first and the second eigenvalue compared to π2 /4:
l(2) - l(1) - pi^2/4
ans = 1.6384e-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 π2:
3-367
3 Solving PDEs
ans = 6.0397e-06
You can explore higher modes by increasing the search range to include eigenvalues greater than 10.
3-368
Eigenvalues and Eigenmodes of Square: PDE Modeler App
The eigenvalue PDE problem is −Δu = λ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
Specify the Neumann condition = 0 for the upper and lower boundary. To do this, specify g
∂n
= 0, q = 0.
• ∂u 3
Specify the generalized Neumann condition − u = 0 for the right boundary. To do this,
∂n 4
specify g = 0, q = -3/4.
4
Specify the coefficients by selecting PDE > PDE Specification or clicking the 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 = λ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.
6 Initialize the mesh by selecting Mesh > Initialize Mesh.
7 Specify the eigenvalue range by selecting Solve > Parameters. In the resulting dialog box,
enter the eigenvalue range as the MATLAB vector [-Inf 10].
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-369
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 last
eigenfunction in the specified range.
3-370
Eigenvalues and Eigenmodes of Square: PDE Modeler App
10 Export the eigenfunctions and eigenvalues to the MATLAB workspace by using the Solve >
Export Solution.
3-371
3 Solving PDEs
This example shows how to calculate the vibration modes of a circular membrane.
The calculation of vibration modes requires the solution of the eigenvalue partial differential
equation. This example compares the solution obtained by using the solvepdeeig solver from
Partial Differential Toolbox™ and the eigs solver from MATLAB®. Eigenvalues calculated by
solvepdeeig and eigs are practically identical, but in some cases one solver is more convenient
than the other. For example, eigs is more convenient when calculating a specified number of
eigenvalues in the vicinity of a particular target value. While solvepdeeig requires that a lower and
upper bound surrounding this target, eigs requires only the target eigenvalue and the desired
number of eigenvalues.
model = createpde;
radius = 2;
g = decsg([1 0 0 radius]','C1',('C1')');
geometryFromEdges(model,g);
figure
pdegplot(model,"EdgeLabels","on")
axis equal
title("Geometry with Edge Labels")
3-372
Vibration of Circular Membrane
c = 1e2;
a = 0;
f = 0;
d = 10;
specifyCoefficients(model,"m",0,"d",d,"c",c,"a",a,"f",f);
Specify that the solution is zero at all four outer edges of the circle.
bOuter = applyBoundaryCondition(model,"dirichlet","Edge",(1:4),"u",0);
Generate a mesh.
generateMesh(model,"Hmax",0.2);
Use assembleFEMatrices to calculate the global finite element mass and stiffness matrices with
boundary conditions imposed using the nullspace approach.
FEMatrices = assembleFEMatrices(model,"nullspace");
K = FEMatrices.Kc;
B = FEMatrices.B;
M = FEMatrices.M;
3-373
3 Solving PDEs
sigma = 1e2;
numberEigenvalues = 5;
[eigenvectorsEigs,eigenvaluesEigs] = eigs(K,M,numberEigenvalues,sigma);
eigenvaluesEigs = diag(eigenvaluesEigs);
Find the largest eigenvalue and its index in the eigenvalues vector.
[maxEigenvaluesEigs,maxIndex] = max(eigenvaluesEigs);
eigenvectorsEigs = B*eigenvectorsEigs;
Now, solve the same eigenvalue problem using solvepdeeig. Set the range for solvepdeeig to be
slightly larger than the range from eigs.
r = [min(eigenvaluesEigs)*0.99 max(eigenvaluesEigs)*1.01];
result = solvepdeeig(model,r);
eigenvectorsPde = result.Eigenvectors;
eigenvaluesPde = result.Eigenvalues;
Both functions calculate the same eigenvalues. For any eigenvalue, you can multiply the eigenvector
by an arbitrary scalar. The eigs and solvepdeeig functions might choose a different arbitrary
scalar for normalizing their eigenvectors.
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-374
Vibration of Circular Membrane
3-375
3 Solving PDEs
To visualize a 2-D scalar PDE solution, you can use the pdeplot function. This function lets you plot
the solution without explicitly interpolating the solution. For example, solve the scalar elliptic
problem − ∇u = 1 on the L-shaped membrane with zero Dirichlet boundary conditions and plot the
solution.
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-376
Solution and Gradient Plots with pdeplot and pdeplot3D
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-377
3 Solving PDEs
ux = results.XGradients;
uy = results.YGradients;
pdeplot(model,"FlowData",[ux,uy])
3-378
Solution and Gradient Plots with pdeplot and pdeplot3D
First, 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-379
3 Solving PDEs
applyBoundaryCondition(model,"dirichlet","Face",4,"u",[0,0]);
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);
generateMesh(model,"Hmax",20);
results = solvepde(model);
u = results.NodalSolution;
pdeplot3D(model,"ColorMapData",u(:,1))
view(-175,4)
title("u(1)")
3-380
Solution and Gradient Plots with pdeplot and pdeplot3D
figure
pdeplot3D(model,"ColorMapData",u(:,2))
view(-175,4)
title("u(2)")
3-381
3 Solving PDEs
Compute the flux of the solution and plot the results for both components.
[cgradx,cgrady,cgradz] = evaluateCGradient(results);
figure
pdeplot3D(model,"FlowData",[cgradx(:,1) cgrady(:,1) cgradz(:,1)])
3-382
Solution and Gradient Plots with pdeplot and pdeplot3D
figure
pdeplot3D(model,"FlowData",[cgradx(:,2) cgrady(:,2) cgradz(:,2)])
3-383
3 Solving PDEs
3-384
2-D Solution and Gradient Plots with MATLAB Functions
You can interpolate the solution and, if needed, its gradient in separate steps, and then plot the
results by using MATLAB® functions, such as surf, mesh, quiver, and so on. For example, solve the
same scalar elliptic problem −Δu = 1 on the L-shaped membrane with zero Dirichlet boundary
conditions. Interpolate the solution and its gradient, and then plot the results.
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,"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-385
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")
Zoom in to see more details. For example, restrict the range to [-0.2,0.2] in each direction.
3-386
2-D Solution and Gradient Plots with MATLAB Functions
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);
set(h2,"Color","r")
axis([-0.2,0.2,-0.2,0.2])
3-387
3 Solving PDEs
figure
mesh(X,Y,uintrp)
xlabel("x")
ylabel("y")
alpha(0.25)
hold on
z = linspace(0,0.15,101);
Z = meshgrid(z);
surf(X,X,Z')
3-388
2-D Solution and Gradient Plots with MATLAB Functions
figure
xq = v;
yq = v;
uintrp = interpolateSolution(results,xq,yq);
plot3(xq,yq,uintrp)
grid on
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-389
3 Solving PDEs
3-390
3-D Solution and Gradient Plots with MATLAB Functions
• 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-391 and “Contour Slices Through 3-D Solution” on page 3-394.
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-398.
• You can use any MATLAB plotting command to create 3-D plots. See “Techniques for Visualizing
Scalar Volume Data” and “Visualizing Vector Volume Data”.
This example shows how to obtain plots from 2-D slices through a 3-D geometry.
The problem is
∂u
− Δu = f
∂t
on a 3-D slab with dimensions 10-by-10-by-1, where u = 0 at time t = 0, boundary conditions are
Dirichlet, and
f x, y, z = 1 + y + 10z2
Define a function for the nonlinear f coefficient in the syntax as given in “f Coefficient for
specifyCoefficients” on page 2-89.
bcMatrix = 1+10*region.z.^2+region.y;
model = createpde;
g = importGeometry(model,"Plate10x10x1.stl");
pdegplot(g,"FaceLabels","on","FaceAlpha",0.5)
3-391
3 Solving PDEs
c = 1;
a = 0;
d = 1;
f = @myfffun;
specifyCoefficients(model,"m",0,"d",d,"c",c,"a",a,"f",f);
applyBoundaryCondition(model,"dirichlet","Face",1:6,"u",0);
setInitialConditions(model,0);
generateMesh(model,"Hmax",0.3);
tlist = 0:0.02:0.2;
results = solvepde(model,tlist);
3-392
3-D Solution and Gradient Plots with MATLAB Functions
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])
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-393
3 Solving PDEs
This example shows how to create contour slices in various directions through a solution in 3-D
geometry.
The problem is to solve Poisson's equation with zero Dirichlet boundary conditions for a complicated
geometry. Poisson's equation is
− ∇ ⋅ ∇u = f .
− ∇ ⋅ ∇(cu) + au = f .
So you can represent the problem by setting c = 1 and a = 0. Arbitrarily set f = 10.
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.
3-394
3-D Solution and Gradient Plots with MATLAB Functions
N = 1;
model = createpde(N);
importGeometry(model,"ForearmLink.stl");
pdegplot(model,"FaceAlpha",0.5)
view(-42,24)
Because the boundary conditions are u = 0 on all faces, the solution u 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.
3-395
3 Solving PDEs
[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));
3-396
3-D Solution and Gradient Plots with MATLAB Functions
colorbar
view(-62,34)
axis equal
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.
For example, interpolate the solution to a grid on the tilted plane 0 ≤ x ≤ 135, 0 ≤ y ≤ 35, and
z = x/10 + y/2. Plot both contours and colored surface data. Use a fine grid, with spacing 0.2.
[X,Y] = meshgrid(0:0.2:135,0:0.2:35);
Z = X/10 + Y/2;
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");
3-397
3 Solving PDEs
axis equal
view(0,90)
title("Colored Plot on Tilted Plane")
xlabel("x")
ylabel("y")
colorbar
This example shows how to calculate the approximate gradients of a solution, and how to use those
gradients in a quiver plot or streamline plot.
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 u(x, y, z) represents the mean time it takes a particle starting at
position (x, y, z) to exit the region.
model = createpde;
importGeometry(model,"Block.stl");
pdegplot(model,"FaceLabels","on","FaceAlpha",0.5)
view(-42,24)
3-398
3-D Solution and Gradient Plots with MATLAB Functions
Set faces 1, 2, and 5 to be the places where the particle can escape. On these faces, the solution
u = 0. Keep the default reflecting boundary conditions on faces 3, 4, and 6.
applyBoundaryCondition(model,"dirichlet","Face",[1,2,5],"u",0);
The PDE is
−Δu = − ∇ ⋅ ∇u = 2
− ∇ ⋅ c ∇u + au = f
c = 1;
a = 0;
f = 2;
specifyCoefficients(model,"m",0,"d",0,"c",c,"a",a,"f",f);
3-399
3 Solving PDEs
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])
ylim([0,20])
zlim([0,50])
axis equal
view(-50,22)
colorbar
3-400
3-D Solution and Gradient Plots with MATLAB Functions
The particle has the largest mean exit time near the point x, y, z = 100, 0, 0 .
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.
[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")
Plot the streamlines of the approximate gradient. Start the streamlines from a sparser set of initial
points.
3-401
3 Solving PDEs
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
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.
3-402
Solve Poisson Equation on Unit Disk Using Physics-Informed Neural Networks
This example shows how to solve the Poisson equation with Dirichlet boundary conditions using a
physics-informed neural network (PINN). You generate the required data for training the PINN by
using the PDE model setup.
The Poisson equation on a unit disk with zero Dirichlet boundary condition can be written as −Δu = 1
in Ω, u = 0 on δΩ, where Ω is the unit disk. The exact solution is
1 − x2 − y2
u(x, y) = .
4
Plot the geometry and display the edge labels for use in the boundary condition definition.
figure
pdegplot(model,EdgeLabels="on");
axis equal
3-403
3 Solving PDEs
applyBoundaryCondition(model,"dirichlet", ...
Edge=1:model.Geometry.NumEdges,u=0);
Create a structural array of coefficients. Specify the coefficients for the PDE model.
pdeCoeffs.m = 0;
pdeCoeffs.d = 0;
pdeCoeffs.c = 1;
pdeCoeffs.a = 0;
pdeCoeffs.f = 1;
specifyCoefficients(model,m=pdeCoeffs.m,d=pdeCoeffs.d, ...
c=pdeCoeffs.c,a=pdeCoeffs.a,f=pdeCoeffs.f);
Generate and plot a mesh with a large number of nodes on the boundary.
To train the PINN, model loss at the collocation points on the domain and boundary. The collocation
points in this example are mesh nodes.
3-404
Solve Poisson Equation on Unit Disk Using Physics-Informed Neural Networks
Define a multilayer perceptron architecture with four fully connected operations, each with 50 hidden
neurons. The first fully connected operation has two input channels corresponding to the inputs x and
y. The last fully connected operation has one output corresponding to u(x,y).
numNeurons = 50;
layers = [
featureInputLayer(2,Name="featureinput")
fullyConnectedLayer(numNeurons,Name="fc1")
tanhLayer(Name="tanh_1")
fullyConnectedLayer(numNeurons,Name="fc2")
tanhLayer(Name="tanh_2")
fullyConnectedLayer(numNeurons,Name="fc3")
tanhLayer(Name="tanh_3")
fullyConnectedLayer(1,Name="fc4")
];
pinn = dlnetwork(layers);
Specify the number of epochs, mini-batch size, initial learning rate, and the learning rate decay.
numEpochs = 50;
miniBatchSize = 500;
initialLearnRate = 0.01;
learnRateDecay = 0.005;
ds = arrayDatastore(domainCollocationPoints);
mbq = minibatchqueue(ds,MiniBatchSize=miniBatchSize, ...
MiniBatchFormat="BC");
averageGrad = [];
averageSqGrad = [];
Calculate the total number of iterations for the training progress monitor.
3-405
3 Solving PDEs
Train PINN
Train the model using a custom training loop. Update the network parameters using the adamupdate
(Deep Learning Toolbox) function. At the end of each iteration, display the training progress.
This training code uses the modelLoss helper function. For more information, see Model Loss
Function on page 3-409.
iteration = 0;
epoch = 0;
learningRate = initialLearnRate;
while epoch < numEpochs && ~monitor.Stop
epoch = epoch + 1;
reset(mbq);
while hasdata(mbq) && ~monitor.Stop
iteration = iteration + 1;
XY = next(mbq);
% Evaluate the model loss and gradients using dlfeval.
[loss,gradients] = dlfeval(@modelLoss,model,pinn,XY,pdeCoeffs);
% Update the network parameters using the adamupdate function.
3-406
Solve Poisson Equation on Unit Disk Using Physics-Informed Neural Networks
[pinn,averageGrad,averageSqGrad] = ...
adamupdate(pinn,gradients,averageGrad, ...
averageSqGrad,iteration,learningRate);
end
% Update learning rate.
learningRate = initialLearnRate / (1+learnRateDecay*iteration);
% Update the training progress monitor.
recordMetrics(monitor,iteration,Loss=loss);
updateInfo(monitor,Epoch=epoch + " of " + numEpochs);
monitor.Progress = 100 * iteration/numIterations;
end
Test PINN
figure;
3-407
3 Solving PDEs
pdeplot(model,XYData=Utrue);
xlabel('$x$',interpreter='latex')
ylabel('$y$',interpreter='latex')
zlabel('$u(x,y)$',interpreter='latex')
title('True Solution: $u(x,y) = (1-x^2-y^2)/4$', ...
interpreter='latex')
nodesDLarry = dlarray(msh.Nodes,"CB");
Upinn = gather(extractdata(predict(pinn,nodesDLarry)));
figure;
pdeplot(model,XYData=Upinn);
xlabel('$x$',interpreter='latex')
ylabel('$y$',interpreter='latex')
zlabel('$u(x,y)$',interpreter='latex')
title(sprintf(['PINN Predicted Solution: ' ...
'L2 Error = %0.1e'],norm(Upinn-Utrue)))
3-408
Solve Poisson Equation on Unit Disk Using Physics-Informed Neural Networks
The modelLoss helper function takes as inputs a dlnetwork object pinn and a mini-batch of input
data XY. The function returns the loss and the gradients of the loss with respect to the learnable
parameters in pinn. To compute the gradients automatically, use the dlgradient (Deep Learning
Toolbox) function. Train the model by enforcing that, given an input (x,y), the output of the network
u(x,y) fulfills the Poisson equation and the boundary conditions.
3-409
3 Solving PDEs
3-410
Reduced-Order Model for Thermal Behavior of Battery
Generate a reduced-order model (ROM) to enable analysis of the spatial thermal behavior of a battery
cell during a fast-charging scenario. You can use the resulting ROM in the “Analyze Battery Spatial
Temperature Variation During Fast Charge” (Simscape Battery) example to analyze the maximum
temperature gradient.
This example first sets up a 3-D thermal analysis model for a Valance:U27_36XP battery in terms of
geometry, material properties, boundary conditions, and initial conditions. Partial Differential
Equation Toolbox™ uses the finite element method (FEM) to discretize the model. FEM models tend
to be very large, typically a few thousand to a million degrees of freedom (DoFs). Such large models
are not ideal for integration into system-level modeling environments. You can reduce the finite-
element model to a ROM, a much smaller system with tens to hundreds DoFs. This example uses
eigenvalue decomposition or modal analysis to create a ROM. The example also adds other data
required for Simscape analysis.
3-411
3 Solving PDEs
Battery Geometry
The battery model has four main prismatic subdomains of different materials. To construct a
prismatic geometry, extrude a 2-D cross section using key geometric dimensions. The
sscv_createCellGeometry helper function takes cell dimensions as input and creates a 3-D
geometry for the cell. The resulting geometry consists of a jelly roll, outer casing, and positive-
negative cell tabs.
[gm3D,IDX] = sscv_createCellGeometry(cell_width_mm, ...
cell_thickness_mm, ...
cell_height_mm, ...
cellCasing_thickness_mm, ...
cellTab_height_mm, ...
cellTab_radius_mm, ...
false);
3-412
Reduced-Order Model for Thermal Behavior of Battery
model = createpde("thermal","modal");
model.Geometry = gm3D;
The battery cell has four subdomains with different material properties. Create a string vector with
identifiers for each subdomain of the cell.
cellDomains = ["Jelly","PositiveTab","NegativeTab","Casing"];
Specify the thermal conductivity, specific heat, and mass density for each subdomain. The jelly roll
has an orthotropic thermal conductivity, with a large in-plane conductivity of 80 W/(K*m) and a small
through-plane conductivity of 2 W/(K*m).
cellThermalCond.inPlane = 80;
cellThermalCond.throughPlane = 2;
tabThermalCond = 386;
casingThermalCond = 50;
thermalConductivity.Jelly = [cellThermalCond.throughPlane
cellThermalCond.inPlane
cellThermalCond.inPlane];
thermalConductivity.PositiveTab = tabThermalCond;
thermalConductivity.NegativeTab = tabThermalCond;
thermalConductivity.Casing = casingThermalCond;
spHeat.Jelly = 785;
spHeat.PositiveTab = 890;
spHeat.NegativeTab = 385;
spHeat.Casing = 840;
density.Jelly = 780;
density.PositiveTab = 2700;
density.NegativeTab = 8830;
density.Casing = 540;
3-413
3 Solving PDEs
Reduced-Order Model
Solve the modal analysis problem, and use the modal results to reduce the thermal model.
rom =
ReducedThermalModel with properties:
K: [15x15 double]
M: [15x15 double]
F: [15x1 double]
InitialConditions: [15x1 double]
Mesh: [1x1 FEMesh]
ModeShapes: [14566x15 double]
The output rom contains a smaller-sized system to use in Simscape™ system-level modeling. In
addition to ROM, defining a control loop requires additional data to couple the ROM with Simscape
elements. The following sections create all the relevant data and populate a pde_rom structure array
with it.
The generated ROM does not include a load or boundary conditions. The Simscape Battery™ loop
computes the heat generation loads and boundary loss. To apply these loads and losses on the ROM,
use unit load vectors and scale them by using scaling factors calculated from the Simscape Battery
libraries. These full-length scaled load vectors with a size equal to the finite-element model DoFs are
projected to reduce loads to ROM space by using the transformation matrix available in the ROM.
The reduced load vectors drive the ROM dynamics.
All battery boundaries are adiabatic, except for the bottom surface where a cooling load is applied
using a thermal resistance. To generate independent load vectors for all controlled loads, apply a unit
loading for each controlled load and then extract the corresponding load vector. The negative sign
indicates the flux directed out of the battery system.
thermalBC(model,HeatFlux=-1,Face=IDX.("cooledFaceID"));
Assemble the finite boundary load vector corresponding to the cooled face by using
assembleFEMatrices.
mats = assembleFEMatrices(model,"G");
boundaryLoad_full = full(mats.G);
3-414
Reduced-Order Model for Thermal Behavior of Battery
In the Simscape model used in “Analyze Battery Spatial Temperature Variation During Fast Charge”
(Simscape Battery), control logic is based on temperature probed at a few spatial locations. These
spatial locations are representative of typical locations of thermocouples in a physical setup. All the
thermocouple locations are defined on the top surface, with tabs, of the battery. You can choose the
temperature from one thermocouple, a subset of thermocouples, or the average temperature across
the battery to define the control.
For simplicity, assume that each thermocouple location coincides with a mesh node, and therefore,
you can use node IDs to index into the temperature vector of the solution. Identify node IDs using the
coordinates of a thermocouple location.
Compute the spatial coordinates of three equally spaced thermocouples. First, compute the geometric
bounding box and compute its mean.
boundingBox = [min(model.Geometry.Vertices);
max(model.Geometry.Vertices)];
boundingBox_mean = mean(boundingBox);
Find the nearest finite element mesh node for each of the thermocouple locations.
thermocouples.probeNodeIDs = ...
model.Mesh.findNodes(nearest=thermocouples.probe_locations);
thermocouples.numOfTempProbes = ...
numel(thermocouples.probeNodeIDs);
The ROM solution is defined in terms of reduced DoFs. For plotting purposes, add a submatrix W of
rom.TransformationMatrix that generates the temperature-time history for the nodes
corresponding to thermocouple locations.
thermocouples.W = ...
rom.TransformationMatrix(thermocouples.probeNodeIDs,:);
Define the cell thermal mass required in the Battery (Table-Based) library component.
cellThermalMass = 0;
for domain = cellDomains
3-415
3 Solving PDEs
volume.(domain) = ...
model.Mesh.volume(model.Mesh.findElements("region", ...
Cell=IDX.(domain)));
cellThermalMass = ...
cellThermalMass + ...
volume.(domain).*density.(domain).*spHeat.(domain);
end
Add all the remaining required data to the pde_rom structure array.
pde_rom.prop.initialTemperature = T0;
Add the weld resistance value of the battery cell tabs, in ohm.
pde_rom.prop.cellTab_weldR = 7.5e-4;
pde_rom.prop.cell_width_mm = cell_width_mm;
pde_rom.prop.cell_thickness_mm = cell_thickness_mm;
pde_rom.prop.cell_height_mm = cell_height_mm;
pde_rom.prop.cellCasing_thickness_mm = cellCasing_thickness_mm;
pde_rom.prop.cellTab_height_mm = cellTab_height_mm;
pde_rom.prop.cellTab_radius_mm = cellTab_radius_mm;
pde_rom.Geometry = model.Geometry;
pde_rom.prop.volume = volume;
pde_rom.prop.cellThermalCond.inPlane = cellThermalCond.inPlane;
pde_rom.prop.cellThermalCond.throughPlane = ...
cellThermalCond.throughPlane;
pde_rom.prop.tabThermalCond = tabThermalCond;
pde_rom.prop.casingThermalCond = casingThermalCond;
pde_rom.prop.thermalConductivity = thermalConductivity;
pde_rom.prop.density = density;
pde_rom.prop.spHeat = spHeat;
pde_rom.prop.cellThermalMass = cellThermalMass;
pde_rom.Q.boundaryLoad_full = boundaryLoad_full;
pde_rom.Q.heatGenUnit_full = heatGenUnit_full;
pde_rom.Q.heatGenUnitPosTab_full = heatGenUnitPosTab_full;
pde_rom.Q.heatGenUnitNegTab_full = heatGenUnitNegTab_full;
pde_rom.thermocouples = thermocouples;
3-416
Reduced-Order Model for Thermal Behavior of Battery
pde_rom.rom = rom
Save the struct array to a MAT-file. You can use the resulting MAT-file in Simscape Battery to
analyze the battery temperature gradient during fast charging. Using the MAT-file does not require
Partial Differential Equation Toolbox.
3-417
3 Solving PDEs
This example shows how to perform a battery cooling analysis determine the effect of a cooling
system. In addition, this example generates a reduced-order model (ROM) for the battery module. You
can use the resulting ROM in a system-level model in Simscape™.
cellWidth = 150/1000;
cellThickness = 15/1000;
tabThickness = 10/1000;
tabWidth = 15/1000;
cellHeight = 100/1000;
tabHeight = 5/1000;
connectorHeight = 3/1000;
numCellsInModule = 20;
Create the geometry of the battery module by using the supporting function
createBatteryModuleGeometry, which is provided in a supporting file.
[geomModule,volumeIDs,boundaryIDs,volume,area,ReferencePoint] = ...
createBatteryModuleGeometry(numCellsInModule, ...
cellWidth, ...
cellThickness, ...
tabThickness, ...
tabWidth, ...
cellHeight, ...
tabHeight, ...
connectorHeight);
pdegplot(geomModule)
3-418
Battery Module Cooling Analysis and Reduced-Order Thermal Model
3-419
3 Solving PDEs
Create a thermal model for transient analysis, and assign the battery module geometry to the model.
model = createpde("thermal","transient");
model.Geometry = geomModule;
generateMesh(model);
pdemesh(model)
3-420
Battery Module Cooling Analysis and Reduced-Order Thermal Model
cellIDs = [volumeIDs.Cell];
tabIDs = [volumeIDs.TabLeft,volumeIDs.TabRight];
connectorIDs = [volumeIDs.ConnectorLeft,volumeIDs.ConnectorRight];
bottomPlateFaces = [boundaryIDs.BottomFace];
cellThermalCond.inPlane = 80;
cellThermalCond.throughPlane = 2;
tabThermalCond = 386;
connectorThermalCond = 400;
density.Cell = 780;
density.TabLeft = 2700;
density.TabRight = 2700;
density.ConnectorLeft = 540;
density.ConnectorRight = 540;
spHeat.Cell = 785;
spHeat.TabLeft = 890;
spHeat.TabRight = 890;
3-421
3 Solving PDEs
spHeat.ConnectorLeft = 840;
spHeat.ConnectorRight = 840;
Assign the thermal material properties of the cell body, tabs, and connectors.
thermalProperties(model,Cell=cellIDs, ...
ThermalConductivity=[cellThermalCond.throughPlane
cellThermalCond.inPlane
cellThermalCond.inPlane], ...
MassDensity=density.Cell, ...
SpecificHeat=spHeat.Cell);
thermalProperties(model,Cell=tabIDs, ...
ThermalConductivity=tabThermalCond, ...
MassDensity=density.TabLeft, ...
SpecificHeat=spHeat.TabLeft);
thermalProperties(model,Cell=connectorIDs, ...
ThermalConductivity=connectorThermalCond, ...
MassDensity=density.ConnectorLeft, ...
SpecificHeat=spHeat.ConnectorLeft);
Tambient = 293;
First, simulate the module with only natural convection cooling applied at the front and back faces of
the module.
thermalBC(model, ...
Face=[boundaryIDs(1).FrontFace,boundaryIDs(end).BackFace], ...
ConvectionCoefficient=15, ...
AmbientTemperature=Tambient);
Apply nominal heat generation. Assume that the heat generation during normal operation is 15 W.
nominalHeatGen = 15/volume(1).Cell;
internalHeatSource(model,nominalHeatGen,Cell=cellIDs);
For a faulty cell, specify a higher heat generation value, for example, 25 W.
faultCellHeatGen = 25/volume(10).Cell;
internalHeatSource(model,faultCellHeatGen,Cell=volumeIDs(10).Cell);
Specify the initial conditions, and solve the problem for 2 hours of operation.
thermalIC(model,Tambient);
R = solve(model,0:60:7200);
pdeplot3D(model.Mesh,ColorMapData=R.Temperature(:,end))
title("Transient Simulation Without Bottom Cooling")
3-422
Battery Module Cooling Analysis and Reduced-Order Thermal Model
Include the cooling effect on the bottom faces of the module, and solve the problem again.
thermalBC(model,Face=bottomPlateFaces, ...
ConvectionCoefficient=100, ...
AmbientTemperature=Tambient);
R = solve(model,0:60:7200);
Plot the temperature at the end of the simulation with bottom cooling.
figure
pdeplot3D(model.Mesh,ColorMapData=R.Temperature(:,end))
title("Transient Simulation with Bottom Cooling")
3-423
3 Solving PDEs
model.AnalysisType = "modal";
Solve for modes of the thermal model in the specified decay range.
Rm = solve(model,DecayRange=[-Inf,5e-2]);
figure
pdeplot3D(model.Mesh,ColorMapData=Rm.ModeShapes(:,1))
title("Mode 1")
3-424
Battery Module Cooling Analysis and Reduced-Order Thermal Model
The output rom contains a smaller-sized system to use in Simscape system-level modeling. In addition
to the ROM, defining a control loop requires other data to couple the ROM with Simscape elements.
The following sections create all the relevant data and populate a pde_rom structure array with it.
The Simscape Battery™ loop computes the heat generation loads and boundary loss. To apply these
loads and losses on the ROM, use unit load vectors and scale them by using scaling factors calculated
from the Simscape Battery libraries. These full-length scaled load vectors with a size equal to the
finite-element model degrees of freedom (DoFs) are projected to reduce load to the ROM space by
using the transformation matrix available in the ROM. The reduced load vector drives the ROM
dynamics.
3-425
3 Solving PDEs
heatLoadUnit_bottomFaces = ...
sscv_unitBCBatteryROM(model,bottomPlateFaces);
Define the cell thermal mass required in the Battery (Table-Based) library component.
cellThermalMass = zeros(1,numCellsInModule);
for domain = ["Cell","TabLeft","TabRight", ...
"ConnectorLeft","ConnectorRight"]
cellThermalMass = cellThermalMass + ...
[volume.(domain)].*[density.(domain)].*[spHeat.(domain)];
end
The thermocouples are attached to the center of the top surface of the cells. Define spatial
coordinates of thermocouples by using reference point coordinates, for the center of the cells.
refPointTopFaceCell1 = ...
ReferencePoint.Cell + [0,0,cellHeight/2];
thermocouples.probe_locations = ...
repmat(refPointTopFaceCell1,numCellsInModule,1);
thermocouples.probe_locations(:,1) = ...
ReferencePoint.Cell(1):-cellThickness:0;
Use these coordinates to find the associated nearest node IDs of the finite-element mesh.
thermocouples.probeNodeIDs = ...
model.Mesh.findNodes("nearest",thermocouples.probe_locations');
thermocouples.numOfTempProbes = ...
numel(thermocouples.probeNodeIDs);
The ROM solution is defined using the reduced DoFs. To recover the solution in terms of physical
temperatures DoFs, use the function reconstructSolution. For plotting purposes, create a
submatrix W of rom.TransformationMatrix that can be used to generate the temperature-time
history for the nodes corresponding to thermocouple locations.
thermocouples.W = ...
rom.TransformationMatrix(thermocouples.probeNodeIDs,:);
Create the pde_rom structure array with all the data needed for a Simscape model. First, add the
initial temperature of the battery, in K.
pde_rom.prop.initialTemperature = Tambient;
pde_rom.numCellsInModule = numCellsInModule;
pde_rom.prop.cell_width_mm = cellWidth;
pde_rom.prop.cell_thickness_mm = cellThickness;
pde_rom.prop.cell_height_mm = cellHeight;
pde_rom.prop.tabWidth_mm = tabWidth;
pde_rom.prop.tabThickness_mm = tabThickness;
pde_rom.prop.connectorHeight_mm = connectorHeight;
pde_rom.Geometry = model.Geometry;
3-426
Battery Module Cooling Analysis and Reduced-Order Thermal Model
pde_rom.volume = volume;
pde_rom.area = area;
Add the thermal load matrices. The heatGenUnit_cells and heatLoadUnit_bottomFaces fields
contain load matrices, with each column of a matrix corresponding to a cell in the module. The
heatGenUnit_tabs and heatGenUnit_connector fields contain load vectors for both the positive
and negative ends for each cell.
pde_rom.Q.heatGenUnit_cells = ...
sscv_unitHeatLoadBatteryROM(model,cellIDs);
pde_rom.Q.heatGenUnit_tabs = ...
sscv_unitHeatLoadBatteryROM(model,tabIDs');
pde_rom.Q.heatGenUnit_connector = ...
sscv_unitHeatLoadBatteryROM(model,connectorIDs');
pde_rom.Q.heatLoadUnit_bottomFaces = ...
sscv_unitBCBatteryROM(model,bottomPlateFaces);
Helper Functions
3-427
3 Solving PDEs
F(:,i) = mats.F;
end
end
function G = sscv_unitBCBatteryROM(model,boundaryIDs)
% Assign zero globally.
G = zeros(size(model.Mesh.Nodes,2),numel(boundaryIDs));
bchandle = thermalBC(model,HeatFlux=-1,Face=1);
for i = 1:numel(boundaryIDs)
% Assign negative heat flux specified boundary
bchandle.RegionID = boundaryIDs(i);
% Assemble the load vector
mats = assembleFEMatrices(model,"G");
G(:,i) = mats.G;
end
end
3-428
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.
solvepdeeig returns an EigenResults object whose properties contain the solution eigenvectors
calculated at the mesh nodes. You can interpolate the solution to other points by using
interpolateSolution.
The dimensions of the solution, its gradient, and flux of the solution depend on:
• For results returned by solvepde or solvepdeeig, this is the number of mesh nodes.
• For results returned by interpolateSolution,evaluateGradient, and
evaluateCGradient this is the number of query points.
• The number of equations.
• For results returned by solvepde or solvepdeeig, this is the number of equations in the
system.
• For results returned by interpolateSolution,evaluateGradient, and
evaluateCGradient, this is the number of query equation indices.
• The number of times for a time-dependent problem or number of modes for an eigenvalue
problem.
• 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-429
3 Solving PDEs
3-430
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)
System, N > 1 result.NodalSolution(iP,iN) Np-by-N Nqp-by-N
result.XGradients(iP,iN)
result.YGradients(iP,iN)
result.ZGradients(iP,iN)
3-431
3 Solving PDEs
result.XGradients(iP,iT)
result.YGradients(iP,iT)
result.ZGradients(iP,iT)
System, N > 1 result.NodalSolution(iP,iN,iT) Np-by-N-by-Nt Nqp-by-Nq-by-Nqt
result.XGradients(iP,iN,iT)
result.YGradients(iP,iN,iT)
result.ZGradients(iP,iN,iT)
See Also
solvepde | solvepdeeig | interpolateSolution | evaluateGradient | StationaryResults
| TimeDependentResults | EigenResults
3-432
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:
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)
4-3
4 PDE Modeler App
Rotate Shapes
To rotate a shape:
1 Select the shapes.
2 Select Rotate from the Draw menu.
3 In the resulting Rotate dialog box, enter the rotation angle in degrees. To rotate
counterclockwise, use positive values of rotation angles. To rotate clockwise, use negative values.
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
4-4
2-D Geometry Creation in PDE Modeler App
dialog box lets you change the name and parameters of the selected shape. The name cannot contain
spaces.
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-5
4 PDE Modeler App
To add axis grid, the snap-to-grid feature, and zoom, use the Options menu. To adjust the grid
spacing:
• Specify the grid spacing for the x-axis and y-axis. For example, change the linear spacing for the x-
axis to -1.5:0.2:1.5.
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-6
2-D Geometry Creation in PDE Modeler App
4-7
4 PDE Modeler App
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.
4-8
2-D Geometry Creation in PDE Modeler App
7 Add four squares with the side 0.2, one in each corner.
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-9
4 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-10
2-D Geometry Creation in PDE Modeler App
4-11
4 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:
• Generalized Neumann conditions, where the boundary condition is determined by the coefficients
q and g according to the following equation:
n · c ∇u + qu = g .
The following figure shows the dialog box for the generic system PDE (Options > Application >
Generic System).
4-12
Specify Boundary Conditions in the PDE Modeler App
For boundary condition entries you can use the following variables in a valid MATLAB expression:
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.
In the nongeneric application modes, the Description column contains descriptions of the physical
interpretation of the boundary condition parameters.
4-13
4 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
• 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.
4-14
Specify Coefficients in PDE Modeler App
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)
• 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:
4-15
4 PDE Modeler App
∂u 1.1 cos(xy)
−∇· ∇u = 10.
∂t cos(xy) 5.5
Enter character expressions for coefficients using the form in “Coefficients for Scalar PDEs” on page
4-14, with additional options for nonlinear equations. The additional options are:
4-16
Specify Coefficients in PDE Modeler App
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)
For example, these expressions show one of each type (1-, 2-, 3-, and 4-element expressions)
4-17
4 PDE Modeler App
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)
∂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:
10t 0 ≤ t ≤ 0.1
f = 10 * 1 0.1 ≤ t ≤ 0.9
10 − 10t 0.9 ≤ t ≤ 1
• c = 1 +.x2 + y2
To solve this equation in the PDE Modeler app, follow these steps:
4-18
Specify Coefficients in PDE Modeler App
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;
2 Open the PDE Modeler app by using the pdeModeler command.
3 Display grid lines by selecting Options > Grid.
4 Align new shapes to the grid lines by selecting Options > Snap.
5 Draw a rectangle with the corners at (-1,-0.4), (-1,0.4), (1,0.4), and (1,-0.4). To do this, first click
the button. Then click one of the corners using the left mouse button and drag to draw a
rectangle.
6
Draw a circle with the radius 0.2 and the center at (0.5,0). To do this, first click the 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.
7 Model the geometry by entering R1-C1 in the Set formula field.
4-19
4 PDE Modeler App
• For the rectangle, use the Dirichlet boundary condition with h = 1 and r = t*(x-y).
• For the circle, use the Neumann boundary condition with g = x.^2+y.^2 and q = 1.
10
Specify the coefficients by selecting PDE > PDE Specification or clicking the button on
the toolbar. Select the Parabolic type of PDE. Specify c = 1+x.^2+y.^2, a = 0, f =
framp(t), and d = 5.
Note Do not include quotes or spaces when you specify your coefficients the PDE Modeler app.
The parser interprets all inputs as vectors of characters. It can misinterpret a space as a vector
separator, as when a MATLAB vector uses a space to separate elements of a vector.
11 Initialize the mesh by selecting Mesh > Initialize Mesh.
12 Refine the mesh twice by selecting Mesh > Refine Mesh.
13 Improve the triangle quality by selecting Mesh > Jiggle Mesh.
4-20
Specify Coefficients in PDE Modeler App
14 Set the initial value and the solution time. To do this, select Solve > Parameters.
In the resulting dialog box, set the time to linspace(0,1,50) and the initial value u(t0) to 0.
15
Solve the equation by selecting Solve > Solve PDE or clicking the button on the toolbar.
4-21
4 PDE Modeler App
4-22
Specify Coefficients in PDE Modeler App
4-23
4 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.
4-24
Specify Mesh Parameters in the PDE Modeler App
• 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-25
4 PDE Modeler App
selecting Solve PDE from the Solve menu or by clicking the button.
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-26
Adjust Solve Parameters in the PDE Modeler App
• Triangle selection method. There are two triangle selection methods, described below. You can
also supply your own function.
• 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” on page 3-294 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-24.
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:
Note The adaptive mode and the nonlinear solver can be used together.
4-27
4 PDE Modeler App
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-28
Adjust Solve Parameters in the 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.
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.
4-29
4 PDE Modeler App
Nonlinear Equations
Before solving a nonlinear elliptic PDE in the PDE Modeler app, select SolveParameters. Then select
Use nonlinear solver and click OK.
4-30
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-31
4 PDE Modeler App
the 3-D plot is simply a mesh plot. You can visualize another scalar property simultaneously
using Color and/or Contour, which results in a 3-D surface or contour plot.
• Animation. Animation of time-dependent solutions to parabolic and hyperbolic problems. If
you select this option, the solution is recorded and then animated in a separate figure window
using the MATLAB movie function.
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:
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.
4-32
Plot the Solution in the PDE Modeler App
• 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
• Interpolated shading. A surface plot using the selected colormap and interpolated shading,
i.e., each triangular area is colored using a linear, interpolated shading (the default).
• Flat shading. A surface plot using the selected colormap and flat shading, i.e., each triangular
area is colored using a constant color.
• Proportional. The length of the arrow corresponds to the magnitude of the property that you
visualize (the default).
• Normalized. The lengths of all arrows are normalized, i.e., all arrows have the same length.
This is useful when you are interested in the direction of the vector field. The direction is
clearly visible even in areas where the magnitude of the field is very small.
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.
For the parabolic and hyperbolic PDEs, the bottom right portion of the Plot Selection dialog box
contains the Time for plot parameter.
4-33
4 PDE Modeler App
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-34
Plot the Solution in the PDE Modeler App
For eigenvalue problems, the bottom right part of the dialog box contains a drop-down 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.
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
Functions
5 Functions
Description
The Visualize PDE Results task enables you to plot and inspect results of structural, thermal,
electromagnetic, or general PDE analysis using interactive controls. The task automatically generates
MATLAB code for your live script.
For general information about Live Editor tasks, see “Add Interactive Tasks to a Live Script”.
5-2
Visualize PDE Results
• On the Live Editor tab, select Task > Visualize PDE Results.
• In a code block in the script, type a relevant keyword, such as pde. Select Visualize PDE Results
from the suggested command completions.
Examples
Use the Visualize PDE Results task in the Live Editor to explore structural modal analysis results of a
tuning fork. Open this example to see a preconfigured script containing the Visualize PDE Results
task.
Find natural frequencies and mode shapes for the fundamental mode of a tuning fork and the next
several modes. To perform unconstrained modal analysis of a structure, you can specify just the
geometry, mesh, and material properties.
model = createpde("structural","modal-solid");
importGeometry(model,"TuningFork.stl");
structuralProperties(model,"YoungsModulus",210e9, ...
"PoissonsRatio",0.3, ...
"MassDensity",8000);
generateMesh(model,"Hmax",0.001);
RF = solve(model,"FrequencyRange",[-1,4000]*2*pi);
To visualize mode shapes, open the Visualize PDE Results Live Editor task. On the Live Editor tab,
select Task > Visualize PDE Results. This action inserts the task into your script.
In the Select results section of the task, select RF from the drop-down list. 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 the 3-D tuning fork. The first flexible mode is
the seventh mode with a frequency of about 460 Hz.
5-3
5 Functions
The best way to visualize mode shapes is to animate the harmonic motion at their respective
frequencies. Select Animate to see the harmonic motion at a frequency of about 460 Hz.
5-4
Visualize PDE Results
5-5
5 Functions
Parameters
Select results — Results to plot
structural results | thermal results | electromagnetic results | general PDE results
Choose the results to plot from the structural, thermal, electromagnetic, and general PDE results
available in the MATLAB workspace. You can select only one solution at a time. The solution must be
specified as one of these objects:
Choose the part of the solution to plot, such as a displacement for a structural problem, temperature
for a thermal problem, or electric field for an electrostatic problem.
Choose to plot the x-, y-, or z-component of a solution such as displacement, stress, temperature
gradient, electric field, or magnetic field.
5-6
Visualize PDE Results
Choose the time to plot results for. The slider values correspond to the times that you used when
solving the problem.
Choose the phase to plot results for. The slider values are from 0 to 2π.
Switch between deformed and undeformed shapes for a 3-D structural model. In an undeformed
shape, center nodes in quadratic meshes are always added at the halfway point between corners.
When you plot a deformed shape, the center nodes can move away from the edge centers.
5-7
5 Functions
Set the colormap limits. The default mapping is useful in most cases, but you can perform the
mapping over any range you choose, even if the range you choose is different than the range of your
data. Choosing a different mapping range allows you to:
Adjust the surface transparency by moving the slider between None, Medium, and High.
Version History
Introduced in R2022b
See Also
pdeplot | pdeplot3D | pdegplot | pdemesh | pdeviz
Topics
“Deflection Analysis of Bracket” on page 3-74
“Thermal Deflection of Bimetallic Beam” on page 3-123
“Modal and Frequency Response Analysis for Single Part of Kinova Gen3 Robotic Arm” on page 3-39
“Finite Element Analysis of Electrostatically Actuated MEMS Device” on page 3-59
“Temperature Distribution in Heat Sink” on page 3-238
“Minimal Surface Problem” on page 3-286
5-8
femodel
femodel
Finite element analysis model object
Description
An femodel object contains information about a finite element problem: analysis type, geometry,
material properties, boundary conditions, loads, initial conditions, and other parameters.
Creation
Syntax
model = femodel(AnalysisType=analysistype)
model = femodel(AnalysisType=geometry,Geometry=Geometry)
Description
Input Arguments
5-9
5 Functions
Geometry description, specified as an fegeometry object. This argument sets the “Geometry” on
page 5-0 property.
Properties
AnalysisType — Type of problem
"structuralStatic" | "structuralModal" | "structuralTransient" |
"structuralFrequency" | "thermalSteady" | "thermalModal" | "thermalTransient" |
"electrostatic" | "magnetostatic" | "electricHarmonic" | "magneticHarmonic" |
"dcConduction"
Geometry description, specified as an fegeometry object. This property is set by the geometry on
page 5-0 input argument.
5-10
femodel
Boundary conditions on geometry faces, specified as a 1-by-N array of faceBC objects. Here, N is the
number of faces in a geometry. Each faceBC object contains boundary conditions for one face of the
geometry.
Boundary conditions on geometry edges, specified as a 1-by-N array of edgeBC objects. Here, N is the
number of edges in a geometry. Each edgeBC object contains boundary conditions for one edge of the
geometry.
Boundary conditions on geometry vertices, specified as a 1-by-N array of vertexBC objects. Here, N
is the number of vertices in a geometry. Each vertexBC object contains boundary conditions for one
vertex of the geometry.
Settings for modeling thermal radiation between surfaces without conductive media, specified as a
surfaceToSurfaceSettings object. The default empty value results in the surface-to-ambient
solution.
Loads
Loads on geometry cells, specified as a 1-by-N array of cellLoad objects. Here, N is the number of
cells in a geometry. Each cellLoad object contains loads for one cell of the geometry.
Loads on geometry faces, specified as a 1-by-N array of faceLoad objects. Here, N is the number of
faces in a geometry. Each faceLoad object contains loads for one face of the geometry.
Loads on geometry edges, specified as a 1-by-N array of edgeLoad objects. Here, N is the number of
edges in a geometry. Each edgeLoad object contains loads for one edge of the geometry.
Loads on geometry vertices, specified as a 1-by-N array of vertexLoad objects. Here, N is the
number of vertices in a geometry. Each vertexLoad object contains loads for one vertex of the
geometry.
Initial Conditions
5-11
5 Functions
Initial conditions on geometry cells, specified as a 1-by-N array of cellIC objects. Here, N is the
number of cells in a geometry. Each cellIC object contains initial conditions for one cell of the
geometry.
Initial conditions on geometry faces, specified as a 1-by-N array of faceIC objects. Here, N is the
number of faces in a geometry. Each faceIC object contains initial conditions for one face of the
geometry.
Initial conditions on geometry edges, specified as a 1-by-N array of edgeIC objects. Here, N is the
number of edges in a geometry. Each edgeIC object contains initial conditions for one edge of the
geometry.
Initial conditions on geometry vertices, specified as a 1-by-N array of vertexIC objects. Here, N is
the number of vertices in a geometry. Each vertexIC object contains initial conditions for one vertex
of the geometry.
Other Parameters
Reference temperature for a thermal load, specified as a real number. The reference temperature
corresponds to the state of zero thermal stress of the model. The value 0 implies that the thermal
load is specified in terms of the temperature change and its derivatives.
To specify the reference temperature for a thermal load in your model, assign the property value
directly, for example, model.ReferenceTemperature = 10. To specify the thermal load itself, use
cellLoad.
Data Types: double
5-12
femodel
Algorithm options for the PDE solvers, specified as a PDESolverOptions object. The properties of
PDESolverOptions include absolute and relative tolerances for internal ODE solvers, maximum
solver iterations, and so on. For a complete list of properties, see PDESolverOptions.
Constants
Permittivity of vacuum for the entire model, specified as a positive number. This value must be
consistent with the units of the model. If the model parameters are in the SI system of units, then the
permittivity of vacuum must be 8.8541878128e-12.
Data Types: double
Permeability of vacuum for the entire model, specified as a positive number. This value must be
consistent with the units of the model. If the model parameters are in the SI system of units, then the
permeability of vacuum must be 1.2566370614e-6.
• SI —5.670367e-8 W/(m2·K4)
• CGS— 5.6704e-5 erg/(cm2·s·K4)
• US customary — 1.714e-9 BTU/(hr·ft2·R4)
Object Functions
generateMesh Create triangular or tetrahedral mesh
pdegplot Plot PDE geometry
pdemesh Plot PDE mesh
solve Solve structural analysis, heat transfer, or electromagnetic analysis problem
Examples
model = femodel(AnalysisType="thermalTransient")
model =
1x1 femodel array
5-13
5 Functions
AnalysisType: "thermalTransient"
Geometry: [0x0 fegeometry]
PlanarType: ""
MaterialProperties: [0x0 materialProperties]
Boundary Conditions
FaceBC: [0x0 faceBC]
EdgeBC: [0x0 edgeBC]
VertexBC: [0x0 vertexBC]
ThermalRadiation: []
Loads
CellLoad: [0x0 cellLoad]
FaceLoad: [0x0 faceLoad]
EdgeLoad: [0x0 edgeLoad]
VertexLoad: [0x0 vertexLoad]
Initial Conditions
CellIC: [0x0 cellIC]
FaceIC: [0x0 faceIC]
EdgeIC: [0x0 edgeIC]
VertexIC: [0x0 vertexIC]
Other Parameters
DampingAlpha: 0
DampingBeta: 0
ReferenceTemperature: []
SolverOptions: [1x1 pde.PDESolverOptions]
Constants
StefanBoltzmann: []
Create an femodel object for solving a static structural problem, and assign a 2-D geometry to the
model.
model =
1x1 femodel array
AnalysisType: "structuralStatic"
Geometry: [1x1 fegeometry]
PlanarType: "planeStress"
5-14
femodel
Boundary Conditions
FaceBC: [0x1 faceBC]
EdgeBC: [0x5 edgeBC]
VertexBC: [0x5 vertexBC]
Loads
FaceLoad: [0x1 faceLoad]
EdgeLoad: [0x5 edgeLoad]
VertexLoad: [0x5 vertexLoad]
Other Parameters
ReferenceTemperature: []
SolverOptions: [1x1 pde.PDESolverOptions]
By default, femodel assumes that a 2-D problem is a plane-stress problem. Specify the plane-strain
problem type.
model.PlanarType = "planeStrain";
model.PlanarType
ans =
"planeStrain"
gm = multicuboid(0.5,0.1,0.1);
pdegplot(gm,FaceAlpha=0.5, ...
FaceLabels="on", ...
EdgeLabels="on")
5-15
5 Functions
Create an femodel object for solving a static structural problem, and assign the geometry to the
model.
model = femodel(AnalysisType="structuralStatic", ...
Geometry=gm)
model =
1x1 femodel array
AnalysisType: "structuralStatic"
Geometry: [1x1 fegeometry]
MaterialProperties: [0x1 materialProperties]
Boundary Conditions
FaceBC: [0x6 faceBC]
EdgeBC: [0x12 edgeBC]
VertexBC: [0x8 vertexBC]
Loads
CellLoad: [0x1 cellLoad]
FaceLoad: [0x6 faceLoad]
EdgeLoad: [0x12 edgeLoad]
VertexLoad: [0x8 vertexLoad]
Other Parameters
ReferenceTemperature: []
5-16
femodel
ans =
1x1 materialProperties array
model.CellLoad = cellLoad(Gravity=[0;0;-9.8]);
model.CellLoad
ans =
1x1 cellLoad array
model.FaceBC(5) = faceBC(Constraint="fixed");
model.FaceBC
ans =
1x6 faceBC array
5-17
5 Functions
Generate a mesh and assign the result to the model. This assignment updates the mesh stored in the
Geometry property of the model.
model = generateMesh(model);
R = solve(model)
R =
StaticStructuralResults with properties:
pdeviz(R.Mesh,R.VonMisesStress)
ans =
PDEVisualization with properties:
5-18
femodel
MeshVisible: off
Transparency: 1
Position: [0.1300 0.1100 0.6705 0.8150]
Units: 'normalized'
Version History
Introduced in R2023a
To support modeling thermal radiation between surfaces without conductive media, the femodel
object has a new ThermalRadiation property that stores surface-to-surface radiation settings.
See Also
Functions
generateMesh | solve
Objects
fegeometry | materialProperties | edgeBC | faceBC | vertexBC | farFieldBC | cellLoad |
faceLoad | edgeLoad | vertexLoad | cellIC | faceIC | edgeIC | vertexIC
5-19
5 Functions
fegeometry
Geometry object for finite element analysis
Description
An fegeometry object contains a geometry for use in a finite element analysis with an femodel
object.
Creation
Syntax
gm = fegeometry(geometry)
gm = fegeometry(geometry,MaxRelativeDeviation=d)
gm = fegeometry(nodes,elements)
gm = fegeometry(nodes,elements,ElementIDToRegionID)
Description
gm = fegeometry(geometry) creates an fegeometry object that you can use in a finite element
analysis with an femodel object. Alternatively, you can assign a geometry directly to the Geometry
property of femodel, for example, femodel.Geometry = geometry.
Input Arguments
• String scalar or character vector that contains a path to an STL or STEP file. The path must end
with the file extension ".stl", ".STL", ".stp", ".STP", ".step", ".STEP", or any
combination of uppercase and lowercase letters in this extension.
• Decomposed geometry matrix or a handle to a geometry function. For details about a decomposed
geometry matrix, see decsg. A geometry function must return the same result for the same input
5-20
fegeometry
arguments in every function call. Thus, it must not contain functions and expressions designed to
return a variety of results, such as random number generators.
• triangulation object. The fegeometry function accepts both surface triangulation and
triangulation with tetrahedra for 3-D geometries. For a 3-D geometry created from surface
triangulation, the Mesh property remains empty. For a 2-D geometry or a 3-D geometry created
from triangulation with tetrahedra, fegeometry uses triangulation points and connectivity list to
specify a linear mesh. If the Mesh property is empty or your task requires a more accurate
quadratic mesh or a finer linear mesh, use the generateMesh function.
• delaunayTriangulation object. The fegeometry function uses triangulation points to specify
a mesh. If your task requires a more accurate quadratic mesh, use the generateMesh function.
• DiscreteGeometry object.
• AnalyticGeometry object.
d — Relative sag
1 (default) | number in the range [0.1, 10]
Relative sag for importing a STEP geometry, specified as a number in the range [0.1, 10]. A relative
sag is the ratio between the local absolute sag and the local mesh edge length. The absolute sag is
the maximal gap between the mesh and the geometry.
Example: gm = fegeometry("AngleBlock.step",MaxRelativeDeviation=5)
Data Types: double
Mesh nodes, specified as an Nnodes-by-2 or Nnodes-by-3 matrix for a 2-D or 3-D geometry,
respectively. Nnodes is the number of nodes in the mesh. Each row of the matrix contains x-, y-, and,
if applicable, z- coordinates of one node.
Data Types: double
Mesh elements, specified as an integer matrix with Nelements rows and 3, 4, 6, or 10 columns,
where Nelements is the number of elements in the mesh.
• Linear planar mesh or linear mesh on the geometry surface has size Nelements-by-3. Each row 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 Nelements-by-4. Each row of elements contains the indices of the
tetrahedral corner nodes for an element.
5-21
5 Functions
• Quadratic planar mesh or quadratic mesh on the geometry surface has size Nelements-by-6.
Each row of elements contains the indices of the triangle corner nodes and edge centers for a
surface element. In this case, the resulting geometry does not contain a full mesh. Create the
mesh using the generateMesh function.
• Quadratic elements have size Nelements-by-10. Each row 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-184.
Data Types: double
Domain information for each mesh element, specified as a vector of positive integers. Each mesh
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
Properties
NumCells — Number of geometry cells
nonnegative integer
5-22
fegeometry
Coordinates of geometry vertices, returned as an N-by-2 or N-by-3 numeric matrix for a 2-D or 3-D
geometry, respectively. Here, N is the number of vertices.
Data Types: double
Mesh for solution, specified as an FEMesh object. See FEMesh for details.
Object Functions
addCell Combine two geometries by adding one inside a cell of another
addFace Fill void regions in 2-D and split cells in 3-D geometry
addVertex Add vertex on geometry boundary
addVoid Create void regions inside 3-D geometry
cellEdges Find edges belonging to boundaries of specified cells
cellFaces Find faces belonging to specified cells
extrude Vertically extrude 2-D geometry or specified faces of 3-D geometry
faceEdges Find edges belonging to specified faces
facesAttachedToEdges Find faces attached to specified edges
generateMesh Create triangular or tetrahedral mesh
mergeCells Merge geometry cells
nearestEdge Find edges nearest to specified point
nearestFace Find faces nearest to specified point
pdegplot Plot PDE geometry
pdemesh Plot PDE mesh
rotate Rotate geometry
scale Scale geometry
translate Translate geometry
triangulation Create triangulation object from fegeometry
Examples
Create and plot a 3-D geometry consisting of three nested cuboids of the same height.
5-23
5 Functions
Create an femodel object for solving a static structural problem and assign the geometry to the
model.
model = femodel(AnalysisType="structuralStatic", ...
Geometry=gm);
model.Geometry
ans =
fegeometry with properties:
NumFaces: 18
NumEdges: 36
NumVertices: 24
NumCells: 3
Vertices: [24x3 double]
Mesh: []
Create an fegeometry object from an STL file representing a forearm link, and use it for a finite
element analysis with an femodel object.
Create an femodel object for solving a static structural problem, and assign the geometry to the
model.
5-24
fegeometry
ans =
fegeometry with properties:
NumFaces: 147
NumEdges: 329
NumVertices: 213
NumCells: 1
Vertices: [213x3 double]
Mesh: []
pdegplot(model,FaceAlpha=0.3)
gm = fegeometry(@cardg)
5-25
5 Functions
gm =
fegeometry with properties:
NumFaces: 1
NumEdges: 4
NumVertices: 4
NumCells: 0
Vertices: [4x2 double]
Mesh: []
gm =
fegeometry with properties:
5-26
fegeometry
NumFaces: 1
NumEdges: 4
NumVertices: 4
NumCells: 0
Vertices: [4x2 double]
Mesh: []
pdegplot(gm,EdgeLabels="on");
xlim([-0.1 1.1])
ylim([-0.1 1.1])
P = [2.5 8.0;
6.5 8.0;
2.5 5.0;
6.5 5.0;
5-27
5 Functions
1.0 6.5;
8.0 6.5];
T = [5 3 1;
3 2 1;
3 4 2;
4 6 2];
TR = triangulation(T,P)
TR =
triangulation with properties:
gm = fegeometry(TR)
gm =
fegeometry with properties:
NumFaces: 1
NumEdges: 6
NumVertices: 6
NumCells: 0
Vertices: [6x3 double]
Mesh: [1x1 FEMesh]
gm.Mesh
ans =
FEMesh with properties:
gm = generateMesh(gm);
gm.Mesh
ans =
FEMesh with properties:
5-28
fegeometry
Version History
Introduced in R2023a
See Also
Functions
generateMesh | pdegplot | addCell | addFace | addVertex | addVoid | rotate | scale |
translate | extrude | cellEdges | cellFaces | faceEdges | facesAttachedToEdges |
nearestEdge | nearestFace
Objects
femodel
5-29
5 Functions
edgeBC
Boundary conditions on geometry edge
Description
An edgeBC object specifies the type of boundary condition on an edge of a geometry. An femodel
object contains an array of edgeBC objects in its EdgeBC property.
Creation
Syntax
model.EdgeBC(EdgeID) = edgeBC(Name=Value)
Description
Input Arguments
Edge IDs, specified as a vector of positive integers. Find the edge IDs using pdegplot with the
EdgeLabels value set to "on".
Data Types: double
Properties
Constraint — Standard structural boundary constraints
"fixed"
x-component of enforced displacement, specified as a real number or function handle. The function
must return a row vector. Each element of this vector corresponds to the x-component value of the
enforced displacement at the boundary coordinates provided by the solver. For a transient or
frequency response analysis, XDisplacement also can be a function of time or frequency,
respectively. For details, see “Nonconstant Parameters of Finite Element Model” on page 2-149.
5-30
edgeBC
For axisymmetric models, this property contains the radial component of the enforced displacement.
Data Types: double | function_handle
y-component of enforced displacement, specified as a real number or function handle. The function
must return a row vector. Each element of this vector corresponds to the y-component value of the
enforced displacement at the boundary coordinates provided by the solver. For a transient or
frequency response analysis, YDisplacement also can be a function of time or frequency,
respectively. For details, see “Nonconstant Parameters of Finite Element Model” on page 2-149.
For axisymmetric models, this property contains the axial component of the enforced displacement.
Data Types: double | function_handle
z-component of enforced displacement for a 3-D model, specified as a real number or function handle.
The function must return a row vector. Each element of this vector corresponds to the z-component
value of the enforced displacement at the boundary coordinates provided by the solver. For a
transient or frequency response analysis, ZDisplacement also can be a function of time or
frequency, respectively. For details, see “Nonconstant Parameters of Finite Element Model” on page
2-149.
Data Types: double | function_handle
Temperature boundary condition, specified as a real number or function handle. Use a function
handle to specify a temperature that depends on space and time. For details, see “Nonconstant
Parameters of Finite Element Model” on page 2-149.
Data Types: double | function_handle
Voltage — Voltage
real number | function handle
Voltage, specified as a real number or function handle. Use a function handle to specify a voltage that
depends on the coordinates. For details, see “Nonconstant Parameters of Finite Element Model” on
page 2-149.
Electric field, specified as a column vector of two elements for a 2-D model, vector of three elements
for a 3-D model, or function handle. Use a function handle to specify an electric field that depends on
the coordinates. For details, see “Nonconstant Parameters of Finite Element Model” on page 2-149.
5-31
5 Functions
The solver uses an electric field boundary condition for a harmonic analysis with an electric field
type.
Data Types: double | function_handle
Magnetic field, specified as a column vector of two elements for a 2-D model, column vector of three
elements for a 3-D model, or function handle. Use a function handle to specify a magnetic field that
depends on the coordinates. For details, see “Nonconstant Parameters of Finite Element Model” on
page 2-149.
The solver uses a magnetic field boundary condition for a harmonic analysis with a magnetic field
type.
Data Types: double | function_handle
Magnetic potential, specified as a real number, column vector of three elements for a 3-D model, or
function handle. Use a function handle to specify a magnetic potential that depends on the
coordinates.
The solver uses a magnetic potential boundary condition for a magnetostatic analysis.
Data Types: double | function_handle
Absorbing region, specified as a farFieldBC object. Properties of this object specify the thickness of
the absorbing region, exponent and scaling parameter defining the attenuation rate of the waves
entering the absorbing region.
Examples
Temperature on Boundary
Specify a temperature boundary condition for an femodel object representing a steady-state thermal
problem.
Create an femodel object for solving a steady-state thermal problem, and assign the unit square
geometry to the model.
model = femodel(AnalysisType="thermalSteady", ...
Geometry=@squareg);
5-32
edgeBC
ans =
1x4 edgeBC array
Index Temperature
1 100
2 []
3 100
4 []
5-33
5 Functions
Create an femodel object for solving a harmonic electromagnetic problem with an electric field type.
Assign a geometry representing a 2-D plate with a hole to the model.
pdegplot(model.Geometry,EdgeLabels="on");
xlim([-1 11])
ylim([-1 21])
ans =
1x5 edgeBC array
5-34
edgeBC
Specify absorbing regions with a thickness of 2 on the edges of the rectangle. Use the default
attenuation rate for the absorbing regions.
ffbc = farFieldBC(Thickness=2);
model.EdgeBC(1:4) = edgeBC(FarField=ffbc);
model.EdgeBC
ans =
1x5 edgeBC array
model.EdgeBC(1).FarField
ans =
farFieldBC with properties:
Thickness: 2
Exponent: 4
Scaling: 5
ffbc = farFieldBC(Thickness=2,Exponent=3,Scaling=100);
model.EdgeBC(1:4) = edgeBC(FarField=ffbc);
model.EdgeBC(1).FarField
ans =
farFieldBC with properties:
Thickness: 2
Exponent: 3
Scaling: 100
Version History
Introduced in R2023a
5-35
5 Functions
See Also
Objects
femodel | fegeometry | farFieldBC | faceBC | vertexBC | cellLoad | faceLoad | edgeLoad |
vertexLoad
5-36
faceBC
faceBC
Boundary conditions on geometry face
Description
A faceBC object specifies the type of boundary condition on a face of a geometry. An femodel object
contains an array of faceBC objects in its FaceBC property.
Creation
Syntax
model.FaceBC(FaceID) = faceBC(Name=Value)
Description
Input Arguments
Face IDs, specified as a vector of positive integers. Find the face IDs using pdegplot with the
FaceLabels value set to "on".
Data Types: double
Properties
Constraint — Standard structural boundary constraints
"fixed"
x-component of enforced displacement, specified as a real number or function handle. The function
must return a row vector. Each element of this vector corresponds to the x-component value of the
enforced displacement at the boundary coordinates provided by the solver. For a transient or
frequency response analysis, XDisplacement also can be a function of time or frequency,
respectively. For details, see “Nonconstant Parameters of Finite Element Model” on page 2-149.
5-37
5 Functions
y-component of enforced displacement, specified as a real number or function handle. The function
must return a row vector. Each element of this vector corresponds to the y-component value of the
enforced displacement at the boundary coordinates provided by the solver. For a transient or
frequency response analysis, YDisplacement also can be a function of time or frequency,
respectively. For details, see “Nonconstant Parameters of Finite Element Model” on page 2-149.
Data Types: double | function_handle
z-component of enforced displacement, specified as a real number or function handle. The function
must return a row vector. Each element of this vector corresponds to the z-component value of the
enforced displacement at the boundary coordinates provided by the solver. For a transient or
frequency response analysis, ZDisplacement also can be a function of time or frequency,
respectively. For details, see “Nonconstant Parameters of Finite Element Model” on page 2-149.
Data Types: double | function_handle
Temperature boundary condition, specified as a real number or function handle. Use a function
handle to specify a temperature that depends on space and time. For details, see “Nonconstant
Parameters of Finite Element Model” on page 2-149.
Data Types: double | function_handle
Voltage — Voltage
real number | function handle
Voltage, specified as a real number or function handle. Use a function handle to specify a voltage that
depends on the coordinates. For details, see “Nonconstant Parameters of Finite Element Model” on
page 2-149.
Electric field, specified as a column vector of two elements for a 2-D model, vector of three elements
for a 3-D model, or function handle. Use a function handle to specify an electric field that depends on
the coordinates. For details, see “Nonconstant Parameters of Finite Element Model” on page 2-149.
The solver uses an electric field boundary condition for a harmonic analysis with an electric field
type.
Data Types: double | function_handle
5-38
faceBC
Magnetic field, specified as a column vector of two elements for a 2-D model, column vector of three
elements for a 3-D model, or function handle. Use a function handle to specify a magnetic field that
depends on the coordinates. For details, see “Nonconstant Parameters of Finite Element Model” on
page 2-149.
The solver uses a magnetic field boundary condition for a harmonic analysis with a magnetic field
type.
Data Types: double | function_handle
Magnetic potential, specified as a real number, column vector of three elements for a 3-D model, or
function handle. Use a function handle to specify a magnetic potential that depends on the
coordinates. For details, see “Nonconstant Parameters of Finite Element Model” on page 2-149.
The solver uses a magnetic potential boundary condition for a magnetostatic analysis.
Data Types: double | function_handle
Absorbing region, specified as a farFieldBC object. Properties of this object specify the thickness of
the absorbing region, exponent and scaling parameter defining the attenuation rate of the waves
entering the absorbing region.
Examples
Fixed Boundaries
Specify fixed boundary conditions for an femodel object representing a static structural problem.
gm = multicylinder([0.01,0.015],0.05);
pdegplot(gm,FaceLabels="on",FaceAlpha=0.4);
5-39
5 Functions
Create an femodel object for solving a static structural problem, and assign the geometry to the
model.
ans =
1x6 faceBC array
5-40
faceBC
Create an femodel object for solving a harmonic electromagnetic problem with an electric field type.
Assign a geometry representing a 3-D plate with a hole to the model.
model = femodel(AnalysisType="electricHarmonic", ...
Geometry="PlateHoleSolid.stl");
ans =
1x7 faceBC array
5-41
5 Functions
Specify absorbing regions with a thickness of 2 on the sides of the plate. Use the default attenuation
rate for the absorbing regions.
ffbc = farFieldBC(Thickness=2);
model.FaceBC(3:6) = faceBC(FarField=ffbc);
model.FaceBC
ans =
1x7 faceBC array
ans =
farFieldBC with properties:
Thickness: 2
Exponent: 4
Scaling: 5
ans =
farFieldBC with properties:
Thickness: 2
Exponent: 3
5-42
faceBC
Scaling: 100
Version History
Introduced in R2023a
See Also
Objects
femodel | fegeometry | farFieldBC | edgeBC | vertexBC | cellLoad | faceLoad | edgeLoad |
vertexLoad
5-43
5 Functions
vertexBC
Boundary conditions on geometry vertex
Description
A vertexBC object specifies the type of boundary condition on a vertex of a geometry. An femodel
object contains an array of vertexBC objects in its VertexBC property.
Creation
Syntax
model.VertexBC(VertexID) = vertexBC(Name=Value)
Description
Input Arguments
Vertex IDs, specified as a vector of positive integers. Find the vertex IDs using pdegplot with the
VertexLabels value set to "on".
Data Types: double
Properties
Constraint — Standard structural boundary constraint
"fixed"
x-component of enforced displacement, specified as a real number or function handle. The function
must return a row vector. Each element of this vector corresponds to the x-component value of the
enforced displacement at the boundary coordinates provided by the solver. For a transient or
frequency response analysis, XDisplacement also can be a function of time or frequency,
respectively. For details, see “Nonconstant Parameters of Finite Element Model” on page 2-149.
5-44
vertexBC
For axisymmetric models, this property contains the radial component of the enforced displacement.
Data Types: double | function_handle
y-component of enforced displacement, specified as a real number or function handle. The function
must return a row vector. Each element of this vector corresponds to the y-component value of the
enforced displacement at the boundary coordinates provided by the solver. For a transient or
frequency response analysis, YDisplacement also can be a function of time or frequency,
respectively. For details, see “Nonconstant Parameters of Finite Element Model” on page 2-149.
For axisymmetric models, this property contains the axial component of the enforced displacement.
Data Types: double | function_handle
z-component of enforced displacement for a 3-D model, specified as a real number or function handle.
The function must return a row vector. Each element of this vector corresponds to the z-component
value of the enforced displacement at the boundary coordinates provided by the solver. For a
transient or frequency response analysis, ZDisplacement also can be a function of time or
frequency, respectively. For details, see “Nonconstant Parameters of Finite Element Model” on page
2-149.
Data Types: double | function_handle
Examples
Displacement at Vertex
Specify fixed boundary conditions for an femodel object representing an axisymmetric static
structural problem.
Create a rectangular geometry that represents a spinning disk. The inner radius of the disk is 0.05,
and the outer radius is 0.2. The thickness of the disk is 0.05.
pdegplot(gm,VertexLabels="on");
xlim([0.04 0.21])
ylim([-0.03 0.03])
5-45
5 Functions
Create an femodel object for solving a static axisymmetric structural problem, and assign the
geometry to the model.
ans =
1x4 vertexBC array
5-46
vertexBC
Version History
Introduced in R2023a
See Also
Objects
femodel | fegeometry | edgeBC | faceBC | cellLoad | faceLoad | edgeLoad | vertexLoad
5-47
5 Functions
farFieldBC
Absorbing boundary condition for harmonic electromagnetic analysis
Description
A farFieldBC object specifies the thickness of an absorbing region as well as the exponent and
scaling parameter defining the attenuation rate of the waves entering the absorbing region. edgeBC
and faceBC objects contain farFieldBC objects in their FarField property.
Creation
Syntax
ffbc = farFieldBC(Name=Value)
Description
Properties
Thickness — Width of far field absorbing region
positive number
Width of the far field absorbing region, specified as a positive number. The solver uses an absorbing
boundary condition for a harmonic analysis.
Data Types: double
Exponent defining the attenuation rate of the waves entering the absorbing region, specified as a
positive number. The solver uses an absorbing boundary condition for a harmonic analysis.
Data Types: double
Scaling parameter defining the attenuation rate of the waves entering the absorbing region, specified
as a positive number. The solver uses an absorbing boundary condition for a harmonic analysis.
Data Types: double
Examples
5-48
farFieldBC
Create an femodel object for solving a harmonic electromagnetic problem with an electric field type.
Assign a geometry representing a 2-D plate with a hole to the model.
model = femodel(AnalysisType="electricHarmonic", ...
Geometry="PlateHolePlanar.stl");
ans =
1x5 edgeBC array
5-49
5 Functions
1 [] []
2 [] []
3 [] []
4 [] []
5 [10 0] []
Specify absorbing regions with a thickness of 2 on the edges of the rectangle. Use the default
attenuation rate for the absorbing regions.
ffbc = farFieldBC(Thickness=2);
model.EdgeBC(1:4) = edgeBC(FarField=ffbc);
model.EdgeBC
ans =
1x5 edgeBC array
model.EdgeBC(1).FarField
ans =
farFieldBC with properties:
Thickness: 2
Exponent: 4
Scaling: 5
ffbc = farFieldBC(Thickness=2,Exponent=3,Scaling=100);
model.EdgeBC(1:4) = edgeBC(FarField=ffbc);
model.EdgeBC(1).FarField
ans =
farFieldBC with properties:
Thickness: 2
Exponent: 3
Scaling: 100
5-50
farFieldBC
Create an femodel object for solving a harmonic electromagnetic problem with an electric field type.
Assign a geometry representing a 3-D plate with a hole to the model.
model = femodel(AnalysisType="electricHarmonic", ...
Geometry="PlateHoleSolid.stl");
ans =
1x7 faceBC array
5-51
5 Functions
2 [] []
3 [] []
4 [] []
5 [] []
6 [] []
7 [10 0 0] []
Specify absorbing regions with a thickness of 2 on the sides of the plate. Use the default attenuation
rate for the absorbing regions.
ffbc = farFieldBC(Thickness=2);
model.FaceBC(3:6) = faceBC(FarField=ffbc);
model.FaceBC
ans =
1x7 faceBC array
ans =
farFieldBC with properties:
Thickness: 2
Exponent: 4
Scaling: 5
ans =
farFieldBC with properties:
Thickness: 2
Exponent: 3
Scaling: 100
5-52
farFieldBC
Version History
Introduced in R2023a
See Also
Objects
femodel | fegeometry | edgeBC | faceBC
5-53
5 Functions
cellLoad
Load on geometry cell
Description
A cellLoad object contains a description of a load on a cell of a geometry. An femodel object
contains an array of cellLoad objects in its CellLoad property.
Creation
Syntax
model.CellLoad(CellID) = cellLoad(Name=Value)
model.CellLoad = cellLoad(Name=Value)
Description
Input Arguments
Cell IDs, specified as a vector of positive integers. Find the cell IDs using pdegplot with the
CellLabels value set to "on".
Data Types: double
Properties
Gravity — Acceleration due to gravity
vector
Acceleration due to gravity, specified as a vector of three elements for a 3-D model.
Data Types: double
5-54
cellLoad
Angular velocity for modeling centrifugal loading in an axisymmetric model, specified as a positive
number.
Data Types: double
Tip If you specify a thermal load, you must also specify a reference temperature using
model.ReferenceTemperature. For details, see the description of the ReferenceTemperature
property in femodel.
Heat source term, specified as a real number or function handle. Use a function handle to specify an
internal heat source that depends on space, time, or temperature. For details, see “Nonconstant
Parameters of Finite Element Model” on page 2-149.
Data Types: double | function_handle
Charge density, specified as a real number or function handle. Use a function handle to specify a
charge density that depends on the coordinates. For details, see “Nonconstant Parameters of Finite
Element Model” on page 2-149.
Data Types: double | function_handle
For magnetostatic analysis, the current density must be a vector of three elements, a
ConductionResults object, or a function handle.
For harmonic analysis with an electric field type, the toolbox multiplies the specified current density
by -i and by frequency. The current density must be a vector of three elements or a function handle
that depends on the coordinates.
For harmonic analysis with a magnetic field type, the toolbox uses the curl of the specified current
density. The current density must be a vector of three elements or a function handle that depends on
the coordinates for a 3-D model.
Data Types: double | function_handle
5-55
5 Functions
Magnetization — Magnetization
vector | function handle
Magnetization, specified as a vector of three elements or a function handle. Use a function handle to
specify a magnetization that depends on the coordinates. For details, see “Nonconstant Parameters of
Finite Element Model” on page 2-149.
Data Types: double | function_handle
Examples
Magnetization on Cell
gm = multicylinder([0.01,0.015],0.05);
pdegplot(gm,CellLabels="on",FaceAlpha=0.4);
Create an femodel object for solving a magnetostatic problem, and assign the geometry to the
model.
5-56
cellLoad
To make the inner cylinder represent a permanent magnet, specify the uniform magnetization in the
positive x-direction.
ans =
1x2 cellLoad array
Specify the gravity load for an femodel object representing a static structural problem.
L = 0.5;
W = 0.1;
H = 0.1;
gm = multicuboid(L,W,[H,H],Zoffset=[0,H]);
pdegplot(gm,CellLabels="on");
5-57
5 Functions
Create an femodel object for solving a static structural problem, and assign the geometry to the
model.
ans =
1x2 cellLoad array
Version History
Introduced in R2023a
5-58
cellLoad
See Also
Objects
femodel | fegeometry | edgeBC | faceBC | vertexBC | faceLoad | edgeLoad | vertexLoad
5-59
5 Functions
faceLoad
Load on geometry face
Description
A faceLoad object contains a description of a load on a face of a geometry. An femodel object
contains an array of faceLoad objects in its FaceLoad property.
Creation
Syntax
model.FaceLoad(FaceID) = faceLoad(Name=Value)
model.FaceLoad = faceLoad(Name=Value)
Description
Input Arguments
Face IDs, specified as a vector of positive integers. Find the face IDs using pdegplot with the
FaceLabels value set to "on".
Data Types: double
Properties
Temperature — Thermal load
real number | SteadyStateThermalResults object | TransientThermalResults object
5-60
faceLoad
Tip If you specify a thermal load, you must also specify a reference temperature using
model.ReferenceTemperature. For details, see the description of the ReferenceTemperature
property in femodel.
Heat source term, specified as a real number or function handle. Use a function handle to specify an
internal heat source that depends on space, time, or temperature. For details, see “Nonconstant
Parameters of Finite Element Model” on page 2-149.
Pressure normal to the boundary, specified as a real number or function handle. A positive-value
pressure acts into the boundary (for example, compression), while a negative-value pressure acts
away from the boundary (for example, suction).
If you specify Pressure as a function handle, the function must return a row vector where each
column corresponds to the value of pressure at the boundary coordinates provided by the solver. For
a transient structural model, Pressure also can be a function of time. For a frequency response
structural model, Pressure can be a function of frequency (when specified as a function handle) or a
constant pressure with the same magnitude for a broad frequency spectrum. For details, see
“Nonconstant Parameters of Finite Element Model” on page 2-149.
Data Types: double | function_handle
Convection to ambient boundary condition, specified as a real number or function handle. Use a
function handle to specify a convection coefficient that depends on space and time. For details, see
“Nonconstant Parameters of Finite Element Model” on page 2-149.
Ambient temperature, specified as a real number. The ambient temperature value is required for
specifying convection and radiation boundary conditions.
Data Types: double
5-61
5 Functions
Specify ambient temperature using the AmbientTemperature property and the Stefan-Boltzmann
constant using the femodel properties. The value of Emissivity is positive for heat radiation into
the ambient environment.
Data Types: double
Normal and tangential distributed forces on the boundary (in the global Cartesian coordinate
system), specified as a vector of three elements or a function handle.
If you specify SurfaceTraction as a function handle, the function must return a three-row matrix.
Each column of the matrix corresponds to the surface traction vector at the boundary coordinates
provided by the solver. For a transient or frequency response analysis, surface traction also can be a
function of time or frequency, respectively. For details, see “Nonconstant Parameters of Finite
Element Model” on page 2-149.
Data Types: double | function_handle
Distributed spring stiffness for each translational direction used to model an elastic foundation,
specified as a vector of three elements or a function handle.
If you specify TranslationalStiffness as a function handle, the function must return a three-row
matrix. Each column of the matrix corresponds to the stiffness vector at the boundary coordinates
provided by the solver. For a transient or frequency response analysis, translational stiffness also can
be a function of time or frequency, respectively. For details, see “Nonconstant Parameters of Finite
Element Model” on page 2-149.
Data Types: double | function_handle
Angular velocity for modeling centrifugal loading in an axisymmetric model, specified as a positive
number.
Data Types: double
Charge density, specified as a real number or function handle. Use a function handle to specify a
charge density that depends on the coordinates. For details, see “Nonconstant Parameters of Finite
Element Model” on page 2-149.
5-62
faceLoad
Current density, specified as a real number, vector, function handle, or ConductionResults object.
Use a function handle to specify a nonconstant current density. For details, see “Nonconstant
Parameters of Finite Element Model” on page 2-149.
• A real number or a function handle for a 2-D model. The toolbox does not support conduction
results as a source of current density for a 2-D magnetostatic analysis.
• A vector of three elements, a ConductionResults object, or a function handle for a 3-D model
For harmonic analysis with an electric field type, the toolbox multiplies the specified current density
by -i and by frequency. The current density must be:
• A vector of two elements or a function handle that depends on the coordinates for a 2-D model
• A vector of three elements or a function handle that depends on the coordinates for a 3-D model
For harmonic analysis with a magnetic field type, the toolbox uses the curl of the specified current
density. The current density must be:
• A number or a function handle that depends on the coordinates for a 2-D model
• A vector of three elements or a function handle that depends on the coordinates for a 3-D model
Magnetization — Magnetization
vector | function handle
Magnetization, specified as a vector of two elements for a 2-D model, vector of three elements for a 3-
D model, or function handle. Use a function handle to specify a magnetization that depends on
coordinates. For details, see “Nonconstant Parameters of Finite Element Model” on page 2-149.
Data Types: double | function_handle
Surface current density in the direction normal to the boundary, specified as a real number or
function handle. The solver uses a surface current density boundary condition for a DC conduction
analysis. Use a function handle to specify a surface current density that depends on the coordinates.
For details, see “Nonconstant Parameters of Finite Element Model” on page 2-149.
Data Types: double | function_handle
Examples
Specify surface traction for an femodel object representing a static structural problem.
5-63
5 Functions
gm = multicylinder([0.01,0.015],0.05);
pdegplot(gm,FaceLabels="on",FaceAlpha=0.4);
Create an femodel object for solving a static structural problem, and assign the geometry to the
model.
ans = 1×3
0 0 100
ans = 1×3
0 0 100
5-64
faceLoad
Specify angular velocity for an femodel object representing a static structural problem. For this
analysis, simplify the 3-D axisymmetric model to a 2-D model.
Create a rectangular geometry that represents an spinning disk. The inner radius of the disk is 0.05,
and the outer radius is 0.2. The thickness of the disk is 0.05.
pdegplot(gm,FaceLabels="on");
xlim([0.04 0.21])
ylim([-0.03 0.03])
Create an femodel object for solving an axisymmetric static structural problem, and assign the
geometry to the model.
Apply centrifugal load due to spinning of the disk. Assume that the disk is spinning at 104.7 rad/s.
model.FaceLoad = faceLoad(AngularVelocity=104.7);
model.FaceLoad
5-65
5 Functions
ans =
1x1 faceLoad array
Version History
Introduced in R2023a
See Also
Objects
femodel | fegeometry | edgeBC | faceBC | vertexBC | cellLoad | edgeLoad | vertexLoad
5-66
surfaceToSurfaceSettings
surfaceToSurfaceSettings
Settings for modeling thermal radiation between surfaces
Description
A surfaceToSurfaceSettings object contains information about the parameters for thermal
radiation analysis between surfaces without conductive media. The settings include all defined
enclosures, names of enclosures currently participating in radiation analysis, and computed view
factors.
Creation
The setupRadiation function creates a surfaceToSurfaceSettings object stored in the
ThermalRadiation property of an femodel object.
When calling setupRadiation, use fem as both the input and output argument to assign the
resulting surfaceToSurfaceSettings object to the ThermalRadiation property of the specified
model.
Properties
ViewFactors — Computed view factors
numeric matrix
Computed view factors, stored as a numeric matrix. Computing view factors involves determining
which mesh facet on the boundary sees which other facets, including the effect of shadowing. The
toolbox uses ray tracing to determine shadowing, while it uses the double area integral method to
compute the view factor itself.
Data Types: double
Enclosures for surface-to-surface radiation analysis, stored as a dictionary with string keys and
enclosureDefinition values. Each enclosure is a group of surfaces between which heat transfer
occurs due to radiation without conductive media.
5-67
5 Functions
Examples
Specify radiation parameters for heat transfer between two parallel plates.
Create the geometry representing two parallel plates of the same dimensions. The distance between
the plates is 0.4 m.
dist = 0.4;
W = 0.05;
L = 0.5;
H = 0.5;
R1 = [3 4 0 W W 0 0 0 L L];
R2 = [3 4 W+dist 2*W+dist 2*W+dist W+dist 0 0 L L];
geom2D = fegeometry(decsg([R1(:) R2(:)], ...
'R1+R2',[char('R1')' char('R2')']));
geom3D = extrude(geom2D,H);
pdegplot(geom3D,FaceLabels="on",FaceAlpha=0.3)
Create a finite element model for thermal analysis and include the geometry.
fem = femodel(AnalysisType="thermalSteady",Geometry=geom3D);
Generate a mesh.
fem = generateMesh(fem,Hmax=H/4);
5-68
surfaceToSurfaceSettings
Account for surface-to-surface radiation in the enclosure formed by the plates by using the
setupRadiation function.
ans =
surfaceToSurfaceSettings with properties:
If you do not specify enclosure names, setupRadiation uses the default names, such as
"Enclosure_1". The function also sets the enclosure perfectness to true, which means that the
solver ignores ambient radiation. To change these settings, use the EnclosureNames and
PerfectEnclosure name-value arguments.
ans =
surfaceToSurfaceSettings with properties:
Specify ambient temperature and emissivity for the enclosure formed by the plates.
Version History
Introduced in R2023b
See Also
Functions
setupRadiation
Objects
femodel | faceLoad
5-69
5 Functions
edgeLoad
Load on geometry edge
Description
An edgeLoad object contains a description of a load on an edge of a geometry. An femodel object
contains an array of edgeLoad objects in its EdgeLoad property.
Creation
Syntax
model.EdgeLoad(EdgeID) = edgeLoad(Name=Value)
Description
Input Arguments
Edge IDs, specified as a vector of positive integers. Find the edge IDs using pdegplot with the
EdgeLabels value set to "on".
Data Types: double
Properties
Heat — Heat source term
real number | function handle
Heat source term, specified as a real number or function handle. Use a function handle to specify an
internal heat source that depends on space, time, or temperature. For details, see “Nonconstant
Parameters of Finite Element Model” on page 2-149.
Pressure normal to the boundary, specified as a real number or function handle. A positive-value
pressure acts into the boundary (for example, compression), while a negative-value pressure acts
away from the boundary (for example, suction).
5-70
edgeLoad
If you specify Pressure as a function handle, the function must return a row vector where each
column corresponds to the value of pressure at the boundary coordinates provided by the solver. For
a transient structural model, Pressure also can be a function of time. For a frequency response
structural model, Pressure can be a function of frequency (when specified as a function handle) or a
constant pressure with the same magnitude for a broad frequency spectrum. For details, see
“Nonconstant Parameters of Finite Element Model” on page 2-149.
Data Types: double | function_handle
Convection to ambient boundary condition, specified as a real number or function handle. Use a
function handle to specify a convection coefficient that depends on space and time. For details, see
“Nonconstant Parameters of Finite Element Model” on page 2-149.
Ambient temperature, specified as a real number. The ambient temperature value is required for
specifying convection and radiation boundary conditions.
Data Types: double
Specify ambient temperature using the AmbientTemperature property and the Stefan-Boltzmann
constant using the femodel properties. The value of Emissivity is positive for heat radiation into
the ambient environment.
Data Types: double
Normal and tangential distributed forces on the boundary (in the global Cartesian coordinate
system), specified as a vector of two elements or a function handle.
If you specify SurfaceTraction as a function handle, the function must return a two-row matrix.
Each column of the matrix corresponds to the surface traction vector at the boundary coordinates
provided by the solver. For a transient or frequency response analysis, surface traction also can be a
function of time or frequency, respectively. For details, see “Nonconstant Parameters of Finite
Element Model” on page 2-149.
Data Types: double | function_handle
5-71
5 Functions
Distributed spring stiffness for each translational direction used to model an elastic foundation,
specified as a vector of two elements or a function handle.
If you specify TranslationalStiffness as a function handle, the function must return a two-row
matrix. Each column of the matrix corresponds to the stiffness vector at the boundary coordinates
provided by the solver. For a transient or frequency response analysis, translational stiffness also can
be a function of time or frequency, respectively. For details, see “Nonconstant Parameters of Finite
Element Model” on page 2-149.
Data Types: double | function_handle
Surface current density in the direction normal to the boundary, specified as a real number or
function handle. The solver uses a surface current density boundary condition for a DC conduction
analysis. Use a function handle to specify a surface current density that depends on the coordinates.
For details, see “Nonconstant Parameters of Finite Element Model” on page 2-149.
Data Types: double | function_handle
Examples
Specify a heat flux through the edge of a square for an femodel object representing a thermal
problem.
Create an femodel object for solving a steady-state thermal problem, and assign the unit square
geometry to the model.
pdegplot(model.Geometry,EdgeLabels="on");
xlim([-1.1 1.1])
ylim([-1.1 1.1])
5-72
edgeLoad
model.EdgeLoad(3) = edgeLoad(Heat=20);
model.EdgeLoad
ans =
1x4 edgeLoad array
Index Heat
1 []
2 []
3 20
4 []
Version History
Introduced in R2023a
5-73
5 Functions
See Also
Objects
femodel | fegeometry | edgeBC | faceBC | vertexBC | cellLoad | faceLoad | vertexLoad
5-74
vertexLoad
vertexLoad
Load on geometry vertex
Description
A vertexLoad object contains a description of a load on a vertex of a geometry. An femodel object
contains an array of vertexLoad objects in its VertexLoad property.
Creation
Syntax
model.VertexLoad(VertexID) = vertexLoad(Force=Value)
Description
You can specify force for a static, transient, or frequency response structural analysis. A structural
modal analysis cannot have concentrated force.
Input Arguments
Vertex IDs, specified as a vector of positive integers. Find the vertex IDs using pdegplot with the
VertexLabels value set to "on".
Data Types: double
Properties
Force — Concentrated force
vector | function handle
Concentrated force at a vertex, specified as a vector or function handle. Use a function handle to
specify concentrated force that depends on time or frequency. For details, see “Nonconstant
Parameters of Finite Element Model” on page 2-149.
Data Types: double | function_handle
Examples
5-75
5 Functions
Specify a force value at a vertex for an femodel object representing a static structural problem.
Create an femodel object for solving a static structural problem, and assign the geometry to the
model.
ans =
1x4 vertexLoad array
Index Force
5-76
vertexLoad
1 [0 10000]
2 []
3 []
4 []
Version History
Introduced in R2023a
See Also
Objects
femodel | fegeometry | edgeBC | faceBC | vertexBC | cellLoad | faceLoad | edgeLoad
5-77
5 Functions
cellIC
Initial conditions on geometry cell
Description
A cellIC object specifies the type of an initial condition on a cell of a geometry. An femodel object
contains an array of cellIC objects in its CellIC property.
• You can use a geometric assignment to associate the initial condition with the specified geometric
regions or the entire geometry.
• You must apply a results-based assignment to all geometric regions because the results object
contains information about the entire geometry.
• For separate assignments to a geometric region (or the entire geometry) 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 EdgeIC assignment precedence over a FaceIC
assignment, even if you specify a FaceIC assignment after an EdgeIC assignment. The
assignments in order of precedence are VertexIC (highest precedence), EdgeIC, FaceIC, and
CellIC (lowest precedence).
Creation
Syntax
model.CellIC(CellID) = cellIC(Name=Value)
model.CellIC = cellIC(Name=Value)
Description
Input Arguments
Cell IDs, specified as a vector of positive integers. Find the cell IDs using pdegplot with the
CellLabels value set to "on".
5-78
cellIC
Properties
Displacement — Initial displacement
numeric vector | function handle | StaticStructuralResults object |
TransientStructuralResults object
Use a function handle to specify spatially varying initial displacement. The function must return a
three-row matrix. Each column of the matrix corresponds to the initial displacement at the
coordinates provided by the solver. For details, see “Nonconstant Parameters of Finite Element
Model” on page 2-149.
Use a function handle to specify spatially varying initial velocity. The function must return a three-row
matrix. Each column of the matrix corresponds to the initial velocity at the coordinates provided by
the solver. For details, see “Nonconstant Parameters of Finite Element Model” on page 2-149.
Initial temperature or initial guess for temperature, specified as a real number, function handle,
SteadyStateThermalResults object, or TransientThermalResults object. Use a function
handle to specify spatially varying initial temperature. For details, see “Nonconstant Parameters of
Finite Element Model” on page 2-149.
5-79
5 Functions
Initial guess for magnetic potential in a nonlinear magnetostatic problem, specified as a column
vector of three elements, a function handle, or a MagnetostaticResults object. Use a function
handle to specify spatially varying initial magnetic potential. For details, see “Nonconstant
Parameters of Finite Element Model” on page 2-149.
Initial flux density, specified as a positive number or a function handle. Use a function handle to
specify an initial flux density that depends on the coordinates, magnetic potential and its gradients,
and the norm of magnetic flux density. For details, see “Nonconstant Parameters of Finite Element
Model” on page 2-149.
If a relative permeability, current density, or magnetization for the model depend on the magnetic
potential or its gradients (state.u, state.ux, and so on), then initial conditions must not depend
on the magnetic flux density (state.NormFluxDensity).
Examples
Specify initial temperature on a cell for an femodel object representing a transient thermal problem.
gm = multicylinder([0.01,0.015],0.05);
gm = rotate(gm,90,[0 0 0],[0 1 0]);
pdegplot(gm,CellLabels="on",FaceAlpha=0.4);
5-80
cellIC
Create an femodel object for solving a transient thermal problem, and assign the geometry to the
model.
model.CellIC(1) = cellIC(Temperature=100);
model.CellIC
ans =
1x2 cellIC array
Index Temperature
1 100
2 []
5-81
5 Functions
Specify initial displacement on a beam geometry for an femodel object representing a transient
structural problem.
Create an femodel object for solving a static structural problem, and assign the geometry to the
model.
model = femodel(AnalysisType="structuralStatic", ...
Geometry=gm);
5-82
cellIC
model = generateMesh(model,Hmax=0.02);
Rstatic = solve(model);
model.AnalysisType = "structuralTransient";
model.CellIC = cellIC(Displacement=Rstatic);
model.CellIC
ans =
1x1 cellIC array
Specify initial magnetic potential for an femodel object representing a nonlinear magnetostatic
problem.
Create an femodel object for solving a magnetostatic problem, and assign a geometry consisting of
four hollow cylinders to the model.
pdegplot(model.Geometry,CellLabels="on");
5-83
5 Functions
ans =
1x4 cellIC array
ans =
1x4 cellIC array
5-84
cellIC
Version History
Introduced in R2023a
See Also
Objects
femodel | fegeometry | faceIC | edgeIC | vertexIC
Functions
filterByIndex
5-85
5 Functions
faceIC
Initial conditions on geometry face
Description
A faceIC object specifies the type of an initial condition on a face of a geometry. An femodel object
contains an array of faceIC objects in its FaceIC property.
• You can use a geometric assignment to associate the initial condition with the specified geometric
regions or the entire geometry.
• You must apply a results-based assignment to all geometric regions because the results object
contains information about the entire geometry.
• For separate assignments to a geometric region (or the entire geometry) 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 EdgeIC assignment precedence over a FaceIC
assignment, even if you specify a FaceIC assignment after an EdgeIC assignment. The
assignments in order of precedence are VertexIC (highest precedence), EdgeIC, FaceIC, and
CellIC (lowest precedence).
Creation
Syntax
model.FaceIC(FaceID) = faceIC(Name=Value)
model.FaceIC = faceIC(Name=Value)
Description
Input Arguments
Face IDs, specified as a vector of positive integers. Find the face IDs using pdegplot with the
FaceLabels value set to "on".
5-86
faceIC
Properties
Displacement — Initial displacement
numeric vector | function handle | StaticStructuralResults object |
TransientStructuralResults object
Use a function handle to specify spatially varying initial displacement. 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. For details, see
“Nonconstant Parameters of Finite Element Model” on page 2-149.
Use a function handle to specify spatially varying 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. For details, see
“Nonconstant Parameters of Finite Element Model” on page 2-149.
Initial temperature or initial guess for temperature, specified as a real number, function handle,
SteadyStateThermalResults object, or TransientThermalResults object. Use a function
handle to specify spatially varying initial temperature. For details, see “Nonconstant Parameters of
Finite Element Model” on page 2-149.
5-87
5 Functions
TransientThermalResults, you can access results for a particular time-step by using the
filterByIndex function.
Initial guess for magnetic potential in a nonlinear magnetostatic problem, specified as a positive
number, function handle, or MagnetostaticResults object. Use a function handle to specify
spatially varying initial magnetic potential. For details, see “Nonconstant Parameters of Finite
Element Model” on page 2-149.
Initial flux density, specified as a positive number or a function handle. Use a function handle to
specify an initial flux density that depends on the coordinates, magnetic potential and its gradients,
and the norm of magnetic flux density. For details, see “Nonconstant Parameters of Finite Element
Model” on page 2-149.
If a relative permeability, current density, or magnetization for the model depend on the magnetic
potential or its gradients (state.u, state.ux, and so on), then initial conditions must not depend
on the magnetic flux density (state.NormFluxDensity).
Examples
Specify initial flux density for an femodel object representing a nonlinear magnetostatic problem.
Create an femodel object for solving a magnetostatic problem, and assign the L-shaped membrane
geometry to the model.
pdegplot(model.Geometry,FaceLabels="on");
5-88
faceIC
model.FaceIC = faceIC(NormFluxDensity=1.5);
model.FaceIC
ans =
1x3 faceIC array
model.FaceIC(1) = faceIC(NormFluxDensity=5);
model.FaceIC
ans =
1x3 faceIC array
5-89
5 Functions
Create an femodel object for solving a transient thermal problem, and assign the geometry to the
model.
Set the initial temperature in the rectangle to be dependent on the y-coordinate, for example,
3
10 0 . 2 − y2 .
T0 = @(location)10^3*(0.2 - location.y.^2);
model.FaceIC = faceIC(Temperature=T0);
model.FaceIC
ans =
1x1 faceIC array
Index Temperature
1 @(location)10^3*(0.2-location.y.^2)
Version History
Introduced in R2023a
See Also
Objects
femodel | fegeometry | cellIC | edgeIC | vertexIC
Functions
filterByIndex
5-90
edgeIC
edgeIC
Initial conditions on geometry edge
Description
An edgeIC object specifies the type of initial condition on an edge of a geometry. An femodel object
contains an array of edgeIC objects in its EdgeIC property.
For separate assignments to a geometric region (or the entire geometry) 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 EdgeIC assignment precedence over a FaceIC assignment,
even if you specify a FaceIC assignment after an EdgeIC assignment. The assignments in order of
precedence are VertexIC (highest precedence), EdgeIC, FaceIC, and CellIC (lowest precedence).
Creation
Syntax
model.EdgeIC(EdgeID) = edgeIC(Name=Value)
model.EdgeIC = edgeIC(Name=Value)
Description
model.EdgeIC = edgeIC(Name=Value) assigns the specified initial condition to all edges of the
geometry. For example, model.EdgeIC = edgeIC(Temperature=25) specifies the initial
temperature on all edges.
Input Arguments
Edge IDs, specified as a vector of positive integers. Find the edge IDs using pdegplot with the
EdgeLabels value set to "on".
Data Types: double
Properties
Displacement — Initial displacement
numeric vector | function handle
5-91
5 Functions
Initial displacement, 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 displacement.
Use a function handle to specify spatially varying initial displacement. 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. For details, see
“Nonconstant Parameters of Finite Element Model” on page 2-149.
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.
Use a function handle to specify spatially varying 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. For details, see
“Nonconstant Parameters of Finite Element Model” on page 2-149.
Initial temperature or initial guess for temperature, specified as a real number or function handle.
Use a function handle to specify spatially varying initial temperature. For details, see “Nonconstant
Parameters of Finite Element Model” on page 2-149.
Examples
Initial Displacement
Specify initial displacement for an femodel object representing a transient structural problem.
Create an femodel object for solving a transient structural problem, and assign the unit square
geometry to the model.
pdegplot(model.Geometry,EdgeLabels="on");
xlim([-1.1 1.1])
ylim([-1.1 1.1])
5-92
edgeIC
The default initial displacement on the entire geometry is zero. Specify a small nonzero initial
displacement on edge 1.
ans =
1x4 edgeIC array
Initial Temperature
Specify initial temperature for an femodel object representing a transient thermal problem.
5-93
5 Functions
Create an femodel object for solving a transient thermal problem, and assign the unit circle
geometry to the model.
model = femodel(AnalysisType="thermalTransient", ...
Geometry=@circleg);
Because there is no default initial temperature, you must first specify the initial temperature for the
entire geometry.
model.FaceIC = faceIC(Temperature=0);
model.FaceIC
ans =
1x1 faceIC array
Index Temperature
1 0
5-94
edgeIC
model.EdgeIC = edgeIC(Temperature=0.1);
model.EdgeIC
ans =
1x4 edgeIC array
Index Temperature
1 0.1000
2 0.1000
3 0.1000
4 0.1000
Version History
Introduced in R2023a
See Also
Objects
femodel | fegeometry | cellIC | faceIC | vertexIC
5-95
5 Functions
vertexIC
Initial conditions on geometry vertex
Description
A vertexIC object specifies the type of initial condition on a vertex of a geometry. An femodel
object contains an array of vertexIC objects in its VertexIC property.
For separate assignments to a geometric region (or the entire geometry) 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 EdgeIC assignment precedence over a FaceIC assignment,
even if you specify a FaceIC assignment after an EdgeIC assignment. The assignments in order of
precedence are VertexIC (highest precedence), EdgeIC, FaceIC, and CellIC (lowest precedence).
Creation
Syntax
model.VertexIC(VertexID) = vertexIC(Name=Value)
model.VertexIC = vertexIC(Name=Value)
Description
Input Arguments
Vertex IDs, specified as a vector of positive integers. Find the vertex IDs using pdegplot with the
VertexLabels value set to "on".
Data Types: double
5-96
vertexIC
Properties
Displacement — Initial displacement
numeric vector | function handle
Initial displacement, 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 displacement.
Use a function handle to specify spatially varying initial displacement. 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. For details, see
“Nonconstant Parameters of Finite Element Model” on page 2-149.
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.
Use a function handle to specify spatially varying 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. For details, see
“Nonconstant Parameters of Finite Element Model” on page 2-149.
Initial temperature or initial guess for temperature, specified as a real number or function handle.
Use a function handle to specify spatially varying initial temperature. For details, see “Nonconstant
Parameters of Finite Element Model” on page 2-149.
Examples
Initial Displacement
Specify initial displacement for an femodel object representing a transient structural problem.
Create an femodel object for solving a transient structural problem, and assign the unit square
geometry to the model.
pdegplot(model.Geometry,VertexLabels="on");
xlim([-1.1 1.1])
ylim([-1.1 1.1])
5-97
5 Functions
The default initial displacement on the entire geometry is zero. Specify a small nonzero initial
displacement on vertex 1.
ans =
1x4 vertexIC array
Initial Temperature
Specify initial temperature for an femodel object representing a transient thermal problem.
5-98
vertexIC
Create an femodel object for solving a transient thermal problem, and assign the unit square
geometry to the model.
model = femodel(AnalysisType="thermalTransient", ...
Geometry=@squareg);
Because there is no default initial temperature, you must specify the initial temperature for the entire
geometry.
model.FaceIC = faceIC(Temperature=0);
model.FaceIC
ans =
1x1 faceIC array
Index Temperature
1 0
5-99
5 Functions
model.VertexIC = vertexIC(Temperature=0.1);
model.VertexIC
ans =
1x4 vertexIC array
Index Temperature
1 0.1000
2 0.1000
3 0.1000
4 0.1000
Version History
Introduced in R2023a
See Also
Objects
femodel | fegeometry | cellIC | faceIC | edgeIC
5-100
materialProperties
materialProperties
Material properties for structural, thermal, and electromagnetic analysis
Description
A materialProperties object contains the description of material properties for structural,
thermal, and electromagnetic analysis. An femodel object contains an array of
materialProperties objects in its MaterialProperties property.
Creation
Syntax
model.MaterialProperties = materialProperties(Name=Value)
model.MaterialProperties(RegionID) = materialProperties(Name=Value)
Description
Input Arguments
Cell or face IDs, specified as a vector of positive integers. Find the region IDs using pdegplot with
the CellLabels (3-D) or FaceLabels (2-D) value set to "on".
Data Types: double
Properties
YoungsModulus — Young's modulus
positive number | three-element vector of positive numbers | function handle
Young's modulus of the material, specified as a positive number, three-element vector of positive
numbers (for both 2-D and 3-D geometries), or function handle. Use a function handle to specify
Young's modulus that depends on space. For details, see “Nonconstant Parameters of Finite Element
Model” on page 2-149.
Specifying Young's modulus as a three-element vector of positive numbers (or a function handle
returning a three-row matrix of positive numbers) means that the material is orthotropic. A matrix of
5-101
5 Functions
positive numbers specifies the orthotropic Young's modulus along the Cartesian coordinates x, y, and
z as [Ex Ey Ez]. For orthotropic materials, you must also specify a shear modulus and Poisson's ratio as
three-row matrices of positive numbers or function handles returning three-row matrices of positive
numbers.
Data Types: double
Poisson's ratio of the material, specified as a positive number, three-element vector of positive
numbers (for both 2-D and 3-D geometries), or function handle. Use a function handle to specify
Poisson's ratio that depends on space. For details, see “Nonconstant Parameters of Finite Element
Model” on page 2-149. For isotropic materials, the value must be in the range (0,0.5).
Specifying Poisson's ratio as a three-element vector of positive numbers (or a function handle
returning a three-row matrix of positive numbers) means that the material is orthotropic. A matrix of
positive numbers specifies the orthotropic Poisson's ratio along the Cartesian coordinates x, y, and z
as [νxy νyz νxz]. For orthotropic materials, you must also specify Young's modulus and a shear modulus
as three-element vectors of positive numbers or function handles returning three-row matrices of
positive numbers.
Data Types: double
Shear modulus of the material, specified as a three-element vector of positive numbers (for both 2-D
and 3-D geometries), or function handle. Specify shear modulus for orthotropic materials. Use a
function handle to specify shear modulus that depends on space. For details, see “Nonconstant
Parameters of Finite Element Model” on page 2-149.
Specifying a shear modulus indicates that the material is orthotropic. A matrix of positive numbers
specifies the orthotropic shear modulus along the Cartesian coordinates x, y, and z as [Gxy Gyz Gxz].
For orthotropic materials, you must also specify Young's modulus and Poisson's ratio as three-element
vectors of positive numbers or function handles returning three-row matrices of positive numbers.
Data Types: double
Mass density of the material, specified as a positive number or function handle. Use a function handle
to specify mass density that depends on space. For details, see “Nonconstant Parameters of Finite
Element Model” on page 2-149. This property is required when modeling gravitational effects.
Data Types: double
Coefficient of thermal expansion of the material, specified as a real number. This property is required
for thermal stress analysis. Thermal stress analysis requires the structural model to be static.
Data Types: double
5-102
materialProperties
Thermal conductivity of the material, specified as a nonnegative number, matrix, or function handle.
You can specify thermal conductivity for a steady-state or transient analysis. For orthotropic thermal
conductivity, use a thermal conductivity matrix. Use a function handle to specify a thermal
conductivity that depends on space, time, or temperature. For details, see “Nonconstant Parameters
of Finite Element Model” on page 2-149.
Data Types: double | function_handle
Specific heat of the material, specified as a positive number or function handle. Specify this property
for a transient thermal conduction analysis. Use a function handle to specify a specific heat that
depends on space, time, or temperature. For details, see “Nonconstant Parameters of Finite Element
Model” on page 2-149.
Data Types: double | function_handle
Hysteretic damping of the material, specified as a nonnegative number. This type of damping is also
called structural damping.
Data Types: double
Relative permeability of the material, specified as a number or function handle. For a magnetostatic
analysis:
5-103
5 Functions
ElectricalConductivity — Conductivity
nonnegative number | function handle
Conductivity of the material, specified as a nonnegative number or function handle. Use a function
handle to specify a conductivity that depends on the coordinates and, for a harmonic analysis, on the
frequency. For details, see “Nonconstant Parameters of Finite Element Model” on page 2-149.
Data Types: double | function_handle
Examples
Create an femodel object for solving a magnetostatic problem, and assign a geometry representing a
plate with a hole to the model.
pdegplot(model.Geometry,FaceLabels="on");
5-104
materialProperties
model.MaterialProperties = materialProperties(RelativePermeability=5000);
model.MaterialProperties
ans =
1x1 materialProperties array
Index RelativePermeability
1 5000
Specify Young's modulus, Poisson's ratio, and the mass density for an femodel object representing a
static structural problem.
5-105
5 Functions
H = 0.1;
gm = multicuboid(0.5,0.1,[H,H],Zoffset=[0,H]);
pdegplot(gm,CellLabels="on");
Create an femodel object for solving a static structural problem, and assign the geometry to the
model.
model = femodel(AnalysisType="structuralStatic", ...
Geometry=gm);
Specify different values of Young's modulus, Poisson's ratio, and the mass density for cells 1 and 2.
model.MaterialProperties(1) = materialProperties(YoungsModulus=210e9, ...
PoissonsRatio=0.28, ...
MassDensity=1.3e-5);
model.MaterialProperties(2) = materialProperties(YoungsModulus=110e9, ...
PoissonsRatio=0.37, ...
MassDensity=2.4e-5);
model.MaterialProperties
ans =
1x2 materialProperties array
5-106
materialProperties
Use function handles to specify a thermal conductivity that depends on temperature and a specific
heat that depends on coordinates.
Create an femodel object for solving a transient thermal problem, and assign the geometry to the
model.
k = @(location,state)40 + 0.003*state.u;
cp = @(location,state)500*location.y;
Specify the thermal conductivity, mass density, and specific heat of the material.
ans =
1x1 materialProperties array
Use a function handle to specify a relative permeability that depends on the magnetic flux density.
Create an femodel object for solving a magnetostatic problem, and assign a geometry representing a
plate with a hole to the model.
5-107
5 Functions
Specify the data for the magnetic flux density, B, and the corresponding magnetic field strength, H.
B = [0 .3 .8 1.12 1.32 1.46 1.54 1.61875 1.74];
H = [0 29.8 79.6 159.2 318.31 795.8 1591.6 3376.7 7957.8];
From the data for B and H, interpolate the H(B) dependency using the modified Akima cubic Hermite
interpolation method.
HofB = griddedInterpolant(B,H,"makima","linear");
muR = @(B) B./HofB(B)/mu0;
Specify the relative permeability that depends on the magnetic flux density.
model.MaterialProperties = materialProperties(RelativePermeability=muR);
model.MaterialProperties
ans =
1x1 materialProperties array
5-108
materialProperties
Index RelativePermeability
1 @(B)B./HofB(B)/mu0
Use vector values to specify Young's modulus, Poisson's ratio, and shear modulus representing an
orthotropic material.
Create an femodel object for solving a static structural problem, and assign a geometry representing
a cube with a cylindrical hole to the model.
pdegplot(model.Geometry,FaceAlpha=0.3);
5-109
5 Functions
Specify Young's modulus, Poisson's ratio, shear modulus, and the mass density. For an orthotropic
material, all parameters, except the mass density, must be 1-by-3 vector of positive numbers.
E = [22E9,9.8E9,22E9];
nu = [0.28,0.28,0.11];
G = [3.5E9,3.5E9,2.5E9];
rho = 1.3e-5;
model.MaterialProperties = materialProperties(YoungsModulus=E, ...
PoissonsRatio=nu, ...
ShearModulus=G, ...
MassDensity=rho);
model.MaterialProperties
ans =
1x1 materialProperties array
Version History
Introduced in R2023a
See Also
Functions
generateMesh | solve | pdegplot | pdemesh
Objects
femodel | fegeometry | edgeBC | faceBC | vertexBC | farFieldBC | cellLoad | faceLoad |
edgeLoad | vertexLoad | cellIC | faceIC | edgeIC | vertexIC
5-110
filterByIndex
filterByIndex
Package: pde
Syntax
subsetR = filterByIndex(results,inds)
Description
subsetR = filterByIndex(results,inds) accesses transient results corresponding to the
specified time steps.
Examples
Create an femodel object for solving a transient thermal problem, and assign a geometry
representing a cylinder to the model.
pdegplot(model,FaceLabels="on",FaceAlpha=0.5);
5-111
5 Functions
Assuming that the heat sink is made of copper, specify the thermal conductivity, mass density, and
specific heat.
model.MaterialProperties = ...
materialProperties(ThermalConductivity=400, ...
MassDensity=8960, ...
SpecificHeat=386);
Apply the temperature boundary condition on the bottom surface of the cylinder.
model.FaceBC(1) = faceBC(Temperature=1000);
Specify the convection and radiation parameters on the top and side surfaces of the cylinder.
model.FaceLoad([2 3]) = faceLoad(ConvectionCoefficient=5, ...
AmbientTemperature=300, ...
Emissivity=0.8);
Generate a mesh.
model = generateMesh(model);
5-112
filterByIndex
results = solve(model,0:0.1:0.2);
Plot the temperature distribution for each time step. Access the results for each step by using the
filterByIndex function.
for i = 1:length(results.SolutionTimes)
figure
resultsByStep = filterByIndex(results,i);
pdeplot3D(results.Mesh,ColorMapData=resultsByStep.Temperature);
clim([300 1000])
title({['Time = ' num2str(results.SolutionTimes(i)) 's']})
end
5-113
5 Functions
5-114
filterByIndex
Now, use the transient thermal results obtained for the second time step as the initial temperature of
the cylinder.
R = filterByIndex(results,2);
model.CellIC = cellIC(Temperature=R);
Solve the transient thermal problem for the 10 time steps between 0.1 and 0.11 second.
results_01_011 = solve(model,linspace(0.1,0.11,10));
Input Arguments
results — Solution of structural or thermal problem
TransientStructuralResults object | TransientThermalResults object
5-115
5 Functions
Output Arguments
subsetR — Solutions corresponding to specified time steps
TransientStructuralResults object | TransientThermalResults object
Version History
Introduced in R2023b
See Also
Objects
TransientStructuralResults | TransientThermalResults
5-116
adaptmesh
adaptmesh
Package: pde
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,Name,Value)
Description
[u,p,e,t] = adaptmesh(g,b,c,a,f) generates an adaptive [p,e,t] mesh and returns the
solution u for an elliptic 2-D PDE problem
− ∇ ⋅ 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.
• Adaption completed. (This means that the Tripick function returned zero triangles to refine.)
• Maximum number of triangles obtained.
• Maximum number of refinement passes obtained.
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 the options so that adaptmesh refines the triangles using the worst error
criterion until it obtains a mesh with at least 500 triangles.
c45 = cos(pi/4);
L1 = [2 -c45 0 c45 0 1 0 0 0 0]';
5-117
5 Functions
[u,p,e,t] = adaptmesh(g,"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))
ans = 0.0028
size(t,2)
ans = 699
pdemesh(p,e,t)
5-118
adaptmesh
Test how many refinements you need with a uniform triangle mesh.
[p,e,t] = initmesh(g);
[p,e,t] = refinemesh(g,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.0116
ans = 816
Refine the mesh one more time. The maximal absolute error for uniform meshing is still greater than
for adaptive meshing.
[p,e,t] = refinemesh(g,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.0075
5-119
5 Functions
size(t,2)
ans = 3264
pdemesh(p,e,t)
Uniform refinement with more triangles produces a larger error. Typically, a problem with regular
2
solution has an O(h ) error. However, this solution is singular since u ≈ r 1/3 at the origin.
Input Arguments
g — Geometry description
decomposed geometry matrix | geometry function | handle to geometry function
A geometry function must return the same result for the same input arguments in every function call.
Thus, it must not contain functions and expressions designed to return a variety of results, such as
random number generators.
5-120
adaptmesh
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. Typically, you export a boundary matrix from the PDE Modeler app.
Example: b = 'circleb1', b = "circleb1", or b = @circleb1
Data Types: double | char | string | function_handle
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
The coefficients c, a, and f can depend on the solution u if you use the nonlinear solver by setting the
value of "Nonlin" to "on". The coefficients cannot be functions of the time t.
Example: "cosh(x+y.^2)"
Data Types: double | char | string | function_handle
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
The coefficients c, a, and f can depend on the solution u if you use the nonlinear solver by setting the
value of "Nonlin" to "on". The coefficients cannot be functions of the time t.
Example: 2*eye(3)
Data Types: double | char | string | function_handle
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
5-121
5 Functions
− ∇ ⋅ c ⊗ ∇u + au = f
The coefficients c, a, and f can depend on the solution u if you use the nonlinear solver by setting the
value of "Nonlin" to "on". The coefficients cannot be function of the time t.
Example: char("sin(x)";"cos(y)";"tan(z)")
Data Types: double | char | string | function_handle
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: [u,p,e,t] =
adaptmesh(g,"cirsb",1,0,0,"Maxt",500,"Tripick","pdeadworst","Ngen",Inf)
Maximum number of new triangles, specified as the comma-separated pair consisting of "Maxt" and
a positive integer.
Data Types: double
Initial mesh, specified as the comma-separated pair consisting of "Mesh" and a mesh specified by
[p,e,t] triples. By default, the function uses the mesh generated by the initmesh function.
Data Types: double
Triangle selection method, specified as the comma-separated pair consisting of "Tripick" and a
MATLAB function. By default, the function uses the indices of triangles returned by the pdeadworst
function.
Given the error estimate computed by the function pdejmps, the triangle selection method identifies
the triangles to be refined in the next triangle generation. The function is called using the arguments
p, t, cc, aa, ff, u, errf, and Par.
5-122
adaptmesh
The matrices cc, aa, ff, and errf all have Nt columns, where Nt is the current number of triangles.
The numbers of rows in cc, aa, and ff are exactly the same as the input arguments c, a, and f. errf
has one row for each equation in the system. The two standard triangle selection methods are
pdeadworst and pdeadgsc.
• pdeadworst identifies triangles where errf exceeds a fraction of the worst value. The default
fraction value is 0.5. You can change it by specifying the Par argument value when calling
adaptmesh.
• pdeadgsc selects triangles using a relative tolerance criterion.
Function parameter for the triangle selection method, specified as the comma-separated pair
consisting of "Par" and a number between 0 and 1. The pdeadworst triangle selection method uses
it as its wlevel argument. The pdeadgsc triangle selection method uses it as its tol argument.
Data Types: double
Triangle refinement method, specified as the comma-separated pair consisting of "Rmethod" and
either "longest" or "regular". For details on the refinement method, see refinemesh.
Data Types: char | string
Toggle to use a nonlinear solver, specified as the comma-separated pair consisting of "Nonlin" and
"on" or "off".
Data Types: char | string
Nonlinear tolerance, specified as the comma-separated pair consisting of "Toln" and a positive
number. The function passes this argument to pdenonlin, which iterates until the magnitude of the
residual is less than Toln.
Data Types: double
Nonlinear initial value, specified as the comma-separated pair consisting of "Init" and a scalar, a
vector of characters, or a vector of numbers. The function passes this argument to pdenonlin, which
uses it as an initial guess in its "U0" argument.
5-123
5 Functions
Nonlinear Jacobian calculation, specified as the comma-separated pair consisting of "Jac" and either
"fixed", "lumped", or "full". The function passes this argument to pdenonlin, which uses it as
an initial guess in its "Jacobian" argument.
Data Types: char | string
Nonlinear solver residual norm, specified as the comma-separated pair consisting of "Norm" and p
value for 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). The function passes this argument to pdenonlin, which uses it as an
initial guess in its "Norm" argument.
Data Types: double | char | string
Algorithm for generating initial mesh, specified as the comma-separated pair consisting of
"MesherVersion" and either "R2013a" or "preR2013a". The "R2013a" algorithm runs faster,
and can triangulate more geometries than the "preR2013a" algorithm. Both algorithms use
Delaunay triangulation.
Data Types: char | string
Output Arguments
u — PDE solution
vector
• If the PDE is scalar, meaning that it 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 represent the solution of
equation 1, the next Np elements represent the solution of equation 2, and so on.
p — Mesh points
2-by-Np matrix
Mesh points, returned as a 2-by-Np matrix. 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) and the y-coordinate of point k in p(2,k). For
details, see “Mesh Data as [p,e,t] Triples” on page 2-181.
e — Mesh edges
7-by-Ne matrix
5-124
adaptmesh
Mesh edges, returned as a 7-by-Ne matrix. 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 as [p,e,t] Triples” on page 2-181.
t — Mesh elements
4-by-Nt matrix
Mesh elements, returned as a 4-by-Nt matrix. Nt is the number of triangles in the mesh.
The t(i,k), with i ranging from 1 through end-1, contain indices to the corner points of element k.
For details, see “Mesh Data as [p,e,t] Triples” on page 2-181. The last row, t(end,k), contains the
subdomain numbers of the elements.
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 mid-sides, 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 efficient to refine the
mesh selectively. The selection that is based on estimates of errors in the computed solutions is called
adaptive mesh refinement.
The adaptive refinement generates a sequence of solutions on successively finer meshes, at each
stage selecting and refining those elements that are judged to contribute most to the error. The
process stops34 when the maximum number of elements is exceeded, when each triangle contributes
less than a preset tolerance, or when an iteration limit is reached. You can provide an initial mesh, or
let adaptmesh call initmesh automatically. You also choose selection and termination criteria
parameters. The three components of the algorithm are the error indicator function (computes an
estimate of the element error contribution), the mesh refiner (selects and subdivides elements), and
the termination criteria.
The adaptation is a feedback process. It is easily applied to a larger range of problems than those for
which its design was tailored. Estimates, selection criteria, and so on must be optimal for giving the
most accurate solution at fixed cost or lowest computational effort for a given accuracy. Such results
have been proven only for model problems, but generally, the equidistribution heuristic has been
found nearly 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.
The error indicator function used in the software is an elementwise estimate of the contribution,
based on [1] and [2]. For Poisson's equation –Δu = f on Ω, the following error estimate for the FEM-
solution uh holds in the L2-norm ⋅ :
5-125
5 Functions
∂v 2 1/2
2
Dh(v) = ∑ hτ
∂nτ
τ ∈ E1
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 2
2 τ ∈∑∂K τ τ
E K = α h f − au K+β h n · c ∇uh
where nτ 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.
Partial Differential Equation Toolbox mesh refinement is geared to elliptic problems. For reasons of
accuracy and ill-conditioning, such problems require the elements not to deviate too much from being
equilateral. Thus, even at essentially one-dimensional solution features, such as boundary layers, the
refinement technique must guarantee reasonably shaped triangles.
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 in [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.
There are two selection criteria. 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 specified dimensionless tolerance. The comparison with the tolerance is
properly scaled with respect to domain, solution size, and so on.
For smooth solutions, error equidistribution can be achieved by the pdeadgsc selection if the
maximum number of elements is large enough. The pdeadworst adaptation only terminates when
the maximum number of elements has been exceeded or when the iteration limit is reached. This
mode is natural when the solution exhibits singularities. The error indicator of the elements next to
the singularity might never vanish, regardless of element size, making equidistribution impossible.
Version History
Introduced before R2006a
5-126
adaptmesh
adaptmesh provides an enhancement option for increased meshing speed and robustness. Choose
the enhanced algorithm by setting the MesherVersion name-value pair to 'R2013a'. The default
MesherVersion value of 'preR2013a' gives the same mesh as previous toolbox versions.
The enhancement is available inpdeModeler from the Mesh > Parameters > Mesher version
menu.
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.
[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
Topics
“Mesh Data as [p,e,t] Triples” on page 2-181
5-127
5 Functions
addCell
Combine two geometries by adding one inside a cell of another
Syntax
g3 = addCell(g1,g2)
Description
g3 = addCell(g1,g2) creates nonempty cells inside g1 using all cells of g2. All cells of the
geometry g2 must be contained inside one cell of the geometry g1. Ensure that the geometries do not
have enclosed cavities and do not intersect one another.
The combined geometry contains cells from both geometries. The cells from g1 retain their original
IDs, while the cells from g2 are numbered starting with N+1, where N is the number of cells in g1.
Note After modifying a geometry, always call generateMesh to ensure a proper mesh association
with the new geometry.
Examples
g1 = multicuboid(2,2,2,"Zoffset",-1);
pdegplot(g1,"CellLabels","on","FaceAlpha",0.5)
5-128
addCell
g2 = importGeometry("DampingMounts.stl");
pdegplot(g2,"CellLabels","on","FaceAlpha",0.5)
5-129
5 Functions
Scale and move the second geometry to fit entirely within the cube g1.
pdegplot(g2,"CellLabels","on","FaceAlpha",0.5)
5-130
addCell
Combine the geometries and plot the result. The combined geometry g3 contains cells from both
geometries. The cell from g1 keeps its ID, and the cells from g2 are now C2, C3, C4, and C5.
g3 = addCell(g1,g2);
pdegplot(g3,"CellLabels","on","FaceAlpha",0.4)
5-131
5 Functions
Input Arguments
g1 — 3-D geometry
fegeometry object | DiscreteGeometry object
g2 — 3-D geometry
fegeometry object | DiscreteGeometry object
Output Arguments
g3 — Resulting 3-D geometry
fegeometry object | DiscreteGeometry object
Version History
Introduced in R2021a
5-132
addCell
See Also
Functions
addFace | addVertex | addVoid
Objects
fegeometry | DiscreteGeometry
5-133
5 Functions
addFace
Package: pde
Syntax
h = addFace(g,edges)
[h,FaceID] = addFace(g,edges)
Description
h = addFace(g,edges) adds a new face to the geometry g. The specified edges must form a closed
contour. For a 2-D geometry, adding a new face lets you fill voids in the geometry. For a 3-D geometry,
adding a new face lets you split one cell into multiple cells.
You can add several new faces simultaneously by specifying their contours in a cell array. Each
contour in the cell array must be unique.
Note After modifying a geometry, always call generateMesh to ensure a proper mesh association
with the new geometry.
[h,FaceID] = addFace(g,edges) also returns a row vector containing IDs of the added faces.
Examples
gm =
DiscreteGeometry with properties:
NumCells: 0
NumFaces: 1
NumEdges: 8
NumVertices: 8
Vertices: [8x3 double]
5-134
addFace
pdegplot(gm,"FaceLabels","on")
Zoom in and display the edge labels of the small hole at the center.
figure
pdegplot(gm,"EdgeLabels","on")
axis([49 51 99 101])
5-135
5 Functions
Fill the hole by adding a face. The number of faces in the geometry changes to 2.
gm = addFace(gm,[1 8 4 5])
gm =
DiscreteGeometry with properties:
NumCells: 0
NumFaces: 2
NumEdges: 8
NumVertices: 8
Vertices: [8x3 double]
pdegplot(gm,"FaceLabels","on")
5-136
addFace
model = createpde();
gm = importGeometry(model,"MotherboardFragment1.stl")
gm =
DiscreteGeometry with properties:
NumCells: 1
NumFaces: 26
NumEdges: 46
NumVertices: 34
Vertices: [34x3 double]
Plot the geometry and display the edge labels. Zoom in on the corresponding part of the geometry to
see the edge labels there more clearly.
5-137
5 Functions
pdegplot(gm,"EdgeLabels","on","FaceAlpha",0.5)
xlim([-0.05 0.05])
ylim([-0.05 0.05])
zlim([0 0.05])
Split the cuboid on the right side into a separate cell. For this, add a face bounded by edges 1, 3, 6,
and 12.
gm =
DiscreteGeometry with properties:
NumCells: 2
NumFaces: 27
NumEdges: 46
NumVertices: 34
Vertices: [34x3 double]
ID = 27
pdegplot(gm,"CellLabels","on","FaceAlpha",0.5)
5-138
addFace
Now split the cuboid on the left side of the board and all cylinders into separate cells by adding a face
at the bottom of each shape. To see edge labels more clearly, zoom and rotate the plot. Use a cell
array to add several new faces simultaneously.
[gm,IDs] = addFace(gm,{[5 7 8 10], ...
30, ...
31, ...
32, ...
33, ...
13})
gm =
DiscreteGeometry with properties:
NumCells: 8
NumFaces: 33
NumEdges: 46
NumVertices: 34
Vertices: [34x3 double]
IDs = 6×1
28
29
30
31
32
5-139
5 Functions
33
pdegplot(gm,"CellLabels","on","FaceAlpha",0.5)
Input Arguments
g — Geometry
fegeometry object | DiscreteGeometry object | AnalyticGeometry object
Edges forming a unique closed flat contour, specified as a vector of positive integers or a cell array of
such vectors. You can specify edges within a vector in any order.
When you use a cell array to add several new faces, each contour in the cell array must be unique.
Example: addFace(g,[1 3 4 7])
5-140
addFace
Output Arguments
h — Resulting geometry
fegeometry object | handle
FaceID — Face ID
positive number | row vector of positive numbers
Face ID, returned as a positive number or a row vector of positive numbers. Each number represents
a face ID. When you add a new face to a geometry with N faces, the ID of the added face is N + 1.
Tips
• addFace errors when the specified contour defines an already existing face.
• If the original geometry g is a DiscreteGeometry or AnalyticGeometry object, addFace
modifies the original geometry g.
• If the original geometry g is an fegeometry object, and you want to replace it with the modified
geometry, assign the output to the original geometry, for example, g = addFace(g,[1 3 4 7]).
Version History
Introduced in R2020a
addFace now lets you fill void regions in 2-D AnalyticGeometry objects.
See Also
Functions
addVertex | pdegplot | importGeometry | geometryFromMesh | generateMesh | mergeCells |
structuralBoundaryLoad | structuralBC
Objects
fegeometry | DiscreteGeometry | AnalyticGeometry
5-141
5 Functions
addVertex
Package: pde
Syntax
VertexID = addVertex(g,"Coordinates",Coords)
Description
VertexID = addVertex(g,"Coordinates",Coords) adds a new isolated vertex at the point with
coordinates Coords to a boundary of the geometry g. To add several vertices simultaneously, specify
Coords as an N-by-2 matrix for a 2-D geometry or an N-by-3 matrix for a 3-D geometry. Here, N is the
number of new points.
If a point with the specified coordinates is slightly offset (within an internally specified tolerance)
from a geometry boundary, addVertex approximates it to a point on the boundary. If a vertex already
exists at the specified location, addVertex returns the ID of the existing vertex instead of creating
one.
Examples
Use addVertex to add a single vertex and multiple vertices on a side of a block geometry.
model = createpde();
g = importGeometry(model,"Block.stl");
5-142
addVertex
VertexID = 9
5-143
5 Functions
VertexIDs = 3×1
10
11
12
5-144
addVertex
Add a vertex at the corner of the block. Since there is already a vertex at the corner, addVertex does
not create a new vertex, but returns the ID of the existing vertex.
VertexID = 5
Input Arguments
g — Geometry
fegeometry object | DiscreteGeometry object
Coordinates of a new vertex, specified as an N-by-2 or N-by-3 numeric matrix for a 2-D or 3-D
geometry, respectively. Here, N is the number of new vertices.
Example: "Coordinates",[0 0 1]
Data Types: double
5-145
5 Functions
Output Arguments
VertexID — Vertex ID
row vector
Vertex ID, returned as a row vector of positive numbers. Each number represents a vertex ID. When
you add a new vertex to a geometry with N vertices, the ID of the added vertex is N + 1. If a vertex
already exists at the specified location, addVertex returns the ID of the existing vertex.
Limitations
• addVertex does not work with AnalyticGeometry objects.
Version History
Introduced in R2019b
See Also
Functions
addFace | pdegplot | importGeometry | geometryFromMesh | generateMesh | mergeCells |
structuralBoundaryLoad | structuralBC
Objects
fegeometry | DiscreteGeometry
5-146
addVoid
addVoid
Create void regions inside 3-D geometry
Syntax
g3 = addVoid(g1,g2)
Description
g3 = addVoid(g1,g2) creates void regions inside g1 using all cells of g2. All cells of the geometry
g2 must be contained inside one cell of the geometry g1. Ensure that the geometries do not have
enclosed cavities and do not intersect one another.
Note After modifying a geometry, always call generateMesh to ensure a proper mesh association
with the new geometry.
Examples
g1 = multicuboid(2,2,2,"Zoffset",-1);
pdegplot(g1,"CellLabels","on","FaceAlpha",0.5)
5-147
5 Functions
g2 = importGeometry("DampingMounts.stl");
pdegplot(g2,"CellLabels","on","FaceAlpha",0.5)
5-148
addVoid
Scale and move the second geometry to fit entirely within the cube g1.
pdegplot(g2,"CellLabels","on","FaceAlpha",0.5)
5-149
5 Functions
Create void regions inside the cube using the cells of the geometry g2. Plot the result.
g3 = addVoid(g1,g2);
pdegplot(g3,"CellLabels","on","FaceAlpha",0.4)
5-150
addVoid
Input Arguments
g1 — 3-D geometry
fegeometry object | DiscreteGeometry object
g2 — 3-D geometry
fegeometry object | DiscreteGeometry object
Output Arguments
g3 — Resulting 3-D geometry
fegeometry object | DiscreteGeometry object
Version History
Introduced in R2021a
5-151
5 Functions
See Also
Functions
addCell | addFace | addVertex
Objects
fegeometry | DiscreteGeometry
5-152
AnalyticGeometry
AnalyticGeometry
Analytic 2-D geometry description
Description
AnalyticGeometry describes a 2-D geometry in the form of an analytic geometry object. PDEModel,
StructuralModel, and ThermalModel objects have a Geometry property, which can be an
AnalyticGeometry or DiscreteGeometry object.
Creation
Add a 2-D analytic geometry to your model by using decsg to create the geometry and
geometryFromEdges to attach it to the model.
Properties
NumEdges — Number of geometry edges
positive integer
Number of geometry faces, specified as a positive integer. If your geometry is one connected region,
then NumFaces = 1.
Data Types: double
Coordinates of geometry vertices, specified as an N-by-2 numeric matrix where N is the number of
vertices.
Data Types: double
Object Functions
faceEdges Find edges belonging to specified faces
facesAttachedToEdges Find faces attached to specified edges
5-153
5 Functions
Examples
Create a decomposed solid geometry model representing a rectangle and include it in a PDE model.
model = createpde;
R1 = [3,4,-1,1,1,-1,0.5,0.5,-0.75,-0.75]';
g = decsg(R1);
geometryFromEdges(model,g);
pdegplot(model,EdgeLabels="on")
axis equal
xlim([-1.1,1.1])
ylim([-0.9,0.6])
5-154
AnalyticGeometry
Version History
Introduced in R2015a
See Also
Functions
geometryFromEdges | decsg
Objects
DiscreteGeometry | PDEModel | StructuralModel | ThermalModel
Topics
“Solve Problems Using PDEModel Objects” on page 2-3
5-155
5 Functions
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.
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-156
applyBoundaryCondition
applyBoundaryCondition(model,"dirichlet", ...
"Edge",1,"u",0);
applyBoundaryCondition(model,"dirichlet", ...
"Edge",2:4, ...
"r",1,"h",1);
model = createpde(2);
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-157
5 Functions
applyBoundaryCondition(model,"neumann", ...
"Edge",4, ...
"g",[0;.123], ...
"q",[0;0;0;0]);
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");
pdegplot(model,"FaceLabels","on","FaceAlpha",0.5)
5-158
applyBoundaryCondition
Set zero Dirichlet conditions on the narrow faces, which are labeled 1 through 4.
applyBoundaryCondition(model,"dirichlet", ...
"Face",1:4,"u",0);
applyBoundaryCondition(model,"neumann", ...
"Face",5,"g",1);
applyBoundaryCondition(model,"neumann", ...
"Face",6,"g",-1);
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-159
5 Functions
model = createpde(3);
importGeometry(model,"Block.stl");
pdegplot(model,"FaceLabels","on","FaceAlpha",0.5)
5-160
applyBoundaryCondition
For face 3, apply generalized Neumann boundary condition for the first equation and Dirichlet
boundary conditions for the second and third equations.
h = [0 0 0;0 1 0;0 0 1];
r = [0;3;3];
q = [1 0 0;0 0 0;0 0 0];
g = [10;0;0];
applyBoundaryCondition(model,"mixed","Face",3, ...
"h",h,"r",r,"g",g,"q",q);
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);
5-161
5 Functions
u = results.NodalSolution;
pdeplot3D(model,"ColorMapData",u(:,1))
Input Arguments
model — PDE model
PDEModel object
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".
5-162
applyBoundaryCondition
Example: applyBoundaryCondition(model,"dirichlet","Face",3:6,"u",0)
Data Types: double
Dirichlet condition h*u = r, specified as a vector with N elements or a function handle. N is the
number of PDEs in the system. For the syntax of the function handle form of r, see “Nonconstant
Boundary Conditions” on page 2-131.
Example: "r",[0;4;-1]
Data Types: double | function_handle
Complex Number Support: Yes
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-131.
Example: "h",[2,1;1,2]
Data Types: double | function_handle
Complex Number Support: Yes
u — Dirichlet conditions
zeros(N,1) (default) | vector of up to N elements | function handle
5-163
5 Functions
For the syntax of the function handle form of u, see “Nonconstant Boundary Conditions” on page 2-
131.
Example: applyBoundaryCondition(model,"dirichlet","Face",[2,4,11],"u",0)
Data Types: double
Complex Number Support: Yes
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.
When using EquationIndex to specify Dirichlet boundary conditions for a subset of components,
use the mixed argument instead of dirichlet. The remaining components satisfy the default
Neumann boundary condition with the zero values for "g" and "q".
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”. For details of this
evaluation, see “Nonconstant Boundary Conditions” on page 2-131.
Example: applyBoundaryCondition(model,"dirichlet","Face",
[2,4,11],"u",@ucalculator,"Vectorized","on")
Data Types: char | string
Output Arguments
bc — Boundary condition
BoundaryCondition object
Boundary condition, returned as a BoundaryCondition object. The model object contains a vector of
BoundaryCondition objects. bc is the last element of this vector.
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.
5-164
applyBoundaryCondition
• 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".
Version History
Introduced in R2015a
See Also
findBoundaryConditions | BoundaryCondition | PDEModel
Topics
“Specify Boundary Conditions” on page 2-128
“Solve PDEs with Constant Boundary Conditions” on page 2-134
“Specify Nonconstant Boundary Conditions” on page 2-138
“No Boundary Conditions Between Subdomains” on page 2-125
“Identify Boundary Labels” on page 2-127
“Solve Problems Using PDEModel Objects” on page 2-3
5-165
5 Functions
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.
A = area(mesh,elements) returns the combined area of the specified elements of the mesh.
Examples
model = createpde;
Include the geometry of the built-in function lshapeg. Plot the geometry.
geometryFromEdges(model,@lshapeg);
pdegplot(model,"FaceLabels","on")
5-166
area
mesh = generateMesh(model);
figure
pdemesh(model)
5-167
5 Functions
ma = area(mesh)
ma = 3.0000
model = createpde;
Include the geometry of the built-in function lshapeg. Plot the geometry.
geometryFromEdges(model,@lshapeg);
pdegplot(model,"FaceLabels","on")
5-168
area
mesh = generateMesh(model);
figure
pdemesh(model)
5-169
5 Functions
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
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-170
area
mesh = generateMesh(model);
figure
pdemesh(model)
5-171
5 Functions
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
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
5-172
area
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.
Version History
Introduced in R2018a
See Also
volume | findElements | findNodes | meshQuality | FEMesh Properties
Topics
“Finite Element Method Basics” on page 1-11
5-173
5 Functions
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
− ∇ ⋅ ∇u = 1 .
− ∇ ⋅ (c ∇u) + au = f .
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-174
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;
5-175
5 Functions
The returned matrix M has all zeros. The K matrix is quite sparse.
disp(['Fraction of nonzero entries in K is ',num2str(nnz(K)/numel(K))])
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
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
5-176
assema
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
Example: char('sin(x)';'cos(y)';'tan(z)')
Data Types: double | char | string | function_handle
Complex Number Support: Yes
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 as [p,e,t] Triples” on page 2-181.
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
Mesh triangles, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For a description of the (p,e,t) matrices, see “Mesh Data as [p,e,t] Triples” on page 2-181.
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-210.
5-177
5 Functions
M — Mass matrix
sparse matrix
Mass matrix. returned as a sparse matrix. See “Elliptic Equations” on page 5-210.
F — Load vector
vector
Version History
Introduced before R2006a
assema is not recommended. Use assembleFEMatrices instead. There are no plans to remove
assema.
See Also
assembleFEMatrices
5-178
assemb
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(b,p,e) assembles the matrices based on the boundary conditions specified
in b and the mesh data in p and e.
[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
− ∇ ⋅ ∇u = 1 .
− ∇ ⋅ (c ∇u) + au = f .
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');
5-179
5 Functions
h = pdegplot(model,'FaceLabels','on');
h(1).FaceAlpha = 0.5;
Set zero Dirichlet boundary conditions on the narrow faces (numbered 1 through 4).
applyBoundaryCondition(model,'Face',1:4,'u',0);
5-180
assemb
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
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.
Example: b = 'circleb1', b = "circleb1", or b = @circleb1
Data Types: double | char | string | function_handle
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 as [p,e,t] Triples” on page 2-181.
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)
5-181
5 Functions
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 as [p,e,t] Triples” on page 2-181.
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
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 matrix, returned as a sparse matrix. See “Elliptic Equations” on page 5-
210.
Neumann boundary condition vector, returned as a sparse vector. See “Elliptic Equations” on page 5-
210.
H — Dirichlet matrix
sparse matrix
R — Dirichlet vector
sparse vector
5-182
assemb
Algorithms
As explained in “Elliptic Equations” on page 5-210, 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 “More About” on page 5-210 section, and the linear algebra approach detailed in “Systems
of PDEs” on page 5-216.
Version History
Introduced before R2006a
assemb is not recommended. Use assembleFEMatrices instead. There are no plans to remove
assemb.
See Also
assembleFEMatrices
5-183
5 Functions
assembleFEMatrices
Assemble finite element matrices
Syntax
FEM = assembleFEMatrices(model)
FEM = assembleFEMatrices(model,matrices)
FEM = assembleFEMatrices(model,bcmethod)
FEM = assembleFEMatrices( ___ ,state)
Description
FEM = assembleFEMatrices(model) returns a structural array containing all finite element
matrices for a PDE problem specified as a model.
FEM = assembleFEMatrices( ___ ,state) assembles finite element matrices using the input
time or solution specified in the state structure array. The function uses the time field of the
structure for time-dependent models and the solution field u for nonlinear models. You can use this
argument with any of the previous syntaxes.
Examples
Create a PDE model for the Poisson equation on an 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-184
assembleFEMatrices
H: [80x401 double]
R: [80x1 double]
M: [401x401 double]
Create a transient thermal model and include the geometry of the built-in function squareg.
thermalmodel = createpde("thermal","steadystate");
geometryFromEdges(thermalmodel,@squareg);
Specify the thermal conductivity of the material and the internal heat source.
thermalProperties(thermalmodel,"ThermalConductivity",0.2);
internalHeatSource(thermalmodel,10);
5-185
5 Functions
thermalBC(thermalmodel,"Edge",[1,3],"Temperature",100);
Generate a mesh.
generateMesh(thermalmodel);
FEM_KM = assembleFEMatrices(thermalmodel,"KM")
FEM_MKAF = assembleFEMatrices(thermalmodel,"MKAF")
The four matrices M, K, A, and F correspond to discretized versions of the PDE coefficients m, c, a,
and f. These four matrices also represent the domain of the finite-element model of the PDE. Instead
of specifying them explicitly, you can use the domain argument.
FEMd = assembleFEMatrices(thermalmodel,"domain")
The four matrices Q, G, H, and R, correspond to discretized versions of q, g, h, and r in the Neumann
and Dirichlet boundary condition specification. These four matrices also represent the boundary of
the finite-element model of the PDE. Use the boundary argument to assemble only these matrices.
FEMb = assembleFEMatrices(thermalmodel,"boundary")
Create a PDE model for the Poisson equation on an L-shaped membrane with zero Dirichlet boundary
conditions.
5-186
assembleFEMatrices
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.
generateMesh(model,"Hmax",0.2);
Obtain the finite element matrices after imposing the boundary condition using the null-space
approach. This approach eliminates the Dirichlet degrees of freedom and provides a reduced system
of equations.
FEMn = assembleFEMatrices(model,"nullspace")
Obtain the solution to the PDE using the nullspace finite element matrices.
un = FEMn.B*(FEMn.Kc\FEMn.Fc) + FEMn.ud;
Compare this result to the solution given by solvepde. The two solutions are identical.
u1 = solvepde(model);
norm(un - u1.NodalSolution)
ans = 0
Obtain the finite element matrices after imposing the boundary condition using the stiff-spring
approach. This approach retains the Dirichlet degrees of freedom, but imposes a large penalty on
them.
FEMs = assembleFEMatrices(model,"stiff-spring")
Obtain the solution to the PDE using the stiff-spring finite element matrices. This technique gives a
less accurate solution.
us = FEMs.Ks\FEMs.Fs;
norm(us - u1.NodalSolution)
ans = 0.0098
5-187
5 Functions
Assemble finite element matrices for the first and last time steps of a transient structural problem.
structuralmodel = createpde("structural","transient-solid");
Create the geometry and include it in the model. Plot the geometry.
gm = multicylinder(0.01,0.05);
addVertex(gm,"Coordinates",[0,0,0.05]);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,"FaceLabels","on","FaceAlpha",0.5)
structuralProperties(structuralmodel,"Cell",1,"YoungsModulus",201E9, ...
"PoissonsRatio",0.3, ...
"MassDensity",7800);
structuralBC(structuralmodel,"Face",1,"Constraint","fixed");
5-188
assembleFEMatrices
structuralBoundaryLoad(structuralmodel,"Face",2,...
"Pressure",5E7, ...
"Frequency",50);
structuralIC(structuralmodel,"Displacement",[0;0;0], ...
"Velocity",[0;0;0]);
generateMesh(structuralmodel,"GeometricOrder","linear");
tlist = linspace(0,1,300);
Assemble the finite element matrices for the initial time step.
state.time = tlist(1);
FEM_domain = assembleFEMatrices(structuralmodel,state)
Pressure applied at the top of the cylinder is the only time-dependent quantity in the model. To model
the dynamics of the system, assemble the boundary-load finite element matrix G for the initial,
intermediate, and final time steps.
state.time = tlist(1);
FEM_boundary_init = assembleFEMatrices(structuralmodel,"G",state)
state.time = tlist(floor(length(tlist)/2));
FEM_boundary_half = assembleFEMatrices(structuralmodel,"G",state)
state.time = tlist(end);
FEM_boundary_final = assembleFEMatrices(structuralmodel,"G",state)
5-189
5 Functions
Assemble finite element matrices for a heat transfer problem with temperature-dependent thermal
conductivity.
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 and plot the
geometry.
geometryFromEdges(thermalmodelS,g);
figure
pdegplot(thermalmodelS,"EdgeLabels","on");
axis([-.9 .9 -.9 .9]);
5-190
assembleFEMatrices
Set the temperature on the left edge to 100 degrees. Set the heat flux out of the block on the right
edge to -10. The top and bottom edges and the edges inside the cavity are all insulated: there is no
heat transfer across these edges.
thermalBC(thermalmodelS,"Edge",6,"Temperature",100);
thermalBC(thermalmodelS,"Edge",1,"HeatFlux",-10);
Specify the thermal conductivity of the material as a simple linear function of temperature u.
k = @(~,state) 0.7+0.003*state.u;
thermalProperties(thermalmodelS,"ThermalConductivity",k);
Generate a mesh.
generateMesh(thermalmodelS);
Rnonlin = solve(thermalmodelS);
Because the thermal conductivity is nonlinear (depends on the temperature), compute the system
matrices corresponding to the converged temperature. Assign the temperature distribution to the u
field of the state structure array. Because the u field must contain a row vector, transpose the
temperature distribution.
state.u = Rnonlin.Temperature.';
Assemble finite element matrices using the temperature distribution at the nodal points.
FEM = assembleFEMatrices(thermalmodelS,"nullspace",state)
Compute the solution using the system matrices to verify that they yield the same temperature as
Rnonlin.
u = FEM.B*(FEM.Kc\FEM.Fc) + FEM.ud;
norm(u - Rnonlin.Temperature)
ans = 5.6523e-05
Input Arguments
model — Model object
PDEModel object | ThermalModel object | StructuralModel object | ElectroMagneticModel
object
5-191
5 Functions
assembleFEMatrices does not support assembling FE matrices for 3-D magnetostatic analysis
models.
Example: model = createpde(1)
Example: thermalmodel = createpde("thermal","steadystate")
Example: structuralmodel = createpde("structural","static-solid")
Example: emagmodel = createpde("electromagnetic","electrostatic")
• Matrix identifiers, such as "F", "MKF", "K", and so on — Assemble the corresponding matrices.
Each uppercase letter represents one matrix: K, A, F, Q, G, H, R, M, and T. You can combine several
letters into one character vector or string, such as "MKF".
• "boundary" — Assemble all matrices related to geometry boundaries.
• "domain" — Assemble all domain-related matrices.
state — Time for time-dependent models and solution for nonlinear models
structure array
Time for time-dependent models and solution for nonlinear models, specified in a structure array. The
array fields represent the following values:
• state.time contains a nonnegative number specifying the time value for time-dependent
models.
• state.u contains a solution matrix of size N-by-Np that can be used to assemble matrices in a
nonlinear problem setup, where coefficients are functions of state.u. Here, N is the number of
equations in the system, and Np is the number of nodes in the mesh.
5-192
assembleFEMatrices
Output Arguments
FEM — Finite element matrices
structural array
Finite element matrices, returned as a structural array. Use the bcmethod and matrices arguments
to specify which finite element matrices you want to assemble.
• If the value is boundary, then the fields are all matrices related to geometry boundaries.
• If the value is domain, then the fields are all domain-related matrices.
• If the value is a matrix identifier or identifiers, such as "F", "MKF", "K", and so on, then the fields
are the corresponding matrices.
Algorithms
Partial Differential Equation Toolbox solves equations of the form
∂2 u ∂u
m +d − ∇ · c ⊗ ∇u + au = f
∂t 2 ∂t
− ∇ · c ⊗ ∇u + au = λdu
or
2
− ∇ · c ⊗ ∇u + au = λ mu
assembleFEMatrices returns the following full finite element matrices and vectors that represent
the corresponding PDE problem:
• K is the stiffness matrix, the integral of the discretized version of the c coefficient.
• M is the mass matrix, the integral of the discretized version of the m or d coefficients. M is nonzero
for time-dependent and eigenvalue problems.
• A is the integral of the discretized version of the a coefficient.
• F is the integral of the discretized version of the f coefficient. For thermal, electromagnetic, and
structural problems, F is a source or body load vector.
• Q is the integral of the discretized version of the q term in a Neumann boundary condition.
5-193
5 Functions
• G is the integral of the discretized version of the g term in a Neumann boundary condition. For
structural problems, G is a boundary load vector.
• The H and R matrices come directly from the Dirichlet conditions and the mesh.
The "nullspace" technique eliminates Dirichlet conditions from the problem using a linear algebra
approach. It generates the combined finite-element matrices Kc, Fc, B, and vector ud corresponding
to the reduced system Kc*u = Fc, where Kc = B'*(K + A + Q)*B, and Fc = B'*((F + G)-(K
+ A + Q)*ud). The B matrix spans the null space of the columns of H (the Dirichlet condition matrix
representing h*ud = r). The R vector represents the Dirichlet conditions in H*ud = R. The ud
vector has the size of the solution vector. Its elements are zeros everywhere except at Dirichlet
degrees-of-freedom (DoFs) locations where they contain the prescribed values.
u = B*(Kc\Fc) + ud.
If you assembled a particular set of matrices, for example G and M, you can impose the boundary
conditions on G and M as follows. First, compute the nullspace of columns of H.
[B,Or] = pdenullorth(H);
ud = Or*((H*Or\R)); % Vector with known value of the constraint DoF.
Then use the B matrix as follows. To eliminate Dirichlet degrees of freedom from the load vector G,
use:
GwithBC = B'*G
M = B'*M*B
You can eliminate Dirichlet degrees of freedom from other vectors and matrices using the same
technique.
Note Internally, the toolbox uses the "nullspace" approach to impose Dirichlet boundary
conditions while computing the solution using solvepde and solve.
If the number of nodes in a model is NumNodes, and the number of equations is N, then the length of
column vectors u and ud is N*NumNodes. The toolbox assigns the IDs to the degrees of freedom in u
and ud:
5-194
assembleFEMatrices
For example, in a 3-D structural model, the length of a solution vector u is 3*NumNodes. The first
NumNodes entries correspond to the x-displacement at each node, the next NumNodes entries
correspond to the y-displacement, and the next NumNodes entries correspond to the z-displacement.
In thermal analysis, the m and a coefficients are zeros. The thermal conductivity maps to the c
coefficient. The product of the mass density and the specific heat maps to the d coefficient. The
internal heat source maps to the f coefficient. The temperature on a boundary corresponds to the
Dirichlet boundary condition term r with h = 1. Various forms of boundary heat flux, such as the
heat flux itself, emissivity, and convection coefficient, map to the Neumann boundary condition terms
q and g.
In structural analysis, the a coefficient is zero. Young's modulus and Poisson's ratio map to the c
coefficient. The mass density maps to the m coefficient. The body loads map to the f coefficient.
Displacements, constraints, and components of displacement along the axes map to the Dirichlet
boundary condition terms h and r. Boundary loads, such as pressure, surface tractions, and
translational stiffnesses, correspond to the Neumann boundary condition terms q and g. When you
specify the damping model by using the Rayleigh damping parameters Alpha and Beta, the
discretized damping matrix C is computed by using the mass matrix M and the stiffness matrix K as C
= Alpha*M + Beta*K. Hysteretic (structural) damping contributes to the stiffness matrix K, which
becomes complex.
In electrostatic and magnetostatic analyses, the m, a, and d coefficients are zeros. The relative
permittivity and relative permeability map to the c coefficient. The charge density and current
density map to the f coefficient. The voltage and magnetic potential on a boundary correspond to the
Dirichlet boundary condition term r with h = 1.
Note Assembling FE matrices does not work for harmonic analysis and 3-D magnetostatic analysis.
Version History
Introduced in R2016a
The function now can assemble matrices using input time or solution for a time-dependent or
nonlinear model, respectively. It also can assemble a subset of matrices, such as updated load only or
stiffness only, to save computation time.
The function accepts thermal and structural models with time- and solution-independent coefficients.
See Also
PDEModel | ThermalModel | StructuralModel | ElectromagneticModel | solvepde | solve
5-195
5 Functions
Topics
“Finite Element Method Basics” on page 1-11
“Equations You Can Solve Using PDE Toolbox” on page 1-3
5-196
assempde
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
u = assempde(b,p,e,t,c,a,f) solves the PDE with boundary conditions b, and finite element
mesh (p,e,t).
[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-210.
[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-210.
[K,M,F,Q,G,H,R] = assempde( ___ ) assembles finite element matrices that represent the PDE
problem. This syntax returns all the matrices involved in converting the problem to finite element
form. See “Algorithms” on page 5-210.
5-197
5 Functions
[K,M,F,Q,G,H,R] = assempde( ___ ,[],sdl) 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
model = createpde;
geometryFromEdges(model,@lshapeg);
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-198
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-199
5 Functions
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;
generateMesh(model);
u = assempde(model,c,a,f);
pdeplot3D(model,'ColorMapData',u)
5-200
assempde
5-201
5 Functions
Obtain the finite-element matrices that represent the problem using a reduced linear algebra
representation of Dirichlet boundary conditions.
Obtain finite element matrices K, F, B, and ud that represent the equation − ∇ ⋅ c ∇u + au = f with
y
parameters c = 1, a = 0, and f = log 1 + x + .
1+z
c = 1;
a = 0;
5-202
assempde
f = 'log(1+x+y./(1+z))';
[K,F,B,ud] = assempde(model,c,a,f);
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.
Obtain finite element matrices Ks and Fs that represent the equation − ∇ ⋅ c ∇u + au = f with
y
parameters c = 1, a = 0, and f = log 1 + x + .
1+z
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);
5-203
5 Functions
c = 1;
a = 0;
f = 1;
generateMesh(model);
[K,M,F,Q,G,H,R] = ...
assempde(model,c,a,f);
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)))])
u = assempde(K,M,F,Q,G,H,R);
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
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
5-204
assempde
− ∇ ⋅ c ⊗ ∇u + au = f
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
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.
Example: b = 'circleb1', b = "circleb1", or b = @circleb1
Data Types: double | char | string | function_handle
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 as [p,e,t] Triples” on page 2-181.
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 as [p,e,t] Triples” on page 2-181.
Typically, you use the p, e, and t data exported from the PDE Modeler app, or generated by
initmesh or refinemesh.
5-205
5 Functions
t — Mesh triangles
matrix
Mesh triangles, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For a description of the (p,e,t) matrices, see “Mesh Data as [p,e,t] Triples” on page 2-181.
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-
210.
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-210.
Example: [K,M,F,Q,G,H,R] = assempde(model,c,a,f)
Data Types: double
Complex Number Support: Yes
Finite element f representation, specified as a vector. Generally, you obtain F from a previous call to
assema or assempde. For the meaning of this representation, see “Elliptic Equations” on page 5-210.
Example: [K,M,F,Q,G,H,R] = assempde(model,c,a,f)
Data Types: double
Complex Number Support: Yes
Neumann boundary condition matrix, specified as a sparse matrix or full matrix. Generally, you obtain
Q from a previous call to assemb or assempde. For the meaning of this matrix, see “Elliptic
Equations” on page 5-210.
Example: [K,M,F,Q,G,H,R] = assempde(model,c,a,f)
5-206
assempde
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-210.
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-210.
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-210.
Example: [K,M,F,Q,G,H,R] = assempde(model,c,a,f)
Data Types: double
Complex Number Support: Yes
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
5-207
5 Functions
• 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 “3-D Solution and Gradient Plots with
MATLAB Functions” on page 3-391.
Kc — Stiffness matrix
sparse matrix
Stiffness matrix, returned as a sparse matrix. See “Elliptic Equations” on page 5-210.
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
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.
5-208
assempde
Finite element matrix for stiff-spring approximation, returned as a sparse matrix. See “Algorithms” on
page 5-210.
u = Ks\Fs.
Generally, Ks and Fs make a quicker but less accurate solution than Kc, Fc, B, and ud.
Load vector corresponding to the stiff-spring approximation for Dirichlet boundary condition,
returned as a vector. See “Algorithms” on page 5-210.
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-210.
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-210.
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.
Neumann boundary condition matrix, returned as a sparse matrix. See “Elliptic Equations” on page 5-
210.
5-209
5 Functions
Neumann boundary condition vector, returned as a sparse vector. See “Elliptic Equations” on page 5-
210.
H — Dirichlet matrix
sparse matrix
R — Dirichlet vector
sparse vector
More About
Reduced Linear System
This form of the finite element matrices eliminates Dirichlet conditions from the problem using a
linear algebra approach. The finite element matrices reduce to the solution u = B*(Kc\Fc) + ud,
where B spans the null space of the columns of H (the Dirichlet condition matrix representing hu = r).
R is the Dirichlet condition vector for Hu = R. ud is the vector of boundary condition solutions for the
Dirichlet conditions. u1 = Kc\Fc returns the solution on the non-Dirichlet points.
See “Systems of PDEs” on page 5-216 for details on the approach used to eliminate Dirichlet
conditions.
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-210. For details of the stiff-spring approximation, see “Systems of
PDEs” on page 5-216.
Algorithms
Elliptic Equations
∂2 u ∂u
m +d − ∇ · c ∇u + au = f
∂t 2 ∂t
5-210
assempde
− ∇ ⋅ 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:
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.
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 condition because division with a very large q
5-211
5 Functions
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-216.
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 = ∫ f v dx
Ω Ω
∫
Ω
c ∇u · ∇v + auv dx − ∫n ·
∂Ω
c ∇u v ds = ∫ f v dx
Ω
∫
Ω
c ∇u · ∇v + auv dx − ∫ −qu + g v ds = ∫ f v dx
∂Ω Ω
∫
Ω
c ∇u · ∇v + auv − f v dx − ∫ −qu + g v ds = 0 ∀v
∂Ω
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 to choose an
Np-dimensional subspace V Np ⊂ V. Project the weak form of the differential equation onto a finite-
dimensional function space simply means requesting u and v to lie in V Np rather than V. The solution
of the finite dimensional problem turns out to be the element of V Np that lies closest to the weak
solution when measured in the energy norm. Convergence is guaranteed if the space V Np tends to V
as Np→∞. Since the differential operator is linear, we demand that the variational equation is satisfied
for Np test-functions Φi ∊V Np that form a basis, i.e.,
∫
Ω
c ∇u · ∇ϕi + auϕi − f ϕi dx −
∂Ω
∫ −qu + g ϕ ds = 0, i = 1, ..., N
i p
Np
u(x) = ∑ U jϕ j(x)
j=1
5-212
assempde
Ki, j = ∫ c ∇ϕ
Ω
j ⋅ ∇ϕi dx (stiffness matrix)
Mi, j =
Ω
∫aϕ ϕ dx j i (mass matrix)
Qi, j = ∫ qϕ ϕ ds
∂Ω
j i
Fi = ∫ f ϕ dx
Ω
i
Gi = ∫ gϕ ds
∂Ω
i
(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.
UT K + M + Q U = ∫ cu
Ω
2
+ au2 dx + ∫ qu
∂Ω
2 ds > 0, if U ≠ 0
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 V Np is nothing 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, V Np approximates the set of smooth functions on Ω.
A suitable basis for V Np 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-218. Requesting ϕi(xi) = 1 yields the very
pleasant property
Np
u xi = ∑ U jϕ j xi = 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
5-213
5 Functions
is that the integrals appearing in Ki,j, Mi,j, Qi,j, Fi and Gi 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.
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.
5-214
assempde
area ΔP1P2P3
mi, j = ∫
ΔP1P2P3
a Pc ϕi x ϕ j x dx = a Pc
12
1 + δi, j
P1 + P2 + P3
Pc =
3
area ΔP1P2P3
f i = 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
∇ϕ1 =
2 area ΔP1P2P3 −x1
1 y1
ki, j = y j, − x j c Pc
4 area ΔP1P2P3 −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 + δi, 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.,
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.
To summarize, assempde performs the following steps to obtain a solution u to an elliptic PDE:
5-215
5 Functions
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
u = B*(Kc\Fc) + ud.
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:
[Kc,Fc,B,ud] = assempde(_)
[Ks,Fs] = assempde(_)
For details, see “Reduced Linear System” on page 5-210 and “Stiff-Spring Approximation” on page 5-
210.
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 = λdu
For 2-D systems, the notation ∇ ⋅ (c ⊗ ∇u) represents an N-by-1 matrix with an (i,1)-component
N
∂ ∂ ∂ ∂ ∂ ∂ ∂ ∂
∑ c
∂x i, j, 1, 1 ∂x
+ c
∂x i, j, 1, 2 ∂y
+ c
∂y i, j, 2, 1 ∂x
+ c u
∂y i, j, 2, 2 ∂y j
j=1
For 3-D systems, the notation ∇ ⋅ (c ⊗ ∇u) represents an N-by-1 matrix with an (i,1)-component
5-216
assempde
N
∂ ∂ ∂ ∂ ∂ ∂
∑ c
∂x i, j, 1, 1 ∂x
+ c
∂x i, j, 1, 2 ∂y
+ c u
∂x i, j, 1, 3 ∂z j
j=1
N
∂ ∂ ∂ ∂ ∂ ∂
+ ∑ c
∂y i, j, 2, 1 ∂x
+ c
∂y i, j, 2, 2 ∂y
+ c u
∂y i, j, 2, 3 ∂z j
j=1
N
∂ ∂ ∂ ∂ ∂ ∂
+ ∑ c
∂z i, j, 3, 1 ∂x
+ c
∂z i, j, 3, 2 ∂y
+ c u
∂z i, j, 3, 3 ∂z 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′μ
For 2-D systems, the notation n · c ⊗ ∇u represents an N-by-1 matrix with (i,1)-component
N
∂ ∂ ∂ ∂
∑ cos(α)ci, j, 1, 1
∂x
+ cos(α)ci, j, 1, 2
∂y
+ sin(α)ci, j, 2, 1
∂x
+ sin(α)ci, j, 2, 2 u
∂y j
j=1
For 3-D systems, the notation n · c ⊗ ∇u represents an N-by-1 matrix with (i,1)-component
N
∂ ∂ ∂
∑ cos(α)ci, j, 1, 1
∂x
+ cos(α)ci, j, 1, 2
∂y
+ cos(α)ci, j, 1, 3 u
∂z j
j=1
N
∂ ∂ ∂
+ ∑ cos(β)ci, j, 2, 1
∂x
+ cos(β)ci, j, 2, 2
∂y
+ cos(β)ci, j, 2, 3 u
∂z j
j=1
N
∂ ∂ ∂
+ ∑ cos(γ)ci, j, 3, 1
∂x
+ cos(γ)ci, j, 3, 2
∂y
+ cos(γ)ci, j, 3, 3 u
∂z 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′μ, 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.
5-217
5 Functions
The rest of this section details the treatment of the Dirichlet conditions and may be skipped on a first
reading.
Partial Differential Equation Toolbox software supports two implementations of Dirichlet conditions.
The simplest is the “Stiff Spring” model, so named for its interpretation in solid mechanics. See
“Elliptic Equations” on page 5-210 for the scalar case, which is equivalent to a diagonal h-matrix. For
the general case, Dirichlet conditions
hu = r
L(h′hu − h′r)
to the equations KU = F, where L is a large number such as 104 times a representative size of the
elements of K.
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
HU = R.
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 pre-multiplying by B´ since,
by the construction, HB = 0 or B´H´ = 0. The reduced system becomes
B´ KBV = B´ F – B´Kud
The finite element method for 3-D geometry is similar to the 2-D method described in “Elliptic
Equations” on page 5-210. The main difference is that the elements in 3-D geometry are tetrahedra,
which means that the basis functions are different from those in 2-D geometry.
It is convenient to map a tetrahedron to a canonical tetrahedron with a local coordinate system (r,s,t).
5-218
assempde
ϕ1 = 1 − r − s − t
ϕ2 = r
ϕ3 = s
ϕ4 = t
For a quadratic tetrahedron, there are additional nodes at the edge midpoints.
5-219
5 Functions
2
ϕ1 = 2 1 − r − s − t − 1−r−s−t
ϕ2 = 2r 2 − r
ϕ3 = 2s2 − s
ϕ4 = 2t2 − t
ϕ5 = 4r 1 − r − s − t
ϕ6 = 4rs
ϕ7 = 4s 1 − r − s − t
ϕ8 = 4t 1 − r − s − t
ϕ9 = 4rt
ϕ10 = 4st
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.
Version History
Introduced before R2006a
assempde is not recommended. Use solvepde instead. There are no plans to remove assempde.
5-220
assempde
See Also
assembleFEMatrices | solvepde
5-221
5 Functions
cellEdges
Find edges belonging to boundaries of specified cells
Syntax
EdgeID = cellEdges(g,RegionID)
EdgeID = cellEdges(g,RegionID,FilterType)
Description
EdgeID = cellEdges(g,RegionID) finds edges belonging to the boundaries of the cells with ID
numbers listed in RegionID.
Examples
Find edges belonging to the boundaries of the two middle cylinders in a geometry consisting of four
stacked cylinders.
gm =
DiscreteGeometry with properties:
NumCells: 4
NumFaces: 9
NumEdges: 5
NumVertices: 5
Vertices: [5x3 double]
pdegplot(gm,"CellLabels","on","EdgeLabels","on","FaceAlpha",0.2)
5-222
cellEdges
edgeIDs = 1×3
2 3 4
Find edges belonging to the boundaries of the outer cuboid in a geometry consisting of two nested
cuboids.
Create a geometry that consists of two nested cuboids of the same height.
gm =
DiscreteGeometry with properties:
NumCells: 2
NumFaces: 12
NumEdges: 24
NumVertices: 16
5-223
5 Functions
Find all edges belonging to the boundaries of the outer cell. Show the first 10 edges.
edgeIDs = cellEdges(gm,2);
edgeIDs(1:10)
ans = 1×10
1 2 3 4 5 6 7 8 9 10
From all edges belonging to the boundaries of the outer cell, return the edges belonging to only the
internal faces. Internal faces are faces shared between multiple cells.
edgeIDs_int = cellEdges(gm,2,"internal")
edgeIDs_int = 1×4
9 10 11 12
From all edges belonging to the boundaries of the outer cell, return the edges belonging to the
external faces. Show the first 10 edges.
5-224
cellEdges
edgeIDs_ext = cellEdges(gm,2,"external");
edgeIDs_ext(1:10)
ans = 1×10
1 2 3 4 5 6 7 8 13 14
Input Arguments
g — 3-D geometry
fegeometry object | DiscreteGeometry object
RegionID — Cell ID
positive number | vector of positive numbers
Cell ID, specified as a positive number or a vector of positive numbers. Each number represents a cell
ID.
• "internal" — Edges belonging to only internal faces. Internal faces are faces shared between
multiple cells.
• "external" — Edges belonging to only external faces. External faces are faces not shared
between multiple cells.
• "all" — All edges belonging to the specified cells.
Output Arguments
EdgeID — IDs of edges belonging to boundaries of specified cells
positive number | vector of positive numbers
IDs of edges belonging to boundaries of specified cells, returned as a positive number or a vector of
positive numbers.
Version History
Introduced in R2021a
5-225
5 Functions
See Also
Functions
cellFaces | faceEdges | facesAttachedToEdges | nearestEdge | nearestFace
Objects
fegeometry | DiscreteGeometry | AnalyticGeometry
5-226
cellFaces
cellFaces
Find faces belonging to specified cells
Syntax
FaceID = cellFaces(g,RegionID)
FaceID = cellFaces(g,RegionID,FilterType)
Description
FaceID = cellFaces(g,RegionID) finds faces belonging to the cells with ID numbers listed in
RegionID.
Examples
Find faces belonging to two cuboids in a geometry consisting of four stacked cuboids.
gm =
DiscreteGeometry with properties:
NumCells: 4
NumFaces: 21
NumEdges: 36
NumVertices: 20
Vertices: [20x3 double]
pdegplot(gm,"CellLabels","on","FaceAlpha",0.2)
5-227
5 Functions
faceIDs = 1×12
1 2 3 4 5 6 7 12 13 14 15 16
pdegplot(gm,"FaceLabels","on","FaceAlpha",0.2)
5-228
cellFaces
Find faces belonging to the outer cuboid in a geometry consisting of two nested cuboids.
Create a geometry that consists of two nested cuboids of the same height.
gm =
DiscreteGeometry with properties:
NumCells: 2
NumFaces: 12
NumEdges: 24
NumVertices: 16
Vertices: [16x3 double]
pdegplot(gm,"CellLabels","on","FaceAlpha",0.2)
5-229
5 Functions
faceIDs = 1×10
3 4 5 6 7 8 9 10 11 12
Find only the internal faces belonging to the outer cell. Internal faces are faces shared between
multiple cells.
faceIDs_int = cellFaces(gm,2,"internal")
faceIDs_int = 1×4
3 4 5 6
faceIDs_ext = 1×6
7 8 9 10 11 12
5-230
cellFaces
pdegplot(gm,"FaceLabels","on","FaceAlpha",0.2)
Input Arguments
g — 3-D geometry
fegeometry object | DiscreteGeometry object
RegionID — Cell ID
positive number | vector of positive numbers
Cell ID, specified as a positive number or a vector of positive numbers. Each number represents a cell
ID.
• "internal" — Internal faces, that is, faces shared between multiple cells.
• "external" — External faces, that is, faces not shared between multiple cells.
• "all" — All faces belonging to the specified cells.
5-231
5 Functions
Output Arguments
FaceID — IDs of faces belonging to specified cells
positive number | vector of positive numbers
IDs of faces belonging to the specified cells, returned as a positive number or a vector of positive
numbers.
Version History
Introduced in R2021a
See Also
Functions
cellEdges | faceEdges | facesAttachedToEdges | nearestEdge | nearestFace
Objects
fegeometry | DiscreteGeometry | AnalyticGeometry
5-232
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, specified as 'Face' for a 2-D region or 'Cell' for a 3-D region.
Data Types: char | string
RegionID — Region ID
vector of positive integers
Region ID, specified as a vector of positive integers. To determine which ID corresponds to which
portion of the geometry, use the pdegplot function, setting 'FaceLabels' to 'on'.
Data Types: double
Acceleration due to gravity, specified as a numeric vector. This property must be specified in units
consistent with those of the geometry and material properties.
Example: structuralBodyLoad(structuralmodel,'GravitationalAcceleration',
[0,0,-9.8])
Data Types: double
Angular velocity for an axisymmetric model, specified as a positive number. This property must be
specified in units consistent with those of the geometry and material properties.
Example: structuralBodyLoad(structuralmodel,'AngularVelocity',2.3)
Data Types: double
5-233
5 Functions
Version History
Introduced in R2017b
See Also
findBodyLoad | structuralBodyLoad
5-234
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.
Specify boundary conditions for your model using the applyBoundaryCondition function.
Properties
Properties
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 by 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 a vector with N elements or a function handle. N is the
number of PDEs in the system. For the syntax of the function handle form of r, see “Nonconstant
Boundary Conditions” on page 2-131.
Example: 'r',[0;4;-1]
Data Types: double | function_handle
Complex Number Support: Yes
5-235
5 Functions
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-131.
Example: 'h',[2,1;1,2]
Data Types: double | function_handle
Complex Number Support: Yes
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-
131.
Example: applyBoundaryCondition(model,'dirichlet','Face',[2,4,11],'u',0)
Data Types: double
Complex Number Support: Yes
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.
5-236
BoundaryCondition Properties
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”. For details of this
evaluation, see “Nonconstant Boundary Conditions” on page 2-131.
Example: applyBoundaryCondition(model,'dirichlet','Face',
[2,4,11],'u',@ucalculator,'Vectorized','on')
Data Types: char
Version History
Introduced in R2015a
See Also
applyBoundaryCondition | findBoundaryConditions | PDEModel
Topics
“Specify Boundary Conditions” on page 2-128
“View, Edit, and Delete Boundary Conditions” on page 2-159
“Solve Problems Using PDEModel Objects” on page 2-3
5-237
5 Functions
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.
∂2 u ∂u
m +d − ∇ · c ∇u + au = f
∂t2 ∂t
− ∇ · c ∇u + au = λdu
or
2
− ∇ · c ∇u + au = λ mu
Properties
Properties
Region type, specified as 'face' for a 2-D region, or 'cell' for a 3-D region.
Data Types: char | string
RegionID — Region ID
vector of positive integers
Region ID, specified as a vector of positive integers. To determine which ID corresponds to which
portion of the geometry, use the pdegplot function. Set the 'FaceLabels' name-value pair to
'on'.
Data Types: double
Second-order time derivative coefficient, specified as a scalar, column vector, or function handle. For
details of the m coefficient specification, see “m, d, or a Coefficient for specifyCoefficients” on page 2-
106.
Data Types: double | function_handle
5-238
CoefficientAssignment Properties
First-order time derivative coefficient, specified as a scalar, column vector, or function handle. For
details of the d coefficient specification, see “m, d, or a Coefficient for specifyCoefficients” on page 2-
106.
Data Types: double | function_handle
Complex Number Support: Yes
Second-order space derivative coefficient, specified as a scalar, column vector, or function handle. For
details of the c coefficient specification, see “c Coefficient for specifyCoefficients” on page 2-91.
Data Types: double | function_handle
Complex Number Support: Yes
Solution multiplier coefficient, specified 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-106.
Data Types: double | function_handle
Complex Number Support: Yes
f — Source coefficient
scalar | column vector | function handle
Source coefficient, specified as a scalar, column vector, or function handle. For details of the f
coefficient specification, see “f Coefficient for specifyCoefficients” on page 2-89.
Data Types: double | function_handle
Complex Number Support: Yes
Version History
Introduced in R2016a
See Also
findCoefficients | specifyCoefficients
Topics
“Solve Problems Using PDEModel Objects” on page 2-3
5-239
5 Functions
createpde
Create model
Syntax
structuralmodel = createpde("structural",StructuralAnalysisType)
thermalmodel = createpde("thermal",ThermalAnalysisType)
emagmodel = createpde("electromagnetic",ElectromagneticAnalysisType)
model = createpde(N)
model = createpde
Description
structuralmodel = createpde("structural",StructuralAnalysisType) returns a
structural analysis model for the specified analysis type. This model lets you solve small-strain linear
elasticity problems.
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.
model = createpde returns a PDE model object for one equation (a scalar PDE). This syntax is
equivalent to model = createpde(1) and model = createpde().
Examples
staticStructural = createpde("structural","static-solid")
staticStructural =
StructuralModel with properties:
AnalysisType: "static-solid"
Geometry: []
MaterialProperties: []
BodyLoads: []
BoundaryConditions: []
ReferenceTemperature: []
SuperelementInterfaces: []
Mesh: []
5-240
createpde
transientStructural = createpde("structural","transient-planestress")
transientStructural =
StructuralModel with properties:
AnalysisType: "transient-planestress"
Geometry: []
MaterialProperties: []
BodyLoads: []
BoundaryConditions: []
DampingModels: []
InitialConditions: []
SuperelementInterfaces: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
modalStructural = createpde("structural","modal-planestrain")
modalStructural =
StructuralModel with properties:
AnalysisType: "modal-planestrain"
Geometry: []
MaterialProperties: []
BoundaryConditions: []
SuperelementInterfaces: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
frStructural = createpde("structural","frequency-axisymmetric")
frStructural =
StructuralModel with properties:
AnalysisType: "frequency-axisymmetric"
Geometry: []
MaterialProperties: []
BodyLoads: []
BoundaryConditions: []
DampingModels: []
SuperelementInterfaces: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
5-241
5 Functions
thermalmodel = createpde("thermal","steadystate")
thermalmodel =
ThermalModel with properties:
AnalysisType: "steadystate"
Geometry: []
MaterialProperties: []
HeatSources: []
StefanBoltzmannConstant: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
thermalmodel = createpde("thermal","transient")
thermalmodel =
ThermalModel with properties:
AnalysisType: "transient"
Geometry: []
MaterialProperties: []
HeatSources: []
StefanBoltzmannConstant: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
thermalmodel = createpde("thermal","modal")
thermalmodel =
ThermalModel with properties:
AnalysisType: "modal"
Geometry: []
MaterialProperties: []
HeatSources: []
StefanBoltzmannConstant: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
5-242
createpde
Create a transient thermal model for solving an axisymmetric problem. An axisymmetric model
simplifies a 3-D problem to a 2-D problem using symmetry around the axis of rotation.
thermalmodel = createpde("thermal","transient-axisymmetric")
thermalmodel =
ThermalModel with properties:
AnalysisType: "transient-axisymmetric"
Geometry: []
MaterialProperties: []
HeatSources: []
StefanBoltzmannConstant: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
emagE = createpde("electromagnetic","electrostatic")
emagE =
ElectromagneticModel with properties:
AnalysisType: "electrostatic"
Geometry: []
MaterialProperties: []
Sources: []
BoundaryConditions: []
VacuumPermittivity: []
Mesh: []
Create an axisymmetric model for magnetostatic analysis. An axisymmetric model simplifies a 3-D
problem to a 2-D problem using symmetry around the axis of rotation.
emagMA = createpde("electromagnetic","magnetostatic-axisymmetric")
emagMA =
ElectromagneticModel with properties:
AnalysisType: "magnetostatic-axisymmetric"
Geometry: []
MaterialProperties: []
Sources: []
BoundaryConditions: []
VacuumPermeability: []
Mesh: []
5-243
5 Functions
emagH = createpde("electromagnetic","harmonic")
emagH =
ElectromagneticModel with properties:
AnalysisType: "harmonic"
Geometry: []
MaterialProperties: []
Sources: []
BoundaryConditions: []
VacuumPermittivity: []
VacuumPermeability: []
Mesh: []
FieldType: "electric"
emagDC = createpde("electromagnetic","conduction")
emagDC =
ElectromagneticModel with properties:
AnalysisType: "conduction"
Geometry: []
MaterialProperties: []
BoundaryConditions: []
Mesh: []
model = createpde
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
model = createpde(3)
model =
PDEModel with properties:
5-244
createpde
PDESystemSize: 3
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
Input Arguments
StructuralAnalysisType — Type of structural analysis
"static-solid" | "static-planestress" | "static-planestrain" | "static-
axisymmetric" | "transient-solid" | "transient-planestress" | "transient-
planestrain" | "transient-axisymmetric" | "modal-solid" | "modal-planestress" |
"modal-planestrain" | "modal-axisymmetric" | "frequency-solid" | "frequency-
planestress" | "frequency-planestrain" | "frequency-axisymmetric"
• "static-solid" — Creates a structural model for static analysis of a solid (3-D) problem.
• "static-planestress" — Creates a structural model for static analysis of a plane-stress
problem.
• "static-planestrain" — Creates a structural model for static analysis of a plane-strain
problem.
• "static-axisymmetric" — Creates an axisymmetric (2-D) structural model for static analysis.
• "transient-solid" — Creates a structural model for transient analysis of a solid (3-D) problem.
• "transient-planestress" — Creates a structural model for transient analysis of a plane-
stress problem.
• "transient-planestrain" — Creates a structural model for transient analysis of a plane-strain
problem.
• "transient-axisymmetric" — Creates an axisymmetric (2-D) structural model for transient
analysis.
• "modal-solid" — Creates a structural model for modal analysis of a solid (3-D) problem.
• "modal-planestress" — Creates a structural model for modal analysis of a plane-stress
problem.
• "modal-planestrain" — Creates a structural model for modal analysis of a plane-strain
problem.
• "modal-axisymmetric" — Creates an axisymmetric (2-D) structural model for modal analysis.
5-245
5 Functions
• "frequency-solid" — Creates a structural model for frequency response analysis of a solid (3-
D) problem.
• "frequency-planestress" — Creates a structural model for frequency response analysis of a
plane-stress problem.
• "frequency-planestrain" — Creates a structural model for frequency response analysis of a
plane-strain problem.
• "frequency-axisymmetric" — Creates an axisymmetric (2-D) structural model for frequency
response analysis.
For axisymmetric models, the toolbox assumes that the axis of rotation is the vertical axis passing
through r = 0.
Example: model = createpde("structural","static-solid")
Data Types: char | string
For axisymmetric models, the toolbox assumes that the axis of rotation is the vertical axis passing
through r = 0.
Example: model = createpde("thermal","transient")
Data Types: char | string
5-246
createpde
For axisymmetric models, the toolbox assumes that the axis of rotation is the vertical axis passing
through r = 0.
Example: model = createpde("electromagnetic","electrostatic")
Data Types: char | string
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);
Data Types: double
Output Arguments
structuralmodel — Structural model
StructuralModel object
Version History
Introduced in R2015a
5-247
5 Functions
createpde now can create a model for axisymmetric thermal and structural analyses. Axisymmetric
analysis simplifies 3-D structural and thermal problems to 2-D using their symmetry around the axis
of rotation.
See Also
PDEModel | ThermalModel | StructuralModel | ElectromagneticModel
Topics
“Structural Mechanics”
“Heat Transfer”
“Electromagnetics”
“Solve Problems Using PDEModel Objects” on page 2-3
“Equations You Can Solve Using PDE Toolbox” on page 1-3
5-248
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.
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");
5-249
5 Functions
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-250
createPDEResults
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]);
E = 200e9;
nu = 0.3;
c = elasticityC3D(E,nu);
a = 0;
f = [0;0;0];
generateMesh(model,"Hmax",1e-2);
u = assempde(model,c,a,f);
results = createPDEResults(model,u)
results =
StationaryResults with properties:
5-251
5 Functions
pdeplot3D(model,"ColorMapData",results.NodalSolution(:,3))
model = createpde();
importGeometry(model,"Tetrahedron.stl");
pdegplot(model,"FaceLabels","on","FaceAlpha",0.5)
view(45,45)
5-252
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.
tlist = 0:10:200;
generateMesh(model);
u = parabolic(u0,tlist,model,c,a,f,d);
5-253
5 Functions
results = createPDEResults(model,u,tlist,"time-dependent");
pdeplot3D(model,"ColorMapData",results.NodalSolution(:,11))
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);
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;
5-254
createPDEResults
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))
Input Arguments
model — PDE model
PDEModel object
5-255
5 Functions
u — PDE solution
vector | matrix
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;
Then eigenvectors has size Np-by-N-by-ev. Each column of eigenvectors 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, and so on.
Output Arguments
results — PDE solution
StationaryResults object (default) | TimeDependentResults object | EigenResults object
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-
429.
Algorithms
The procedure for evaluating gradients at nodal locations is as follows:
5-256
createPDEResults
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.
Version History
Introduced in R2015b
• To create the TimeDependentResults object for a time-dependent problem, use the syntax
createPDEResults(pdem,u,utimes,'time-dependent'), where utimes is a vector of
solution times.
• To create the EigenResults object for an eigenvalue problem, use the syntax
createPDEResults(pdem,eigenvectors,eigenvalues,'eigen').
EigenResults has different property names than PDEResults. Update any eigenvalue scripts that
use PDEResults property names.
See Also
interpolateSolution | evaluateGradient | StationaryResults | TimeDependentResults |
EigenResults
Topics
“Linear Elasticity Equations” on page 3-194
5-257
5 Functions
csgdel
Delete boundaries between subdomains
Syntax
[dl1,bt1] = csgdel(dl,bt,bl)
[dl1,bt1] = csgdel(dl,bt)
Description
[dl1,bt1] = csgdel(dl,bt,bl) deletes the boundaries bl between subdomains. If deleting the
boundaries in bl makes the decomposed geometry matrix inconsistent, then csgdel deletes
additional border segments (edge segments between subdomains) to preserve consistency.
Deleting boundaries typically changes the edge IDs of the remaining boundaries.
Examples
Delete edges in a 2-D geometry created in the PDE Modeler app and exported to the MATLAB
workspace.
Create a geometry in the PDE Modeler app by entering the following commands in the MATLAB
Command Window:
pdecirc(0,0,1,"C1")
pdecirc(0,0,0.5,"C2")
pderect([-0.2 0.2 0.2 0.9],"R1")
pderect([0 1 0 1],"SQ1")
Reduce the geometry to the first quadrant by intersecting it with a square. To do this, enter
(C1+C2+R1)*SQ1 in the Set formula field.
From the PDE Modeler app, export the geometry description matrix, set formula, and name-space
matrix to the MATLAB workspace by selecting Export Geometry Description, Set Formula,
Labels from the Draw menu.
In the MATLAB Command Window, use the decsg function to decompose the exported geometry into
minimal regions. This creates an AnalyticGeometry object dl. Plot dl.
[dl,bt] = decsg(gd,sf,ns);
pdegplot(dl,"EdgeLabels","on","FaceLabels","on")
xlim([-0.1 1.1])
ylim([-0.1 1.1])
5-258
csgdel
Remove edges 1, 2, and 13 using the csgdel function. Specify the edges to delete as a vector of edge
IDs. Plot the resulting geometry.
5-259
5 Functions
Now remove all boundaries between subdomains and plot the resulting geometry.
[dl1,bt1] = csgdel(dl,bt);
pdegplot(dl1,"EdgeLabels","on","FaceLabels","on")
xlim([-0.1 1.1])
ylim([-0.1 1.1])
5-260
csgdel
Input 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 columns 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-261
5 Functions
Row number Circle edge segment Line edge segment Ellipse edge segment
1 1 2 4
2 starting x-coordinate starting x-coordinate starting x-coordinate
3 ending x-coordinate ending x-coordinate ending x-coordinate
4 starting y-coordinate starting y-coordinate starting y-coordinate
5 ending y-coordinate ending y-coordinate ending y-coordinate
6 left minimal region label left minimal region label left minimal region label
7 right minimal region right minimal region right minimal region
label label label
8 x-coordinate of the x-coordinate of the
center center
9 y-coordinate of the y-coordinate of the
center center
10 radius of the circle x-semiaxis before
rotation
11 y-semiaxis before
rotation
12 Angle in radians
between x-axis and first
semiaxis
Boolean table relating the original shapes to the minimal regions, returned as a matrix of 1s and 0s.
Data Types: double
bl — Boundaries to delete
positive integer | vector of positive integers
Boundaries to delete, specified as a positive integer or a vector of positive integers. Each integer
represents a boundary ID.
Data Types: double
Output Arguments
dl1 — Modified decomposed geometry matrix
matrix of double-precision numbers
5-262
csgdel
Boolean table relating the remaining original shapes to the minimal regions, returned as a matrix of
1s and 0s.
Data Types: double
Version History
Introduced before R2006a
See Also
decsg
5-263
5 Functions
decsg
Decompose constructive solid 2-D 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-17 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.
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.
5-264
decsg
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 face labels.
pdegplot(dl,"EdgeLabels","on","FaceLabels","on")
axis equal
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
5-265
5 Functions
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. 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)
5-266
decsg
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 face labels.
pdegplot(dl,"EdgeLabels","on","FaceLabels","on")
axis equal
[dl2,bt2] = csgdel(dl,bt);
figure
pdegplot(dl2,"EdgeLabels","on","FaceLabels","on")
axis equal
5-267
5 Functions
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 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.
5-268
decsg
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
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.
5-269
5 Functions
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.
Row number Circle edge segment Line edge segment Ellipse edge segment
1 1 2 4
2 starting x-coordinate starting x-coordinate starting x-coordinate
3 ending x-coordinate ending x-coordinate ending x-coordinate
4 starting y-coordinate starting y-coordinate starting y-coordinate
5 ending y-coordinate ending y-coordinate ending y-coordinate
6 left minimal region label left minimal region label left minimal region label
7 right minimal region right minimal region right minimal region
label label label
8 x-coordinate of the x-coordinate of the
center center
9 y-coordinate of the y-coordinate of the
center center
10 radius of the circle x-semiaxis before
rotation
11 y-semiaxis before
rotation
12 Angle in radians
between x-axis and first
semiaxis
Boolean table relating the original shapes to the minimal regions, returned as a matrix of 1s and 0s.
Data Types: double
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.
5-270
decsg
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.
• decsg returns NaN if it cannot evaluate the set formula sf.
Version History
Introduced before R2006a
See Also
geometryFromEdges | csgdel | wgeom | pdecirc | pdeellip | pdepoly | pderect | PDE Modeler
Topics
“2-D Geometry Creation at Command Line” on page 2-17
5-271
5 Functions
DiscreteGeometry
Discrete 2-D or 3-D geometry description
Description
DiscreteGeometry describes a 2-D or 3-D geometry in the form of a discrete geometry object.
PDEModel, StructuralModel, and ThermalModel objects have a Geometry property, which can be
an AnalyticGeometry or DiscreteGeometry object.
Creation
Create a discrete geometry for your model by using one of the following approaches:
• Use importGeometry to import a 2-D or 3-D geometry from an STL file or a 3-D geometry from a
STEP file and attach it to the model.
• Use geometryFromMesh to reconstruct a 2-D or 3-D geometry from mesh and attach it to the
model.
• Use multicuboid, multicylinder, or multisphere to create a 3-D geometry. Then assign the
resulting geometry to the Geometry property of the model. For example, create a PDE model and
add the following geometry formed by three spheres to the model.
model = createpde;
gm = multisphere([1,2,3]);
model.Geometry = gm;
• Use extrude to create a 3-D geometry by vertically extruding a 2-D geometry.
Properties
NumCells — Number of geometry cells
nonnegative integer
5-272
DiscreteGeometry
Coordinates of geometry vertices, specified as an N-by-2 or N-by-3 numeric matrix for a 2-D or 3-D
geometry, respectively. Here, N is the number of vertices.
Data Types: double
Object Functions
addFace Fill void regions in 2-D and split cells in 3-D geometry
addVertex Add vertex on geometry boundary
rotate Rotate geometry
scale Scale geometry
translate Translate geometry
mergeCells Merge geometry cells
cellEdges Find edges belonging to boundaries of specified cells
cellFaces Find faces belonging to specified cells
faceEdges Find edges belonging to specified faces
facesAttachedToEdges Find faces attached to specified edges
nearestEdge Find edges nearest to specified point
nearestFace Find faces nearest to specified point
Examples
Create the geometry consisting of three cylinders of the same height by using the multicylinder
function.
gm = multicylinder([5 10 15],20)
gm =
DiscreteGeometry with properties:
NumCells: 3
NumFaces: 9
NumEdges: 6
NumVertices: 6
Vertices: [6x3 double]
pdegplot(gm,FaceAlpha=0.5)
5-273
5 Functions
gm = importGeometry("ForearmLink.stl")
gm =
DiscreteGeometry with properties:
NumCells: 1
NumFaces: 147
NumEdges: 329
NumVertices: 213
Vertices: [213x3 double]
pdegplot(gm)
5-274
DiscreteGeometry
Version History
Introduced in R2015a
See Also
Functions
addFace | addVertex | mergeCells | geometryFromMesh | importGeometry | multicuboid |
multicylinder | multisphere
Objects
PDEModel | StructuralModel | ThermalModel | AnalyticGeometry
Topics
“Solve Problems Using PDEModel Objects” on page 2-3
5-275
5 Functions
dst
(Not recommended) Discrete sine transform
Syntax
y = dst(x)
y = dst(x,n)
Description
y = dst(x) computes the discrete sine transform of x according to the equation
N
kn
y(k) = ∑ x(n)sin π
N+1
, k = 1, ..., N
n=1
If x is a matrix, then dst applies to each column. For best performance, the number of rows in x must
be 2m – 1, where m is an integer.
y = dst(x,n) truncates the vector x or pads it with trailing zeros to length n before computing the
transform. If x is a matrix, then dst truncates or pads each column.
Examples
Find the discrete sine transform of the exponential by using dst, and then invert the result by using
idst.
Create a time vector sampled in increments of 0.1 second over a period of 10 seconds.
Ts = 0.1;
t = 0:Ts:10;
x = exp(t);
plot(t,x)
xlabel('Time (seconds)')
ylabel('Amplitude')
5-276
dst
Compute the discrete sign transform of the signal, and create the vector f that corresponds to the
sampling of the signal in frequency space.
y = dst(x);
fs = 1/Ts;
f = (0:length(y)-1)*fs/length(y);
plot(f,y)
xlabel('Frequency (Hz)')
ylabel('Magnitude')
5-277
5 Functions
Compute the inverse discrete sine transform of y, and plot the result.
z = idst(y);
figure
plot(t,z)
xlabel('Time (seconds)')
ylabel('Amplitude')
5-278
dst
Input Arguments
x — Input array
vector | matrix
Input array, specified as a vector or a matrix. If x is a matrix, then dst applies to each column.
Data Types: double
n — Transform length
nonnegative integer
Transform length, specified as a nonnegative integer. If x is a vector, then dst truncates it or pads it
with trailing zeros, so that the resulting vector has n elements. If x is a matrix, then dst truncates or
pads each column.
Data Types: double
Output Arguments
y — Discrete sine transform coefficients
row vector | matrix
Discrete sine transform coefficients, returned as a vector or matrix of the same size as x.
5-279
5 Functions
Version History
Introduced before R2006a
See Also
idst
5-280
idst
idst
(Not recommended) Invert discrete sine transform
Syntax
x = idst(y)
x = idst(y,n)
Description
x = idst(y) computes the inverse discrete sine transform of y according to the equation
N
2 kn
N + 1 n∑
x(k) = y(n)sin π , k = 1, ..., N
=1
N +1
If y is a matrix, idst applies to each column. For best performance, the number of rows in y must be
2m – 1, where m is an integer.
x = idst(y,n) truncates the vector y or pads it with zeros to length n before computing the
transform.
Examples
Find the discrete sine transform of the exponential by using dst, and then invert the result by using
idst.
Create a time vector sampled in increments of 0.1 second over a period of 10 seconds.
Ts = 0.1;
t = 0:Ts:10;
x = exp(t);
plot(t,x)
xlabel('Time (seconds)')
ylabel('Amplitude')
5-281
5 Functions
Compute the discrete sign transform of the signal, and create the vector f that corresponds to the
sampling of the signal in frequency space.
y = dst(x);
fs = 1/Ts;
f = (0:length(y)-1)*fs/length(y);
plot(f,y)
xlabel('Frequency (Hz)')
ylabel('Magnitude')
5-282
idst
Compute the inverse discrete sine transform of y, and plot the result.
z = idst(y);
figure
plot(t,z)
xlabel('Time (seconds)')
ylabel('Amplitude')
5-283
5 Functions
Input Arguments
y — Input array
vector | matrix
Input array, specified as a vector or a matrix. If y is a matrix, then idst applies to each column.
Data Types: double
n — Transform length
nonnegative integer
Transform length, specified as a nonnegative integer. If y is a vector, then idst truncates it or pads it
with trailing zeros, so that the resulting vector has n elements. If y is a matrix, then idst truncates
or pads each column.
Data Types: double
Output Arguments
x — Inverse discrete sine transform coefficients
vector | matrix
Inverse discrete sine transform coefficients, returned as a vector or matrix of the same size as y.
5-284
idst
Version History
Introduced before R2006a
See Also
dst
5-285
5 Functions
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
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-429.
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.
5-286
EigenResults
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)
results =
EigenResults with properties:
pdeplot(model,'XYData',results.Eigenvectors(:,10))
5-287
5 Functions
Version History
Introduced in R2016a
See Also
solvepdeeig | StationaryResults | TimeDependentResults
Topics
“Eigenvalues and Eigenmodes of L-Shaped Membrane” on page 3-353
“Eigenvalues and Eigenmodes of Square” on page 3-364
“Solve Problems Using PDEModel Objects” on page 2-3
5-288
ElectromagneticModel
ElectromagneticModel
Electromagnetic model object
Description
An ElectromagneticModel object contains information about an electromagnetic analysis problem:
the geometry, material properties, electromagnetic sources, boundary conditions, and mesh.
Creation
To create a ElectromagneticModel object, use the createpde function and specify
"electromagnetic" as its first argument.
Properties
AnalysisType — Type of electromagnetic analysis
'electrostatic' | 'magnetostatic' | 'harmonic' | 'conduction' | 'electrostatic-
axisymmetric' | 'magnetostatic-axisymmetric' | 'harmonic-axisymmetric'
Material properties within the domain, specified as an object containing the material property
assignments.
Boundary conditions applied to the geometry, specified as an object containing the boundary
condition assignments.
5-289
5 Functions
Permittivity of vacuum for the entire model, specified as a number. This value must be consistent with
the units of the model. If the model parameters are in the SI system of units, then the permittivity of
vacuum must be 8.8541878128E-12.
Permeability of vacuum for the entire model, specified as a number. This value must be consistent
with the units of the model. If the model parameters are in the SI system of units, then the
permeability of vacuum must be 1.2566370614E-6.
Mesh for the solution, specified as a FEMesh object. See FEMesh. You create the mesh using the
generateMesh function. For a 3-D magnetostatic model, the mesh must be linear.
Algorithm options for the PDE solvers, specified as a PDESolverOptions object. The properties of a
PDESolverOptions object include absolute and relative tolerances for internal ODE solvers,
maximum solver iterations, and so on. For details, see PDESolverOptions.
Object Functions
geometryFromEdges Create 2-D geometry from decomposed geometry matrix
geometryFromMesh Create 2-D or 3-D geometry from mesh
importGeometry Import geometry from STL or STEP file
generateMesh Create triangular or tetrahedral mesh
electromagneticProperties Assign properties of material for electromagnetic model
electromagneticSource Specify current density, charge density, and magnetization for
electromagnetic model
electromagneticBC Apply boundary conditions to electromagnetic model
solve Solve structural analysis, heat transfer, or electromagnetic analysis
problem
Examples
emagE = createpde("electromagnetic","electrostatic")
5-290
ElectromagneticModel
emagE =
ElectromagneticModel with properties:
AnalysisType: "electrostatic"
Geometry: []
MaterialProperties: []
Sources: []
BoundaryConditions: []
VacuumPermittivity: []
Mesh: []
Create an axisymmetric model for magnetostatic analysis. An axisymmetric model simplifies a 3-D
problem to a 2-D problem using symmetry around the axis of rotation.
emagMA = createpde("electromagnetic","magnetostatic-axisymmetric")
emagMA =
ElectromagneticModel with properties:
AnalysisType: "magnetostatic-axisymmetric"
Geometry: []
MaterialProperties: []
Sources: []
BoundaryConditions: []
VacuumPermeability: []
Mesh: []
emagH = createpde("electromagnetic","harmonic")
emagH =
ElectromagneticModel with properties:
AnalysisType: "harmonic"
Geometry: []
MaterialProperties: []
Sources: []
BoundaryConditions: []
VacuumPermittivity: []
VacuumPermeability: []
Mesh: []
FieldType: "electric"
emagDC = createpde("electromagnetic","conduction")
emagDC =
ElectromagneticModel with properties:
AnalysisType: "conduction"
Geometry: []
MaterialProperties: []
BoundaryConditions: []
5-291
5 Functions
Mesh: []
Version History
Introduced in R2021a
The programmatic workflow for a DC conduction analysis enables you to analyze stationary current
distribution in conductors due to applied voltage.
You can also specify magnetization using the electromagneticSource function to account for
materials generating their own magnetic fields in a magnetostatic analysis workflow.
The programmatic workflow for a harmonic electromagnetic analysis enables you to set up, solve, and
analyze time-harmonic Maxwell’s equations (the Helmholtz equation).
The programmatic workflow for electrostatic and magnetostatic analyses now enables you to set up,
solve, and analyze 3-D problems in addition to previously supported 2-D problems.
See Also
electromagneticProperties | electromagneticSource | electromagneticBC | solve
5-292
electromagneticBC
electromagneticBC
Package: pde
Syntax
electromagneticBC(emagmodel,RegionType,RegionID,"Voltage",V)
electromagneticBC(emagmodel,RegionType,RegionID,"MagneticPotential",A)
electromagneticBC(emagmodel,RegionType,RegionID,"SurfaceCurrentDensity",K)
electromagneticBC(emagmodel,RegionType,RegionID,"ElectricField",E)
electromagneticBC(emagmodel,RegionType,RegionID,"MagneticField",H)
electromagneticBC(emagmodel,RegionType,
RegionID,"FarField","absorbing","Thickness",h)
electromagneticBC(emagmodel,RegionType,
RegionID,"FarField","absorbing","Thickness",h,"Exponent",e,"Scaling",s)
Description
electromagneticBC(emagmodel,RegionType,RegionID,"Voltage",V) adds a voltage
boundary condition to emagmodel. The boundary condition applies to regions of type RegionType
with ID numbers in RegionID. The solver uses a voltage boundary condition for an electrostatic
analysis.
electromagneticBC(emagmodel,RegionType,RegionID,"MagneticPotential",A) adds a
magnetic potential boundary condition to emagmodel. The solver uses a magnetic potential boundary
condition for a magnetostatic analysis.
electromagneticBC(emagmodel,RegionType,RegionID,"SurfaceCurrentDensity",K)
adds a surface current density boundary condition to emagmodel. The solver uses a surface current
density boundary condition for a DC conduction analysis.
electromagneticBC(emagmodel,RegionType,RegionID,"ElectricField",E) adds an
electric field boundary condition to emagmodel. The solver uses an electric field boundary condition
for a harmonic analysis with the electric field type.
electromagneticBC(emagmodel,RegionType,RegionID,"MagneticField",H) adds a
magnetic field boundary condition to emagmodel. The solver uses a magnetic field boundary
condition for a harmonic analysis with the magnetic field type.
electromagneticBC(emagmodel,RegionType,
RegionID,"FarField","absorbing","Thickness",h) adds an absorbing boundary condition to
emagmodel and specifies the thickness of the absorbing region. The solver uses an absorbing
boundary condition for a harmonic analysis.
electromagneticBC(emagmodel,RegionType,
RegionID,"FarField","absorbing","Thickness",h,"Exponent",e,"Scaling",s)
5-293
5 Functions
specifies the rate of attenuation of the waves entering the absorbing region. You can specify e, s, or
both.
Use this syntax with any of the input argument combinations in the previous syntaxes.
Examples
Apply the voltage boundary condition on the side faces of the geometry.
5-294
electromagneticBC
bc1 = electromagneticBC(emagmodel,"Voltage",0,"Face",3:6)
bc1 =
ElectromagneticBCAssignment with properties:
RegionID: [3 4 5 6]
RegionType: 'Face'
Vectorized: 'off'
Voltage: 0
Apply the voltage boundary condition on the face bordering the hole.
bc2 = electromagneticBC(emagmodel,"Voltage",1000,"Face",7)
bc2 =
ElectromagneticBCAssignment with properties:
RegionID: 7
RegionType: 'Face'
Vectorized: 'off'
Voltage: 1000
emagmodel = createpde("electromagnetic","magnetostatic");
geometryFromEdges(emagmodel,@circleg);
electromagneticBC(emagmodel,"Edge",1,"MagneticPotential",0)
ans =
ElectromagneticBCAssignment with properties:
RegionID: 1
RegionType: 'Edge'
Vectorized: 'off'
MagneticPotential: 0
emagmodel = createpde("electromagnetic","conduction");
gm = importGeometry(emagmodel,"PlateHoleSolid.stl");
pdegplot(gm,"FaceLabels","on","FaceAlpha",0.3)
5-295
5 Functions
Apply the surface current density boundary condition on the front and back faces of the geometry.
electromagneticBC(emagmodel,"SurfaceCurrentDensity",100,"Face",[1 2])
ans =
ElectromagneticBCAssignment with properties:
RegionID: [1 2]
RegionType: 'Face'
Vectorized: 'off'
Voltage: []
SurfaceCurrentDensity: 100
Use a function handle to specify a boundary condition that depends on the coordinates.
emagmodel = createpde("electromagnetic","electrostatic");
geometryFromEdges(emagmodel,@circleg);
5-296
electromagneticBC
bc = @(location,~)location.x.^2;
electromagneticBC(emagmodel,"Edge",1:emagmodel.Geometry.NumEdges, ...
"Voltage",bc)
ans =
ElectromagneticBCAssignment with properties:
RegionID: [1 2 3 4]
RegionType: 'Edge'
Vectorized: 'off'
Voltage: @(location,~)location.x.^2
Specify an absorbing boundary condition and an electric field on a boundary for harmonic analysis.
emagmodel = createpde("electromagnetic","harmonic");
gm = importGeometry(emagmodel,"PlateHolePlanar.stl");
pdegplot(gm,"EdgeLabels","on")
5-297
5 Functions
electromagneticBC(emagmodel,"Edge",5,"ElectricField",[10 0])
ans =
ElectromagneticBCAssignment with properties:
RegionID: 5
RegionType: 'Edge'
Vectorized: 'off'
ElectricField: [10 0]
MagneticField: []
Far Field
FarField: []
Thickness: []
Scaling: 5
Exponent: 4
Specify absorbing regions with the thickness 2 on the edges of the rectangle. Use the default
attenuation rate for the absorbing regions.
electromagneticBC(emagmodel,"Edge",1:4, ...
"FarField","absorbing", ...
"Thickness",2)
5-298
electromagneticBC
ans =
ElectromagneticBCAssignment with properties:
RegionID: [1 2 3 4]
RegionType: 'Edge'
Vectorized: 'off'
ElectricField: [2x1 double]
MagneticField: [2x1 double]
Far Field
FarField: "absorbing"
Thickness: 2
Scaling: 5
Exponent: 4
Now specify the attenuation rate for the absorbing regions by using the Exponent and Scaling
arguments.
electromagneticBC(emagmodel,"Edge",1:4, ...
"FarField","absorbing", ...
"Thickness",2, ...
"Exponent",3, ...
"Scaling",100)
ans =
ElectromagneticBCAssignment with properties:
RegionID: [1 2 3 4]
RegionType: 'Edge'
Vectorized: 'off'
ElectricField: [2x1 double]
MagneticField: [2x1 double]
Far Field
FarField: "absorbing"
Thickness: 2
Scaling: 100
Exponent: 3
emagmodel =
ElectromagneticModel with properties:
AnalysisType: "harmonic"
Geometry: []
MaterialProperties: []
Sources: []
5-299
5 Functions
BoundaryConditions: []
VacuumPermittivity: []
VacuumPermeability: []
Mesh: []
FieldType: "electric"
emagmodel.FieldType = "magnetic"
emagmodel =
ElectromagneticModel with properties:
AnalysisType: "harmonic"
Geometry: []
MaterialProperties: []
Sources: []
BoundaryConditions: []
VacuumPermittivity: []
VacuumPermeability: []
Mesh: []
FieldType: "magnetic"
Include a square geometry in the model. Plot the geometry with the edge labels.
geometryFromEdges(emagmodel,@squareg);
pdegplot(emagmodel,"EdgeLabels","on")
xlim([-1.2 1.2])
ylim([-1.2 1.2])
5-300
electromagneticBC
electromagneticBC(emagmodel,"Edge",1:4,"MagneticField",[10 10])
ans =
ElectromagneticBCAssignment with properties:
RegionID: [1 2 3 4]
RegionType: 'Edge'
Vectorized: 'off'
ElectricField: []
MagneticField: [10 10]
Far Field
FarField: []
Thickness: []
Scaling: 5
Exponent: 4
Input Arguments
emagmodel — Electromagnetic model
ElectromagneticModel object
5-301
5 Functions
Geometric region type, specified as "Edge" for a 2-D model or "Face" for a 3-D model.
Example: electromagneticBC(emagmodel,"Edge",1,"Voltage",100)
Data Types: char | string
RegionID — Region ID
vector of positive integers
Region ID, specified as a vector of positive integers. Find the edge or face IDs by using pdegplot
with the EdgeLabels or FaceLabels name-value argument set to "on".
Data Types: double
V — Voltage
real number | function handle
Voltage, specified as a real number or a function handle. Use a function handle to specify a voltage
that depends on the coordinates. For details, see “More About” on page 5-303.
A — Magnetic potential
real number | column vector | function handle
Magnetic potential, specified as a real number, a column vector of three elements for a 3-D model, or
a function handle. Use a function handle to specify a magnetic potential that depends on the
coordinates. For details, see “More About” on page 5-303.
The solver uses a magnetic potential boundary condition for a magnetostatic analysis.
Data Types: double | function_handle
E — Electric field
column vector | function handle
Electric field, specified as a column vector of two elements for a 2-D model, a vector of three
elements for a 3-D model, or a function handle. Use a function handle to specify an electric field that
depends on the coordinates. For details, see “More About” on page 5-303.
The solver uses an electric field boundary condition for a harmonic analysis with the electric field
type.
Data Types: double | function_handle
Surface current density in the direction normal to the boundary, specified as a real number or a
function handle. The solver uses a surface current density boundary condition for a DC conduction
5-302
electromagneticBC
analysis. Use a function handle to specify a surface current density that depends on the coordinates.
For details, see “More About” on page 5-303.
Data Types: double
H — Magnetic field
column vector | function handle
Magnetic field, specified as a column vector of two elements for a 2-D model, a column vector of
three elements for a 3-D model, or a function handle. Use a function handle to specify a magnetic
field that depends on the coordinates. For details, see “More About” on page 5-303.
The solver uses a magnetic field boundary condition for a harmonic analysis with the magnetic field
type.
Data Types: double | function_handle
Width of the far field absorbing region, specified as a nonnegative number. The solver uses an
absorbing boundary condition for a harmonic analysis.
Data Types: double
Exponent defining the attenuation rate of the waves entering the absorbing region, specified as a
nonnegative number. The solver uses an absorbing boundary condition for a harmonic analysis.
Data Types: double
Scaling parameter defining the attenuation rate of the waves entering the absorbing region, specified
as a nonnegative number. The solver uses an absorbing boundary condition for a harmonic analysis.
Data Types: double
Output Arguments
emagBC — Handle to electromagnetic boundary condition
ElectromagneticBCAssignment object
More About
Specifying Nonconstant Parameters of Electromagnetic Model
In Partial Differential Equation Toolbox, use a function handle to specify these electromagnetic
parameters when they depend on the coordinates and, for a harmonic analysis, on the frequency:
5-303
5 Functions
For example, use function handles to specify the relative permittivity, charge density, and voltage on
the boundary for emagmodel.
electromagneticProperties(emagmodel, ...
"RelativePermittivity", ...
@myfunPermittivity)
electromagneticSource(emagmodel, ...
"ChargeDensity",@myfunCharge, ...
"Face",2)
electromagneticBC(emagmodel, ...
"Voltage",@myfunBC, ...
"Edge",2)
The solver computes and populates the data in the location and state structure arrays and passes
this data to your function. You can define your function so that its output depends on this data. You
can use any names in place of location and state.
If you call electromagneticBC with Vectorized set to "on", then location can contain several
evaluation points. If you do not set Vectorized or set Vectorized to "off", then the solver passes
just one evaluation point in each call.
Furthermore, for boundary conditions, the solver passes this data in the location structure:
• location.nx — The x-component of the normal vector at the evaluation point or points
• location.ny — The y-component of the normal vector at the evaluation point or points
• location.nz — For a 3-D or an axisymmetric geometry, the z-component of the normal vector
at the evaluation point or points
5-304
electromagneticBC
• location.nr — For an axisymmetric geometry, the r-component of the normal vector at the
evaluation point or points
• state — A structure array containing this field for a harmonic electromagnetic problem:
Relative permittivity, relative permeability, and conductivity get this data from the solver:
Charge density, current density, magnetization, surface current density on the boundary, and electric
or magnetic field on the boundary get this data from the solver:
Voltage or magnetic potential on the boundary get these data from the solver:
When you solve an electrostatic, magnetostatic, or DC conduction problem, the output returned by
the function handle must be of the following size. Here, Np = numel(location.x) is the number of
points.
When you solve a harmonic problem, the output returned by the function handle must be of the
following size. Here, Np = numel(location.x) is the number of points.
• 1-by-Np if a function specifies the nonconstant relative permittivity, relative permeability, and
conductivity.
• 2-by-Np for a 2-D problem and 3-by-Np for a 3-D problem if a function specifies the nonconstant
electric or magnetic field.
• 2-by-Np or Np-by-2 for a 2-D problem and 3-by-Np or Np-by-3 for a 3-D problem if a function
specifies the nonconstant current density and the field type is electric.
• 1-by-Np or Np-by-1 for a 2-D problem and 3-by-Np or Np-by-3 for a 3-D problem if a function
specifies the nonconstant current density and the field type is magnetic.
If relative permittivity, relative permeability, or conductivity for a harmonic analysis depends on the
frequency, ensure that your function returns a matrix of NaN values of the correct size when
state.frequency is NaN. Solvers check whether a problem is nonlinear by passing NaN state values
and looking for returned NaN values.
5-305
5 Functions
To use additional arguments in your function, wrap your function (that takes additional arguments)
with an anonymous function that takes only the location and state arguments. For example:
Version History
Introduced in R2021a
Surface current density boundary condition can be specified for a DC conduction analysis.
Electric and magnetic field on boundaries, and absorbing boundary conditions can be specified for
harmonic analysis.
Voltage and magnetic potential can be specified on faces for 3-D electrostatic and magnetostatic
problems.
See Also
ElectromagneticModel | ElectromagneticBCAssignment Properties | createpde |
electromagneticSource | solve | assembleFEMatrices | electromagneticProperties
5-306
ElectromagneticBCAssignment Properties
ElectromagneticBCAssignment Properties
Electromagnetic boundary condition assignments
Description
An ElectromagneticBCAssignment object specifies the type of PDE boundary condition on a set of
geometry boundaries. An ElectromagneticModel object contains an array of
ElectromagneticBCAssignment objects in its BoundaryConditions.BCAssignments property.
Create boundary condition assignments for your electromagnetic model using the
electromagneticBC function.
Properties
Properties
Electric field boundary condition, specified as a column vector of two elements for a 2-D model, a
column vector of three elements for a 3-D model, or a function handle. Use a function handle to
specify an electric field that depends on the coordinates.
The solver uses an electric field boundary condition for a harmonic analysis with the electric field
type.
Data Types: double | function_handle
Magnetic field boundary condition, specified as a column vector of two elements for a 2-D model, a
column vector of three elements for a 3-D model, or a function handle. Use a function handle to
specify a magnetic field that depends on the coordinates.
The solver uses a magnetic field boundary condition for a harmonic analysis with the magnetic field
type.
Data Types: double | function_handle
Magnetic potential boundary condition, specified as a real number for a 2-D model, a column vector
of three elements for a 3-D model, or a function handle. Use a function handle to specify a magnetic
potential that depends on the coordinates.
The solver uses a magnetic potential boundary condition for a magnetostatic analysis.
Data Types: double | function_handle
5-307
5 Functions
Surface current density boundary condition, specified as a real number. The solver uses a surface
current density boundary condition for a DC conduction analysis.
Data Types: double
RegionID — Region ID
vector of positive integers
Region ID, specified as a vector of positive integers. Find the edge or face IDs by using pdegplot
with the EdgeLabels or FaceLabels name-value argument set to "on".
Data Types: double
Geometric region type, specified as "Edge" for a 2-D model or "Face" for a 3-D model.
Data Types: char | string
Vectorized function evaluation, specified as "off" or "on". This property applies when you pass a
function handle as an argument. To save time in the function handle evaluation, specify "on" if your
function handle computes in a vectorized fashion. See “Vectorization”. For details on vectorized
function evaluation, see “Nonconstant Boundary Conditions” on page 2-131.
Data Types: char | string
Voltage boundary condition, specified as a real number or a function handle. Use a function handle to
specify a voltage that depends on the coordinates.
Absorbing boundary condition, specified as "absorbing". The solver uses an absorbing boundary
condition for a harmonic analysis.
Data Types: char
Width of the far field absorbing region, specified as a nonnegative number. The solver uses an
absorbing boundary condition for a harmonic analysis.
Data Types: double
5-308
ElectromagneticBCAssignment Properties
Scaling parameter defining the attenuation rate of the waves entering the absorbing region, specified
as a nonnegative number. The solver uses an absorbing boundary condition for a harmonic analysis.
Data Types: double
Exponent defining the attenuation rate of the waves entering the absorbing region, specified as a
nonnegative number. The solver uses an absorbing boundary condition for a harmonic analysis.
Data Types: double
Version History
Introduced in R2021a
See Also
ElectromagneticModel | electromagneticBC
5-309
5 Functions
electromagneticProperties
Package: pde
Syntax
electromagneticProperties(emagmodel,"RelativePermittivity",epsilon)
electromagneticProperties(emagmodel,"RelativePermeability",mu)
electromagneticProperties(emagmodel,"Conductivity",sigma)
electromagneticProperties(emagmodel,"RelativePermittivity",
epsilon,"RelativePermeability",mu,"Conductivity",sigma)
electromagneticProperties( ___ ,RegionType,RegionID)
mtl = electromagneticProperties( ___ )
Description
electromagneticProperties(emagmodel,"RelativePermittivity",epsilon) assigns the
relative permittivity epsilon to the entire geometry. Specify the permittivity of vacuum using the
electromagnetic model properties. The solver uses a relative permittivity for electrostatic and
harmonic analyses.
electromagneticProperties(emagmodel,"RelativePermittivity",
epsilon,"RelativePermeability",mu,"Conductivity",sigma) assigns the relative
permittivity, relative permeability, and conductivity to the entire geometry. Specify the permittivity
and permeability of vacuum using the electromagnetic model properties. The solver requires all three
parameters for a harmonic analysis.
For a nonconstant material, specify epsilon, mu, and sigma as function handles.
5-310
electromagneticProperties
Examples
mtl =
ElectromagneticMaterialAssignment with properties:
RegionType: 'Cell'
5-311
5 Functions
RegionID: 1
RelativePermittivity: 2.2500
RelativePermeability: []
Conductivity: []
5-312
electromagneticProperties
mtl =
ElectromagneticMaterialAssignment with properties:
RegionType: 'Face'
RegionID: 1
RelativePermittivity: []
RelativePermeability: 5000
Conductivity: []
Specify Conductivity
Import and plot a geometry representing a plate with a hole in its center.
gm = importGeometry(emagmodel,"PlateHoleSolid.stl");
pdegplot(gm)
5-313
5 Functions
ans =
ElectromagneticMaterialAssignment with properties:
RegionType: 'Cell'
RegionID: 1
RelativePermittivity: []
RelativePermeability: []
Conductivity: 37000000
Specify relative permittivity, relative permeability, and conductivity of a material for harmonic
analysis.
Specify the vacuum permittivity and permeability values in the SI system of units.
5-314
electromagneticProperties
emagmodel.VacuumPermeability = 1.2566370614E-6;
emagmodel.VacuumPermittivity = 8.8541878128E-12;
Specify the relative permittivity, relative permeability, and conductivity of the material.
electromagneticProperties(emagmodel,"RelativePermittivity",2.25, ...
"RelativePermeability",5000, ...
"Conductivity",1)
ans =
ElectromagneticMaterialAssignment with properties:
RegionType: 'Cell'
RegionID: 1
RelativePermittivity: 2.2500
RelativePermeability: 5000
Conductivity: 1
emagmodel = createpde("electromagnetic","electrostatic");
Create a 2-D geometry with two faces. First, import and plot a 2-D geometry representing a plate
with a hole.
gm = importGeometry(emagmodel,"PlateHolePlanar.stl");
pdegplot(gm,"EdgeLabels","on","FaceLabels","on")
5-315
5 Functions
Then, fill the hole by adding a face and plot the resulting geometry.
gm = addFace(gm,5);
pdegplot(gm,"FaceLabels","on")
5-316
electromagneticProperties
emagmodel.VacuumPermittivity = 8.8541878128E-12;
electromagneticProperties(emagmodel,"RelativePermittivity",2.25, ...
"Face",1)
ans =
ElectromagneticMaterialAssignment with properties:
RegionType: 'Face'
RegionID: 1
RelativePermittivity: 2.2500
RelativePermeability: []
Conductivity: []
electromagneticProperties(emagmodel,"RelativePermittivity",1, ...
"Face",2)
ans =
ElectromagneticMaterialAssignment with properties:
RegionType: 'Face'
RegionID: 2
RelativePermittivity: 1
5-317
5 Functions
RelativePermeability: []
Conductivity: []
Use a function handle to specify a relative permittivity that depends on the spatial coordinates.
emagmodel = createpde("electromagnetic","electrostatic");
geometryFromEdges(emagmodel,@squareg);
emagmodel.VacuumPermittivity = 8.8541878128E-12;
Specify the relative permittivity of the material as a function of the x-coordinate, ε = 1 + x2.
ans =
ElectromagneticMaterialAssignment with properties:
RegionType: 'Face'
RegionID: 1
RelativePermittivity: @(location,~)sqrt(1+location.x.^2)
RelativePermeability: []
Conductivity: []
Input Arguments
emagmodel — Electromagnetic model
ElectromagneticModel object
5-318
electromagneticProperties
• Use a function handle to specify a relative permittivity that depends on the coordinates and, for a
harmonic analysis, on the frequency.
mu — Relative permeability
positive number | complex number | function handle
sigma — Conductivity
nonnegative number | function handle
Geometric region type, specified as "Face" for a 2-D geometry or "Cell" for a 3-D geometry.
Data Types: char | string
RegionID — Region ID
vector of positive integers
Region ID, specified as a vector of positive integers. Find the face or cell IDs by using pdegplot with
the "FaceLabels" or "CellLabels" name-value argument set to "on".
Example:
electromagneticProperties(emagmodel,"RelativePermeability",5000,"Face",1:3)
Data Types: double
Output Arguments
mtl — Handle to material properties
ElectromagneticMaterialAssignment object
5-319
5 Functions
More About
Specifying Nonconstant Parameters of Electromagnetic Model
In Partial Differential Equation Toolbox, use a function handle to specify these electromagnetic
parameters when they depend on the coordinates and, for a harmonic analysis, on the frequency:
For example, use function handles to specify the relative permittivity, charge density, and voltage on
the boundary for emagmodel.
electromagneticProperties(emagmodel, ...
"RelativePermittivity", ...
@myfunPermittivity)
electromagneticSource(emagmodel, ...
"ChargeDensity",@myfunCharge, ...
"Face",2)
electromagneticBC(emagmodel, ...
"Voltage",@myfunBC, ...
"Edge",2)
The solver computes and populates the data in the location and state structure arrays and passes
this data to your function. You can define your function so that its output depends on this data. You
can use any names in place of location and state.
If you call electromagneticBC with Vectorized set to "on", then location can contain several
evaluation points. If you do not set Vectorized or set Vectorized to "off", then the solver passes
just one evaluation point in each call.
5-320
electromagneticProperties
• location.z — For a 3-D or an axisymmetric geometry, the z-coordinate of the point or points
• location.r — For an axisymmetric geometry, the r-coordinate of the point or points
Furthermore, for boundary conditions, the solver passes this data in the location structure:
• location.nx — The x-component of the normal vector at the evaluation point or points
• location.ny — The y-component of the normal vector at the evaluation point or points
• location.nz — For a 3-D or an axisymmetric geometry, the z-component of the normal vector
at the evaluation point or points
• location.nr — For an axisymmetric geometry, the r-component of the normal vector at the
evaluation point or points
• state — A structure array containing this field for a harmonic electromagnetic problem:
Relative permittivity, relative permeability, and conductivity get this data from the solver:
Charge density, current density, magnetization, surface current density on the boundary, and electric
or magnetic field on the boundary get this data from the solver:
Voltage or magnetic potential on the boundary get these data from the solver:
When you solve an electrostatic, magnetostatic, or DC conduction problem, the output returned by
the function handle must be of the following size. Here, Np = numel(location.x) is the number of
points.
When you solve a harmonic problem, the output returned by the function handle must be of the
following size. Here, Np = numel(location.x) is the number of points.
• 1-by-Np if a function specifies the nonconstant relative permittivity, relative permeability, and
conductivity.
• 2-by-Np for a 2-D problem and 3-by-Np for a 3-D problem if a function specifies the nonconstant
electric or magnetic field.
5-321
5 Functions
• 2-by-Np or Np-by-2 for a 2-D problem and 3-by-Np or Np-by-3 for a 3-D problem if a function
specifies the nonconstant current density and the field type is electric.
• 1-by-Np or Np-by-1 for a 2-D problem and 3-by-Np or Np-by-3 for a 3-D problem if a function
specifies the nonconstant current density and the field type is magnetic.
If relative permittivity, relative permeability, or conductivity for a harmonic analysis depends on the
frequency, ensure that your function returns a matrix of NaN values of the correct size when
state.frequency is NaN. Solvers check whether a problem is nonlinear by passing NaN state values
and looking for returned NaN values.
To use additional arguments in your function, wrap your function (that takes additional arguments)
with an anonymous function that takes only the location and state arguments. For example:
Version History
Introduced in R2021a
Relative permeability can depend on the magnetic flux density, magnetic potential, and its gradients.
Material properties now include conductivity. For harmonic analysis, relative permittivity, relative
permeability, and conductivity can depend on frequency. Also for harmonic analysis, relative
permittivity and permeability can be a complex value.
See Also
ElectromagneticModel | ElectromagneticMaterialAssignment Properties | createpde |
electromagneticSource | electromagneticBC | solve | assembleFEMatrices
5-322
ElectromagneticMaterialAssignment Properties
ElectromagneticMaterialAssignment Properties
Electromagnetic material properties assignments
Description
An ElectromagneticMaterialAssignment object describes the material properties of an
electromagnetic model. An ElectromagneticModel object contains a vector of
ElectromagneticMaterialAssignment objects in its
MaterialProperties.MaterialAssignments property.
Create material property assignments for your electromagnetic model using the
electromagneticProperties function.
Properties
Properties
Geometric region type, specified as "Face" for a 2-D geometry or "Cell" for a 3-D geometry.
Data Types: char | string
RegionID — Region ID
vector of positive integers
Region ID, specified as a vector of positive integers. Find the face or cell IDs by using pdegplot with
the "FaceLabels" or "CellLabels" name-value argument set to "on".
Data Types: double
Relative permittivity of the material, specified as a positive or complex number or a function handle.
Relative permeability of the material, specified as a positive or complex number or a function handle.
5-323
5 Functions
Tips
• When there are multiple assignments to the same face, the toolbox uses the last applied setting.
• To avoid assigning material properties to the wrong region, check that you are using the correct
face IDs and cell IDs by plotting and visually inspecting the geometry. Use pdegplot with the
"FaceLabels" or "CellLabels" name-value argument set to "on".
Version History
Introduced in R2021a
See Also
ElectromagneticModel | electromagneticProperties | pdegplot
5-324
electromagneticSource
electromagneticSource
Package: pde
Specify current density, charge density, and magnetization for electromagnetic model
Syntax
electromagneticSource(emagmodel,"ChargeDensity",rho)
electromagneticSource(emagmodel,"CurrentDensity",J)
electromagneticSource(emagmodel,"Magnetization",M)
electromagneticSource( ___ ,RegionType,RegionID)
emagSource = electromagneticSource( ___ )
Description
electromagneticSource(emagmodel,"ChargeDensity",rho) specifies the charge density. The
solver uses a charge density for an electrostatic analysis.
For a 3-D magnetostatic analysis, you can specify current density by using the DC conduction results.
See ConductionResults. The toolbox does not support conduction results as a source of current
density for a 2-D magnetostatic analysis, in which case current density must be a scalar or a function
handle returning a scalar that represents out-of-plane current.
Examples
ans =
ElectromagneticSourceAssignment with properties:
RegionType: 'Cell'
RegionID: 1
5-325
5 Functions
ChargeDensity: 10
CurrentDensity: []
Magnetization: []
model = createpde("electromagnetic","harmonic");
Include a square geometry in the model. Plot the geometry with the edge labels.
geometryFromEdges(model,@squareg);
pdegplot(model,"EdgeLabels","on")
xlim([-1.1 1.1])
ylim([-1.1 1.1])
Specify current density on the entire geometry. For a 2-D harmonic analysis model with the electric
field type, the current density must be a column vector of two elements. When solving the model, the
toolbox multiplies the specified current density value by -i and by frequency.
electromagneticSource(model,"CurrentDensity",[1;0])
5-326
electromagneticSource
ans =
ElectromagneticSourceAssignment with properties:
RegionType: 'Face'
RegionID: 1
ChargeDensity: []
CurrentDensity: [2x1 double]
Magnetization: []
Create a 2-D geometry with two faces. First, import and plot a 2-D geometry representing a plate
with a hole.
gm = importGeometry(emagmodel,"PlateHolePlanar.stl");
pdegplot(gm,"EdgeLabels","on","FaceLabels","on")
Then, fill the hole by adding a face and plot the resulting geometry.
5-327
5 Functions
gm = addFace(gm,5);
pdegplot(gm,"FaceLabels","on")
sc1 = electromagneticSource(emagmodel,"Face",1,"ChargeDensity",0.3)
sc1 =
ElectromagneticSourceAssignment with properties:
RegionType: 'Face'
RegionID: 1
ChargeDensity: 0.3000
CurrentDensity: []
Magnetization: []
sc2 = electromagneticSource(emagmodel,"Face",2,"ChargeDensity",0.28)
sc2 =
ElectromagneticSourceAssignment with properties:
RegionType: 'Face'
RegionID: 2
ChargeDensity: 0.2800
CurrentDensity: []
Magnetization: []
5-328
electromagneticSource
Use a function handle to specify a charge density that depends on the coordinates.
emagmodel = createpde("electromagnetic","electrostatic");
geometryFromEdges(emagmodel,@circleg);
ans =
ElectromagneticSourceAssignment with properties:
RegionType: 'Face'
RegionID: 1
ChargeDensity: @(location,~)0.3.*sqrt(location.x.^2+location.y.^2)
CurrentDensity: []
Magnetization: []
Use a solution obtained by performing DC conduction analysis to specify current density for a
magnetostatic model.
emagmodel = createpde("electromagnetic","conduction");
gm = importGeometry(emagmodel,"PlateHoleSolid.stl");
pdegplot(gm,"FaceLabels","on","FaceAlpha",0.3)
5-329
5 Functions
electromagneticProperties(emagmodel,"Conductivity",6e4);
Apply the voltage boundary conditions on the left, right, and back faces of the plate.
electromagneticBC(emagmodel,"Voltage",0,"Face",[1 3 5]);
Specify the surface current density on the front face of the geometry and on the face bordering the
hole.
electromagneticBC(emagmodel,"SurfaceCurrentDensity",100,"Face",[2 7]);
generateMesh(emagmodel);
R = solve(emagmodel);
emagmodel.AnalysisType = "magnetostatic";
This model already has a quadratic mesh that you generated for the DC conduction analysis. For a 3-
D magnetostatic model, the mesh must be linear. Generate a new linear mesh. The generateMesh
function creates a linear mesh by default if the model is 3-D and magnetostatic.
5-330
electromagneticSource
generateMesh(emagmodel);
Specify the current density for the entire geometry using the DC conduction solution.
electromagneticSource(emagmodel,"CurrentDensity",R)
ans =
ElectromagneticSourceAssignment with properties:
RegionType: 'Cell'
RegionID: 1
ChargeDensity: []
CurrentDensity: [1x1 pde.ConductionResults]
Magnetization: []
Specify Magnetization
Create a unit square geometry with a circle in its center. The circle represents a permanent magnet.
L = 0.8;
r = 0.25;
sq = [3 4 -L L L -L -L -L L L]';
circ = [1 0 0 r 0 0 0 0 0 0]';
gd = [sq,circ];
sf = "sq + circ";
ns = char('sq','circ');
ns = ns';
g = decsg(gd,sf,ns);
pdegplot(g,"FaceLabels","on")
5-331
5 Functions
emagmodel = createpde("electromagnetic","magnetostatic");
geometryFromEdges(emagmodel,g);
M = 1;
To make the circle represent a permanent magnet, specify the uniform magnetization in the positive
x-direction.
electromagneticSource(emagmodel,"Face",2,"Magnetization",M*[1;0])
ans =
ElectromagneticSourceAssignment with properties:
RegionType: 'Face'
RegionID: 2
ChargeDensity: []
CurrentDensity: []
Magnetization: [2x1 double]
5-332
electromagneticSource
Input Arguments
emagmodel — Electromagnetic model
ElectromagneticModel object
Charge density, specified as a real number or a function handle. Use a function handle to specify a
charge density that depends on the coordinates. For details, see “More About” on page 5-334.
Data Types: double | function_handle
J — Current density
real number | column vector | function handle | ConductionResults object
• A real number or a function handle for a 2-D model. The toolbox does not support conduction
results as a source of current density for a 2-D magnetostatic analysis.
• A column vector of three elements, a ConductionResults object, or a function handle for a 3-D
model.
For harmonic analysis with the electric field type, the toolbox multiplies the specified current density
by -i and by frequency. The current density must be
• A column vector of two elements or a function handle that depends on the coordinates for a 2-D
model.
• A column vector of three elements or a function handle that depends on the coordinates for a 3-D
model.
For harmonic analysis with the magnetic field type, the toolbox uses the curl of the specified current
density. The current density must be
• A scalar or a function handle that depends on the coordinates for a 2-D model.
• A column vector of three elements or a function handle that depends on the coordinates for a 3-D
model.
M — Magnetization
column vector | function handle
Magnetization, specified as a column vector of two elements for a 2-D model, a column vector of
three elements for a 3-D model, or a function handle. Use a function handle to specify a
magnetization that depends on the coordinates. For details, see “More About” on page 5-334.
5-333
5 Functions
Geometric region type, specified as "Face" for a 2-D model or "Cell" for a 3-D model.
Data Types: char | string
RegionID — Region ID
vector of positive integers
Region ID, specified as a vector of positive integers. Find the face or cell IDs by using pdegplot with
the FaceLabels or CellLabels name-value argument set to "on".
Example: electromagneticSource(emagmodel,"CurrentDensity",10,"Face",1:3)
Data Types: double
Output Arguments
emagSource — Handle to electromagnetic source
ElectromagneticSourceAssignment object
More About
Specifying Nonconstant Parameters of Electromagnetic Model
In Partial Differential Equation Toolbox, use a function handle to specify these electromagnetic
parameters when they depend on the coordinates and, for a harmonic analysis, on the frequency:
For example, use function handles to specify the relative permittivity, charge density, and voltage on
the boundary for emagmodel.
electromagneticProperties(emagmodel, ...
"RelativePermittivity", ...
5-334
electromagneticSource
@myfunPermittivity)
electromagneticSource(emagmodel, ...
"ChargeDensity",@myfunCharge, ...
"Face",2)
electromagneticBC(emagmodel, ...
"Voltage",@myfunBC, ...
"Edge",2)
The solver computes and populates the data in the location and state structure arrays and passes
this data to your function. You can define your function so that its output depends on this data. You
can use any names in place of location and state.
If you call electromagneticBC with Vectorized set to "on", then location can contain several
evaluation points. If you do not set Vectorized or set Vectorized to "off", then the solver passes
just one evaluation point in each call.
Furthermore, for boundary conditions, the solver passes this data in the location structure:
• location.nx — The x-component of the normal vector at the evaluation point or points
• location.ny — The y-component of the normal vector at the evaluation point or points
• location.nz — For a 3-D or an axisymmetric geometry, the z-component of the normal vector
at the evaluation point or points
• location.nr — For an axisymmetric geometry, the r-component of the normal vector at the
evaluation point or points
• state — A structure array containing this field for a harmonic electromagnetic problem:
Relative permittivity, relative permeability, and conductivity get this data from the solver:
Charge density, current density, magnetization, surface current density on the boundary, and electric
or magnetic field on the boundary get this data from the solver:
Voltage or magnetic potential on the boundary get these data from the solver:
5-335
5 Functions
When you solve an electrostatic, magnetostatic, or DC conduction problem, the output returned by
the function handle must be of the following size. Here, Np = numel(location.x) is the number of
points.
When you solve a harmonic problem, the output returned by the function handle must be of the
following size. Here, Np = numel(location.x) is the number of points.
• 1-by-Np if a function specifies the nonconstant relative permittivity, relative permeability, and
conductivity.
• 2-by-Np for a 2-D problem and 3-by-Np for a 3-D problem if a function specifies the nonconstant
electric or magnetic field.
• 2-by-Np or Np-by-2 for a 2-D problem and 3-by-Np or Np-by-3 for a 3-D problem if a function
specifies the nonconstant current density and the field type is electric.
• 1-by-Np or Np-by-1 for a 2-D problem and 3-by-Np or Np-by-3 for a 3-D problem if a function
specifies the nonconstant current density and the field type is magnetic.
If relative permittivity, relative permeability, or conductivity for a harmonic analysis depends on the
frequency, ensure that your function returns a matrix of NaN values of the correct size when
state.frequency is NaN. Solvers check whether a problem is nonlinear by passing NaN state values
and looking for returned NaN values.
To use additional arguments in your function, wrap your function (that takes additional arguments)
with an anonymous function that takes only the location and state arguments. For example:
Version History
Introduced in R2021a
Magnetization and current density can depend on the magnetic flux density, magnetic potential, and
its gradients.
5-336
electromagneticSource
Magnetization can be specified to account for materials generating their own magnetic fields in a
magnetostatic analysis workflow.
See Also
ElectromagneticModel | ConductionResults | ElectromagneticSourceAssignment Properties |
createpde | electromagneticProperties | electromagneticBC | solve |
assembleFEMatrices
5-337
5 Functions
ElectromagneticSourceAssignment Properties
Electromagnetic source assignments
Description
An ElectromagneticSourceAssignment object describes the source of an electromagnetic model.
An ElectromagneticModel object contains a vector of ElectromagneticSourceAssignment
objects in its Sources.SourceAssignments property.
Create electromagnetic source assignments for your model using the electromagneticSource
function.
Properties
Properties
Geometric region type, specified as "Face" for a 2-D model or "Cell" for a 3-D model.
Data Types: char | string
RegionID — Region ID
vector of positive integers
Region ID, specified as a vector of positive integers. Find the face or cell IDs by using pdegplot with
the FaceLabels or CellLabels name-value argument set to "on".
Data Types: double
Charge density, specified as a real number or a function handle. Use a function handle to specify a
charge density that depends on the coordinates.
Data Types: double | function_handle
For magnetostatic analysis, the current density must be a real number for a 2-D model, a column
vector of three elements for a 3-D model, a function handle for a 2-D or 3-D model, or a
ConductionResults object for a 3-D model.
5-338
ElectromagneticSourceAssignment Properties
For harmonic analysis with the electric field type, the current density must be a column vector of two
elements for a 2-D model, a column vector of three elements for a 3-D model, or a function handle for
a 2-D or 3-D model. The toolbox multiplies the specified current density value by -i and by frequency.
For harmonic analysis with the magnetic field type, the current density must be a scalar for a 2-D
model, a column vector of three elements for a 3-D model, or a function handle for a 2-D or 3-D
model. The toolbox uses the curl of the specified current density.
Data Types: double | function_handle
Magnetization — Magnetization
column vector | function handle
Magnetization, specified as a column vector of two elements for a 2-D model, a column vector of
three elements for a 3-D model, or a function handle. Use a function handle to specify a
magnetization that depends on the coordinates.
Data Types: double | function_handle
Version History
Introduced in R2021a
See Also
electromagneticSource | ElectromagneticModel
5-339
5 Functions
ElectrostaticResults
Electrostatic solution and derived quantities
Description
An ElectrostaticResults object contains the electric potential, electric field, and electric flux
density values in a form convenient for plotting and postprocessing.
The electric potential, electric field, and electric flux density are calculated at the nodes of the
triangular or tetrahedral mesh generated by generateMesh. Electric potential values at the nodes
appear in the ElectricPotential property. Electric field values at the nodes appear in the
ElectricField property. Electric flux density at the nodes appear in the ElectricFluxDensity
property.
To interpolate the electric potential, electric field, and electric flux density to a custom grid, such as
the one specified by meshgrid, use the interpolateElectricPotential,
interpolateElectricField, and interpolateElectricFlux functions.
Creation
Solve an electrostatic problem using the solve function. This function returns a solution as an
ElectrostaticResults object.
Properties
ElectricPotential — Electric potential values at nodes
vector
Electric field values at nodes, returned as an FEStruct object. The properties of this object contain
the components of the electric field at nodes.
Electric flux density values at nodes, returned as an FEStruct object. The properties of this object
contain the components of electric flux density at nodes.
5-340
ElectrostaticResults
Finite element mesh, returned as an FEMesh object. For details, see FEMesh.
Object Functions
interpolateElectricPotential Interpolate electric potential in electrostatic or DC conduction result at
arbitrary spatial locations
interpolateElectricField Interpolate electric field in electrostatic or DC conduction result at
arbitrary spatial locations
interpolateElectricFlux Interpolate electric flux density in electrostatic result at arbitrary
spatial locations
Examples
Solve an electromagnetic problem and find the electric potential and field distribution for a 2-D
geometry representing a plate with a hole.
emagmodel = createpde(electromagnetic="electrostatic");
importGeometry(emagmodel,"PlateHolePlanar.stl");
pdegplot(emagmodel,EdgeLabels="on")
5-341
5 Functions
emagmodel.VacuumPermittivity = 8.8541878128E-12;
electromagneticProperties(emagmodel,RelativePermittivity=1);
Apply the voltage boundary conditions on the edges framing the rectangle and the circle.
electromagneticBC(emagmodel,Voltage=0,Edge=1:4);
electromagneticBC(emagmodel,Voltage=1000,Edge=5);
electromagneticSource(emagmodel,ChargeDensity=5E-9);
generateMesh(emagmodel);
R = solve(emagmodel)
R =
ElectrostaticResults with properties:
5-342
ElectrostaticResults
Solve an electromagnetic problem and find the electric potential and field distribution for a 3-D
geometry representing a plate with a hole.
5-343
5 Functions
emagmodel.VacuumPermittivity = 8.8541878128E-12;
electromagneticProperties(emagmodel,RelativePermittivity=1);
electromagneticSource(emagmodel,ChargeDensity=5E-9);
Apply the voltage boundary conditions on the side faces and the face bordering the hole.
electromagneticBC(emagmodel,Voltage=0,Face=3:6);
electromagneticBC(emagmodel,Voltage=1000,Face=7);
generateMesh(emagmodel);
R = solve(emagmodel)
R =
ElectrostaticResults with properties:
5-344
ElectrostaticResults
figure
pdeplot3D(R.Mesh,ColorMapData=R.ElectricPotential)
pdeplot3D(R.Mesh,FlowData=[R.ElectricField.Ex ...
R.ElectricField.Ey ...
R.ElectricField.Ez])
5-345
5 Functions
Version History
Introduced in R2021a
See Also
Functions
solve | interpolateElectricPotential | interpolateElectricField |
interpolateElectricFlux
Objects
femodel | ElectromagneticModel | MagnetostaticResults | HarmonicResults |
ConductionResults
5-346
MagnetostaticResults
MagnetostaticResults
Magnetostatic solution and derived quantities
Description
A MagnetostaticResults object contains the magnetic potential, magnetic field, magnetic flux
density, and mesh values in a form convenient for plotting and postprocessing.
The magnetic potential, magnetic field, and magnetic flux density are calculated at the nodes of the
triangular or tetrahedral mesh generated by generateMesh. Magnetic potential values at the nodes
appear in the MagneticPotential property. Magnetic field values at the nodes appear in the
MagneticField property. Magnetic flux density values at the nodes appear in the
MagneticFluxDensity property.
To interpolate the magnetic potential, magnetic field, and magnetic flux density to a custom grid,
such as the one specified by meshgrid, use the interpolateMagneticPotential,
interpolateMagneticField, and interpolateMagneticFlux functions.
Creation
Solve a magnetostatic problem using the solve function. This function returns a solution as a
MagnetostaticResults object.
Properties
MagneticPotential — Magnetic potential values at nodes
vector | FEStruct object
Magnetic potential values at nodes, returned as a vector for a 2-D problem or an FEStruct object for
a 3-D problem. The properties of this object contain the components of the magnetic potential at
nodes.
Magnetic field values at nodes, returned as an FEStruct object. The properties of this object contain
the components of the magnetic field at nodes.
Magnetic flux density values at nodes, returned as an FEStruct object. The properties of this object
contain the components of the magnetic flux density at nodes.
5-347
5 Functions
Finite element mesh, returned as an FEMesh object. For details, see FEMesh. For a 3-D model, the
mesh must be linear.
Object Functions
interpolateMagneticPotential Interpolate magnetic potential in magnetostatic result at arbitrary
spatial locations
interpolateMagneticField Interpolate magnetic field in magnetostatic result at arbitrary spatial
locations
interpolateMagneticFlux Interpolate magnetic flux density in magnetostatic result at arbitrary
spatial locations
Examples
Solve a 2-D electromagnetic problem on a geometry representing a plate with a hole in its center. Plot
the resulting magnetic potential and field distribution.
emagmodel = createpde("electromagnetic","magnetostatic");
importGeometry(emagmodel,"PlateHolePlanar.stl");
pdegplot(emagmodel,"EdgeLabels","on")
5-348
MagnetostaticResults
emagmodel.VacuumPermeability = 1.2566370614e-6;
electromagneticProperties(emagmodel,"RelativePermeability",5000);
Apply the magnetic potential boundary conditions on the edges framing the rectangle and the circle.
electromagneticBC(emagmodel,"MagneticPotential",0,"Edge",1:4);
electromagneticBC(emagmodel,"MagneticPotential",0.01,"Edge",5);
electromagneticSource(emagmodel,"CurrentDensity",0.5);
generateMesh(emagmodel);
R = solve(emagmodel)
R =
MagnetostaticResults with properties:
5-349
5 Functions
Solve a 3-D electromagnetic problem on a geometry representing a plate with a hole in its center. Plot
the resulting magnetic potential and field distribution.
5-350
MagnetostaticResults
emagmodel.VacuumPermeability = 1.2566370614e-6;
electromagneticProperties(emagmodel,"RelativePermeability",5000);
Apply the magnetic potential boundary conditions on the side faces and the face bordering the hole.
electromagneticBC(emagmodel,"MagneticPotential",[0;0;0],"Face",3:6);
electromagneticBC(emagmodel,"MagneticPotential",[0;0;0.01],"Face",7);
electromagneticSource(emagmodel,"CurrentDensity",[0;0;0.5]);
generateMesh(emagmodel);
R = solve(emagmodel)
R =
MagnetostaticResults with properties:
5-351
5 Functions
pdeplot3D(emagmodel,"ColormapData",R.MagneticPotential.Az)
pdeplot3D(emagmodel,"FlowData",[R.MagneticField.Hx ...
R.MagneticField.Hy ...
R.MagneticField.Hz])
5-352
MagnetostaticResults
Use a solution obtained by performing a DC conduction analysis to specify current density for a
magnetostatic model.
emagmodel = createpde("electromagnetic","conduction");
gm = importGeometry(emagmodel,"PlateHoleSolid.stl");
pdegplot(gm,"FaceLabels","on","FaceAlpha",0.3)
5-353
5 Functions
Apply the voltage boundary conditions on the left, right, top, and bottom faces of the plate.
electromagneticBC(emagmodel,"Voltage",0,"Face",3:6);
Specify the surface current density on the face bordering the hole.
electromagneticBC(emagmodel,"SurfaceCurrentDensity",100,"Face",7);
This model already has a quadratic mesh that you generated for the DC conduction analysis. For a 3-
D magnetostatic model, the mesh must be linear. Generate a new linear mesh. The generateMesh
function creates a linear mesh by default if the model is 3-D and magnetostatic.
generateMesh(emagmodel);
5-354
MagnetostaticResults
emagmodel.VacuumPermeability = 1.2566370614e-6;
electromagneticProperties(emagmodel,"RelativePermeability",5000);
Apply the magnetic potential boundary conditions on the side faces and the face bordering the hole.
electromagneticBC(emagmodel,"MagneticPotential",[0;0;0],"Face",3:6);
electromagneticBC(emagmodel,"MagneticPotential",[0;0;0.01],"Face",7);
Specify the current density for the entire geometry using the DC conduction solution.
electromagneticSource(emagmodel,"CurrentDensity",R);
Rmagnetostatic = solve(emagmodel);
pdeplot3D(emagmodel,"ColormapData",Rmagnetostatic.MagneticPotential.Ax)
pdeplot3D(emagmodel,"ColormapData",Rmagnetostatic.MagneticPotential.Az)
5-355
5 Functions
Solve a magnetostatic model of a copper square with a permanent neodymium magnet in its center.
L = 0.8;
r = 0.25;
sq = [3 4 -L L L -L -L -L L L]';
circ = [1 0 0 r 0 0 0 0 0 0]';
gd = [sq,circ];
sf = "sq + circ";
ns = char('sq','circ');
ns = ns';
g = decsg(gd,sf,ns);
pdegplot(g,"FaceLabels","on","EdgeLabels","on")
5-356
MagnetostaticResults
emagmodel = createpde("electromagnetic","magnetostatic");
geometryFromEdges(emagmodel,g);
emagmodel.VacuumPermeability = 1.2566370614e-6;
electromagneticProperties(emagmodel,"Face",1, ...
"RelativePermeability",1);
electromagneticProperties(emagmodel,"Face",2, ...
"RelativePermeability",1.05);
M = 1e6;
Specify magnetization on the circular face in the positive x-direction. Magnetization for a 2-D model
is a column vector of two elements.
dir = [1;0];
electromagneticSource(emagmodel,"Face",2,"Magnetization",M*dir);
5-357
5 Functions
Apply the magnetic potential boundary conditions on the edges framing the square.
electromagneticBC(emagmodel,"Edge",1:4,"MagneticPotential",0);
Generate the mesh with finer meshing near the edges of the circle.
generateMesh(emagmodel,"Hedge",{5:8,0.007});
figure
pdemesh(emagmodel)
Solve the model, and find the resulting magnetic fields B and H. Here, B = μH + μ0M, where μ is the
absolute magnetic permeability of the material, μ0 is the vacuum permeability, and M is the
magnetization.
R = solve(emagmodel);
Bmag = sqrt(R.MagneticFluxDensity.Bx.^2 + R.MagneticFluxDensity.By.^2);
Hmag = sqrt(R.MagneticField.Hx.^2 + R.MagneticField.Hy.^2);
figure
pdeplot(emagmodel,"XYData",Bmag, ...
"FlowData",[R.MagneticFluxDensity.Bx ...
R.MagneticFluxDensity.By])
5-358
MagnetostaticResults
figure
pdeplot(emagmodel,"XYData",Hmag, ...
"FlowData",[R.MagneticField.Hx R.MagneticField.Hy])
5-359
5 Functions
Version History
Introduced in R2021a
See Also
Functions
solve | interpolateMagneticPotential | interpolateMagneticField |
interpolateMagneticFlux
Objects
femodel | ElectromagneticModel | ElectrostaticResults | HarmonicResults |
ConductionResults
5-360
HarmonicResults
HarmonicResults
Harmonic electromagnetic solution
Description
A HarmonicResults object contains the electric or magnetic field, frequency, and mesh values in a
form convenient for plotting and postprocessing.
The electric or magnetic field values are calculated at the nodes of the triangular or tetrahedral mesh
generated by generateMesh. Electric field values at the nodes appear in the ElectricField
property. Magnetic field values at the nodes appear in the MagneticField property.
To interpolate the electric or magnetic field to a custom grid, such as the one specified by meshgrid,
use the interpolateHarmonicField function.
Creation
Solve a harmonic electromagnetic analysis problem using the solve function. This function returns a
solution as a HarmonicResults object.
Properties
ElectricField — Electric field values at nodes
FEStruct object
Electric field values at nodes, returned as an FEStruct object. The properties of this object contain
the components of the electric field at nodes.
Magnetic field values at nodes, returned as an FEStruct object. The properties of this object contain
the components of the magnetic field at nodes.
5-361
5 Functions
Finite element mesh, returned as an FEMesh object. For details, see FEMesh.
Object Functions
interpolateHarmonicField Interpolate electric or magnetic field in harmonic result at arbitrary
spatial locations
Examples
For an electromagnetic harmonic analysis problem, find the x- and y-components of the electric field.
Solve the problem on a domain consisting of a square with a circular hole.
emagmodel = createpde("electromagnetic","harmonic");
Define a circle in a square, place them in one matrix, and create a set formula that subtracts the
circle from the square.
SQ = [3,4,-5,-5,5,5,-5,5,5,-5]';
C = [1,0,0,1]';
C = [C;zeros(length(SQ) - length(C),1)];
gm = [SQ,C];
sf = 'SQ-C';
ns = char('SQ','C');
ns = ns';
g = decsg(gm,sf,ns);
Include the geometry in the model and plot the geometry with the edge labels.
geometryFromEdges(emagmodel,g);
pdegplot(emagmodel,"EdgeLabels","on")
xlim([-5.5 5.5])
ylim([-5.5 5.5])
5-362
HarmonicResults
emagmodel.VacuumPermittivity = 1;
emagmodel.VacuumPermeability = 1;
Specify the relative permittivity, relative permeability, and conductivity of the material.
electromagneticProperties(emagmodel,"RelativePermittivity",1, ...
"RelativePermeability",1, ...
"Conductivity",0);
Apply the absorbing boundary condition with a thickness of 2 on the edges of the square. Use the
default attenuation rate for the absorbing region.
electromagneticBC(emagmodel,"Edge",1:4, ...
"FarField","absorbing", ...
"Thickness",2);
E = @(location,state) [1;0]*exp(-1i*2*pi*location.y);
electromagneticBC(emagmodel,"Edge",5:8,"ElectricField",E);
Generate a mesh.
generateMesh(emagmodel,"Hmax",1/2^3);
5-363
5 Functions
result = solve(emagmodel,"Frequency",2*pi);
Plot the real part of the x-component of the resulting electric field.
figure
pdeplot(emagmodel,"XYData",real(result.ElectricField.Ex));
title("Real Part of x-Component of Electric Field")
Plot the real part of the y-component of the resulting electric field.
figure
pdeplot(emagmodel,"XYData",real(result.ElectricField.Ey));
title("Real Part of y-Component of Electric Field")
5-364
HarmonicResults
Version History
Introduced in R2022a
See Also
Functions
interpolateHarmonicField | solve
Objects
femodel | ElectromagneticModel | ElectrostaticResults | MagnetostaticResults |
ConductionResults
5-365
5 Functions
ConductionResults
DC conduction solution
Description
A ConductionResults object contains the electric potential, electric field, current density, and
mesh values in a form convenient for plotting and postprocessing.
The electric potential, electric field, and current density values are calculated at the nodes of the
triangular or tetrahedral mesh generated by generateMesh. Electric potential values at the nodes
appear in the ElectricPotential property. Electric field values at the nodes appear in the
ElectricField property. Current density values at the nodes appear in the CurrentDensity
property.
To interpolate the electric potential, electric field, and current density to a custom grid, such as the
one specified by meshgrid, use the interpolateElectricPotential,
interpolateElectricField, and interpolateCurrentDensity functions.
Creation
Solve a DC conduction problem using the solve function. This function returns a solution as a
ConductionResults object.
Properties
ElectricPotential — Electric potential values at nodes
vector
Electric field values at nodes, returned as an FEStruct object. The properties of this object contain
the components of the electric field at nodes.
Electric flux density values at nodes, returned as an FEStruct object. The properties of this object
contain the components of the electric flux density at nodes.
5-366
ConductionResults
Finite element mesh, returned as an FEMesh object. For details, see FEMesh.
Object Functions
interpolateElectricPotential Interpolate electric potential in electrostatic or DC conduction result at
arbitrary spatial locations
interpolateElectricField Interpolate electric field in electrostatic or DC conduction result at
arbitrary spatial locations
interpolateCurrentDensity Interpolate current density in DC conduction result at arbitrary spatial
locations
Examples
Solve a DC conduction problem on a geometry representing a 3-D plate with a hole in its center. Plot
the electric potential and the components of the current density.
emagmodel = createpde("electromagnetic","conduction");
gm = importGeometry(emagmodel,"PlateHoleSolid.stl");
pdegplot(gm,"FaceLabels","on","FaceAlpha",0.3)
5-367
5 Functions
electromagneticProperties(emagmodel,"Conductivity",6e4);
Apply the voltage boundary conditions on the left, right, top, and bottom faces of the plate.
electromagneticBC(emagmodel,"Voltage",0,"Face",3:6);
Specify the surface current density on the face bordering the hole.
electromagneticBC(emagmodel,"SurfaceCurrentDensity",100,"Face",7);
generateMesh(emagmodel);
R = solve(emagmodel)
R =
ConductionResults with properties:
5-368
ConductionResults
figure
pdeplot3D(emagmodel,"ColorMapData",R.ElectricPotential)
figure
pdeplot3D(emagmodel,"ColorMapData",R.CurrentDensity.Jx)
title("x-Component of Current Density")
5-369
5 Functions
figure
pdeplot3D(emagmodel,"ColorMapData",R.CurrentDensity.Jy)
title("y-Component of Current Density")
5-370
ConductionResults
figure
pdeplot3D(emagmodel,"ColorMapData",R.CurrentDensity.Jz)
title("z-Component of Current Density")
5-371
5 Functions
Use a solution obtained by performing a DC conduction analysis to specify current density for a
magnetostatic model.
emagmodel = createpde("electromagnetic","conduction");
gm = importGeometry(emagmodel,"PlateHoleSolid.stl");
pdegplot(gm,"FaceLabels","on","FaceAlpha",0.3)
5-372
ConductionResults
Apply the voltage boundary conditions on the left, right, top, and bottom faces of the plate.
electromagneticBC(emagmodel,"Voltage",0,"Face",3:6);
Specify the surface current density on the face bordering the hole.
electromagneticBC(emagmodel,"SurfaceCurrentDensity",100,"Face",7);
This model already has a quadratic mesh that you generated for the DC conduction analysis. For a 3-
D magnetostatic model, the mesh must be linear. Generate a new linear mesh. The generateMesh
function creates a linear mesh by default if the model is 3-D and magnetostatic.
generateMesh(emagmodel);
5-373
5 Functions
emagmodel.VacuumPermeability = 1.2566370614e-6;
electromagneticProperties(emagmodel,"RelativePermeability",5000);
Apply the magnetic potential boundary conditions on the side faces and the face bordering the hole.
electromagneticBC(emagmodel,"MagneticPotential",[0;0;0],"Face",3:6);
electromagneticBC(emagmodel,"MagneticPotential",[0;0;0.01],"Face",7);
Specify the current density for the entire geometry using the DC conduction solution.
electromagneticSource(emagmodel,"CurrentDensity",R);
Rmagnetostatic = solve(emagmodel);
pdeplot3D(emagmodel,"ColormapData",Rmagnetostatic.MagneticPotential.Ax)
pdeplot3D(emagmodel,"ColormapData",Rmagnetostatic.MagneticPotential.Az)
5-374
ConductionResults
Version History
Introduced in R2022b
See Also
Functions
solve | interpolateElectricPotential | interpolateElectricField |
interpolateCurrentDensity
Objects
femodel | ElectromagneticModel | ElectrostaticResults | MagnetostaticResults |
HarmonicResults
5-375
5 Functions
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.
uOut = evaluate(F,x,y,z) returns the interpolated values from the interpolant F at the points
[x(k),y(k),z(k)], for k from 1 through numel(x). This syntax applies to 3-D geometry.
Examples
This example shows how to interpolate a solution to a scalar problem using a pOut matrix of values.
Solve the equation −Δu = 1 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
model = createpde;
gm = geometryFromEdges(model,g);
% Zero Dirichlet conditions
applyBoundaryCondition(model,"dirichlet", ...
"Edge",(1:gm.NumEdges), ...
"u",0);
[p,e,t] = initmesh(gm);
c = 1;
5-376
evaluate
a = 0;
f = 1;
u = assempde(model,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 −Δu = 1 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
model = createpde;
gm = geometryFromEdges(model,g);
% Zero Dirichlet conditions
applyBoundaryCondition(model,"dirichlet", ...
"Edge",(1:gm.NumEdges), ...
"u",0);
[p,e,t] = initmesh(gm);
c = 1;
a = 0;
f = 1;
u = assempde(model,p,e,t,c,a,f); % solve the PDE
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.
5-377
5 Functions
Solve the system of equations −Δu = f with Dirichlet boundary conditions on the unit disk, where
T
xy
f = sin(x) + cos(y), cosh(xy), .
1 + x2 + y2
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-378
evaluate
∂u
− Δu = 1
∂t
on the unit disk with zero Dirichlet conditions and zero initial conditions. Solve at five times from 0 to
1.
5-379
5 Functions
f = 1;
d = 1;
tlist = 0:1/4:1;
u = parabolic(0,tlist,model,p,e,t,c,a,f,d);
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
Use the built-in geometry functions to create an L-shaped region with zero Dirichlet boundary
conditions. Solve an elliptic PDE with coefficients c = 1, a = 0, f = 1, with zero Dirichlet boundary
conditions.
Create an Interpolant
F = pdeInterpolant(p,t,u);
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.
5-380
evaluate
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
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
Query point component, specified as a vector or array. evaluate interpolates at either 2-D points
[x(k),y(k)] or at 3-D points [x(k),y(k),z(k)]. The x and y, and z arrays must contain the
same number of entries.
evaluate transforms query point components to the linear index representation, such as x(:).
Example: x = -1:0.2:3
Data Types: double
Query point component, specified as a vector or array. evaluate interpolates at either 2-D points
[x(k),y(k)] or at 3-D points [x(k),y(k),z(k)]. The x and y, and z arrays must contain the
same number of entries.
evaluate transforms query point components to the linear index representation, such as y(:).
Example: y = -1:0.2:3
Data Types: double
5-381
5 Functions
Query point component, specified as a vector or array. evaluate interpolates at either 2-D points
[x(k),y(k)] or at 3-D points [x(k),y(k),z(k)]. The x and y, and z arrays must contain the
same number of entries.
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.
More About
Element
For 2-D problems, an element is a triangle in the model.Mesh.Element property. If the triangle
represents a linear element, it has nodes only at the triangle corners. If the triangle represents a
quadratic element, then it has nodes at the triangle corners and edge centers.
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.
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.
5-382
evaluate
Version History
Introduced in R2014b
See Also
pdeInterpolant
Topics
“Mesh Data” on page 2-184
5-383
5 Functions
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.
[ ___ ] = 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.
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.
5-384
evaluateCGradient
second dimension represents equation indices. For a single time-dependent PDE, the second
dimension represents time-steps. The third dimension represents time-step indices for a system of
time-dependent PDEs.
Examples
Solve the problem −Δu = 1 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.
model = createpde;
geometryFromEdges(model,@lshapeg);
pdegplot(model,"FaceLabels","on")
5-385
5 Functions
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);
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-386
evaluateCGradient
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")
N = 3;
model = createpde(N);
5-387
5 Functions
importGeometry(model,"SquareBeam.stl");
pdegplot(model,"FaceLabels","on")
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]);
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);
5-388
evaluateCGradient
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.
[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-389
5 Functions
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-390
evaluateCGradient
figure
pdegplot(model,"FaceLabels","on")
view(-134,-32)
title("Bracket with Face Labels, Rear View")
5-391
5 Functions
applyBoundaryCondition(model,"dirichlet","Face",4,"u",[0,0,0]);
distributedLoad = 1e4; % Applied load in Pascals
applyBoundaryCondition(model,"neumann","Face",8, ...
"g",[0,0,-distributedLoad]);
result = solvepde(model);
Create a grid. For this grid, compute the stress tensor, which is the product of c-coefficient and
gradients of displacement.
5-392
evaluateCGradient
v = linspace(0,0.2,21);
[xq,yq,zq] = meshgrid(v);
[cgradx,cgrady,cgradz] = evaluateCGradient(result);
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-393
5 Functions
Solve a 2-D transient heat transfer problem on a square domain and compute heat flow across
convective boundary.
5-394
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-395
5 Functions
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.
numberOfPDE = 1;
model = createpde(numberOfPDE);
geometryFromEdges(model,dl);
pdegplot(model,"EdgeLabels","on","FaceLabels","on")
xlim([-1.5,4.5])
5-396
evaluateCGradient
ylim([-0.5,3.5])
axis equal
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);
5-397
5 Functions
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 c ⊗ ∇u. 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)], ...
"ColorMap","hot")
5-398
evaluateCGradient
Input Arguments
results — PDE solution
StationaryResults object | TimeDependentResults object
x-coordinate query points, specified as a real array. evaluateCGradient evaluates the tensor
product of c-coefficient and gradients of the PDE solution at either the 2-D coordinate points
[xq(i),yq(i)] or at the 3-D coordinate points [xq(i),yq(i),zq(i)]. So xq, yq, and (if present)
zq must have the same number of entries.
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
y-coordinate query points, specified as a real array. evaluateCGradient evaluates the tensor
product of c-coefficient and gradients of the PDE solution at either the 2-D coordinate points
[xq(i),yq(i)] or at the 3-D coordinate points [xq(i),yq(i),zq(i)]. So xq, yq, and (if present)
zq must have the same number of entries.
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
z-coordinate query points, specified as a real array. evaluateCGradient evaluates the tensor
product of c-coefficient and gradients of the PDE solution at the 3-D coordinate points
[xq(i),yq(i),zq(i)]. So xq, yq, and zq must have the same number of entries.
evaluateCGradient converts query points to column vectors xq(:), yq(:), and zq(:). For a
single stationary PDE, the result consists of column vectors of the same size. To ensure that the
5-399
5 Functions
dimensions of the returned x-, y-, and z-components are consistent with the dimensions of the
original query points, use reshape. For example, use cgradz = reshape(cgradz,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. 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
Equation indices, specified as a vector of positive integers. Each entry in iU specifies an equation
index.
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-429.
For query points that are outside the geometry, cgradx = NaN.
5-400
evaluateCGradient
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-429.
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 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-429.
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.
Version History
Introduced in R2016b
See Also
PDEModel | StationaryResults | TimeDependentResults | evaluateGradient |
interpolateSolution
Topics
“Deflection Analysis of Bracket” on page 3-74
“Dynamics of Damped Cantilever Beam” on page 3-20
“Heat Transfer Between Two Squares Made of Different Materials: PDE Modeler App” on page 3-234
5-401
5 Functions
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.
[ ___ ] = evaluateGradient( ___ ,iU) returns the interpolated values of the gradients for the
system of equations for equation indices (components) iU. When solving a system of elliptic PDEs,
specify iU after the input arguments in any of the previous syntaxes.
The first dimension of gradx, grady, and, in 3-D case, gradz corresponds to query points. The
second dimension corresponds to equation indices iU.
[ ___ ] = evaluateGradient( ___ ,iT) returns the interpolated values of the gradients for the
time-dependent equation or system of time-dependent equations at 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.
5-402
evaluateGradient
Create the solution to the problem −Δu = 1 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));
quiver(xq,yq,gradx,grady)
xlabel("x")
ylabel("y")
5-403
5 Functions
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-404
evaluateGradient
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")
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 −Δu = 1 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-405
5 Functions
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")
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-406
evaluateGradient
Evaluate gradients of the solution to a two-component elliptic system and plot the results.
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-134.
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);
5-407
5 Functions
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]);
5-408
evaluateGradient
figure
gradx1 = gradx(:,1);
grady1 = grady(:,1);
quiver(X(:),Y(:),gradx1,grady1)
title("Component 1")
axis equal
xlim([-0.3,0.3])
figure
gradx2 = gradx(:,2);
grady2 = grady(:,2);
quiver(X(:),Y(:),gradx2,grady2)
title("Component 2")
axis equal
xlim([-0.3,0.3])
5-409
5 Functions
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-410
evaluateGradient
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 “Linear Elasticity Equations” on page 3-194.
E = 200e9;
nu = 0.3;
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);
5-411
5 Functions
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")
ylabel("grady")
ylim([-5e-6, 20e-6])
5-412
evaluateGradient
Input Arguments
results — PDE solution
StationaryResults object | TimeDependentResults object
x-coordinate query points, specified as a real array. evaluateGradient evaluates the gradients of
the solution at the 2-D coordinate points [xq(i),yq(i)] or at the 3-D coordinate points
[xq(i),yq(i),zq(i)]. So xq, yq, and (if present) zq must have the same number of entries.
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(:).
5-413
5 Functions
y-coordinate query points, specified as a real array. evaluateGradient evaluates the gradients of
the solution at the 2-D coordinate points [xq(i),yq(i)] or at the 3-D coordinate points
[xq(i),yq(i),zq(i)]. So xq, yq, and (if present) zq must have the same number of entries.
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
z-coordinate query points, specified as a real array. evaluateGradient evaluates the gradients of
the solution at the 3-D coordinate points [xq(i),yq(i),zq(i)]. So xq, yq, and zq must have the
same number of entries.
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
Equation indices, specified as a vector of positive integers. Each entry in iU specifies an equation
index.
Example: iU = [1,5] specifies the indices for the first and fifth equations.
Data Types: double
5-414
evaluateGradient
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
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-429.
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-429.
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-429.
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.
Version History
Introduced in R2016a
See Also
PDEModel | StationaryResults | TimeDependentResults | interpolateSolution |
evaluateCGradient | quiver | quiver3 | contour
Topics
“Solution and Gradient Plots with pdeplot and pdeplot3D” on page 3-376
“3-D Solution and Gradient Plots with MATLAB Functions” on page 3-391
5-415
5 Functions
5-416
evaluateHeatFlux
evaluateHeatFlux
Package: pde
Syntax
[qx,qy] = evaluateHeatFlux(thermalresults)
[qx,qy,qz] = evaluateHeatFlux(thermalresults)
[qx,qy] = evaluateHeatFlux(thermalresults,xq,yq)
[qx,qy,qz] = evaluateHeatFlux(thermalresults,xq,yq,zq)
[ ___ ] = evaluateHeatFlux(thermalresults,querypoints)
Description
[qx,qy] = evaluateHeatFlux(thermalresults) returns the heat flux for a 2-D problem at the
nodal points of the triangular mesh.
[ ___ ] = 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 represents the node indices or corresponds to
query points. The second dimension corresponds to time steps iT.
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.
5-417
5 Functions
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 geometry represents an iron plate, the thermal conductivity is 79 . 5 W /(mK).
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);
generateMesh(thermalmodel);
results = solve(thermalmodel)
5-418
evaluateHeatFlux
results =
SteadyStateThermalResults with properties:
[qx,qy] = evaluateHeatFlux(results);
figure
pdeplot(thermalmodel,"FlowData",[qx qy])
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));
5-419
5 Functions
figure
quiver(X,Y,qx,qy)
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-420
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="steadystate");
importGeometry(thermalmodel,"Block.stl");
pdegplot(thermalmodel,FaceLabels="on",FaceAlpha=0.5)
title("Copper block, cm")
axis equal
5-421
5 Functions
Assuming that this is a copper block, the thermal conductivity of the block is approximately
4 W /(cmK).
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).
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:
5-422
evaluateHeatFlux
[qx,qy,qz] = evaluateHeatFlux(thermalresults);
figure
pdeplot3D(thermalresults.Mesh,FlowData=[qx qy qz])
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-423
5 Functions
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-424
evaluateHeatFlux
Solve a 2-D transient heat transfer problem on a square domain, and compute heat flow across a
convective boundary.
thermalmodel = createpde("thermal","transient");
g = @squareg;
geometryFromEdges(thermalmodel,g);
pdegplot(thermalmodel,"EdgeLabels","on")
xlim([-1.2 1.2])
ylim([-1.2 1.2])
axis equal
5-425
5 Functions
Assign the following thermal properties: thermal conductivity is 100 W /(m∘C), mass density is
7800 kg/m3, and specific heat is 500 J/(kg∘C).
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
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);
Create a grid specified by x and y coordinates, and evaluate heat flux to the grid.
5-426
evaluateHeatFlux
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
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.
thermalmodel = createpde("thermal","transient");
5-427
5 Functions
For the square region, assign the following thermal properties: thermal conductivity is 10 W /(m∘C),
mass density is 2 kg/m3, and specific heat is 0 . 1 J/(kg∘C).
thermalProperties(thermalmodel,"ThermalConductivity",10, ...
"MassDensity",2, ...
"SpecificHeat",0.1, ...
"Face",1);
For the diamond-shaped region, assign the following thermal properties: thermal conductivity is
2 W /(m∘C), mass density is 1 kg/m3, and specific heat is 0 . 1 J/(kg∘C).
5-428
evaluateHeatFlux
thermalProperties(thermalmodel,"ThermalConductivity",2, ...
"MassDensity",1, ...
"SpecificHeat",0.1, ...
"Face",2);
Assume that the diamond-shaped region is a heat source with the density of 4 W /m3.
internalHeatSource(thermalmodel,4,"Face",2);
∘
Apply a constant temperature of 0 C to the sides of the square plate.
thermalBC(thermalmodel,"Temperature",0,"Edge",[1 2 7 8]);
∘
Set the initial temperature to 0 C.
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-429
5 Functions
Input Arguments
thermalresults — Solution of thermal problem
SteadyStateThermalResults object | TransientThermalResults object
x-coordinate query points, specified as a real array. evaluateHeatFlux evaluates the heat flux at
the 2-D coordinate points [xq(i) yq(i)] or at the 3-D coordinate points [xq(i) yq(i) zq(i)].
So xq, yq, and (if present) zq must have the same number of entries.
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
5-430
evaluateHeatFlux
y-coordinate query points, specified as a real array. evaluateHeatFlux evaluates the heat flux at
the 2-D coordinate points [xq(i) yq(i)] or at the 3-D coordinate points [xq(i) yq(i) zq(i)].
So xq, yq, and (if present) zq must have the same number of entries.
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
z-coordinate query points, specified as a real array. evaluateHeatFlux evaluates the heat flux at
the 3-D coordinate points [xq(i) yq(i) zq(i)]. So xq, yq, and zq must have the same number of
entries.
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 qz = reshape(qz,size(zq)).
Data Types: double
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 or corresponds to the query point. The second array dimension represents the time step.
5-431
5 Functions
y-component of the heat flux, returned as an array. The first array dimension represents the node
index or corresponds to the query point. The second array dimension represents the time step.
z-component of the heat flux, returned as an array. The first array dimension represents the node
index or corresponds to the query point. The second array dimension represents the time step.
Version History
Introduced in R2017a
See Also
ThermalModel | SteadyStateThermalResults | TransientThermalResults |
evaluateHeatRate | evaluateTemperatureGradient | interpolateTemperature
5-432
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-433
5 Functions
thermalProperties(thermalmodel,"ThermalConductivity",80);
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");
thermalresults = solve(thermalmodel);
Qn = evaluateHeatRate(thermalresults,"Face",3)
Qn = 4.0000e+04
5-434
evaluateHeatRate
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);
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-435
5 Functions
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)
5-436
evaluateHeatRate
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.
Version History
Introduced in R2017a
See Also
ThermalModel | SteadyStateThermalResults | TransientThermalResults |
evaluateHeatFlux | evaluateTemperatureGradient | interpolateTemperature
5-437
5 Functions
evaluatePrincipalStrain
Package: pde
Syntax
pStrain = evaluatePrincipalStrain(structuralresults)
Description
pStrain = evaluatePrincipalStrain(structuralresults) evaluates principal strain at
nodal locations using strain values from structuralresults. For transient and frequency response
structural models, evaluatePrincipalStrain evaluates principal strain for all time- or frequency-
steps, respectively.
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-438
evaluatePrincipalStrain
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]);
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel)
structuralresults =
StaticStructuralResults with properties:
5-439
5 Functions
pStrain = evaluatePrincipalStrain(structuralresults);
Use the principal strain to evaluate the first and second invariant of strain.
Evaluate the principal strain and octahedral shear strain in a beam under a harmonic excitation.
structuralmodel = createpde("structural","transient-solid");
5-440
evaluatePrincipalStrain
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 the 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);
Generate a mesh.
generateMesh(structuralmodel,"Hmax",0.01);
structuralIC(structuralmodel,"Displacement",[0;0;0],"Velocity",[0;0;0]);
5-441
5 Functions
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-442
evaluatePrincipalStrain
Input Arguments
structuralresults — Solution of structural analysis problem
StaticStructuralResults object | TransientStructuralResults object |
FrequencyStructuralResults object
Output Arguments
pStrain — Principal strain at nodal locations
structure array
Version History
Introduced in R2017b
For transient structural models, evaluatePrincipalStrain evaluates principal strain for all time-
steps.
See Also
StructuralModel | StaticStructuralResults | interpolateDisplacement |
interpolateStress | interpolateStrain | interpolateVonMisesStress |
evaluateReaction | evaluatePrincipalStress
5-443
5 Functions
evaluatePrincipalStress
Package: pde
Syntax
pStress = evaluatePrincipalStress(structuralresults)
Description
pStress = evaluatePrincipalStress(structuralresults) evaluates principal stress at
nodal locations using stress values from structuralresults. For transient and frequency response
structural models, evaluatePrincipalStress evaluates principal stress for all time- and
frequency-steps, respectively.
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-444
evaluatePrincipalStress
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]);
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel)
structuralresults =
StaticStructuralResults with properties:
5-445
5 Functions
pStress = evaluatePrincipalStress(structuralresults);
Use the principal stress to evaluate the first and second invariant of stress.
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-446
evaluatePrincipalStress
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 the 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);
Generate a mesh.
generateMesh(structuralmodel,"Hmax",0.01);
structuralIC(structuralmodel,"Displacement",[0;0;0],"Velocity",[0;0;0]);
5-447
5 Functions
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-448
evaluatePrincipalStress
Input Arguments
structuralresults — Solution of structural analysis problem
StaticStructuralResults object | TransientStructuralResults object |
FrequencyStructuralResults object
Output Arguments
pStress — Principal stress at nodal locations
structure array
Version History
Introduced in R2017b
For transient structural models, evaluatePrincipalStress evaluates principal stress for all time-
steps.
See Also
StructuralModel | StaticStructuralResults | interpolateDisplacement |
interpolateStress | interpolateStrain | interpolateVonMisesStress |
evaluateReaction | evaluatePrincipalStrain
5-449
5 Functions
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 transient and frequency response structural models,
evaluateReaction evaluates reaction forces for all time- and frequency-steps, respectively.
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-450
evaluateReaction
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'
Boundary Loads
Force: []
5-451
5 Functions
SurfaceTraction: []
Pressure: []
TranslationalStiffness: []
Label: []
structuralBoundaryLoad(structuralmodel,"Face",2,"Pressure",100)
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 2
Vectorized: 'off'
Boundary Loads
Force: []
SurfaceTraction: []
Pressure: 100
TranslationalStiffness: []
Label: []
Evaluate the reaction forces at the fixed end of a beam subject to harmonic excitation.
5-452
evaluateReaction
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 the 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);
Generate a mesh.
generateMesh(structuralmodel,"Hmax",0.01);
structuralIC(structuralmodel,"Displacement",[0;0;0],"Velocity",[0;0;0]);
5-453
5 Functions
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 |
FrequencyStructuralResults 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
Geometric region ID, specified as a vector of positive integers. Find the region IDs by using
pdegplot.
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.
5-454
evaluateReaction
Version History
Introduced in R2017b
For frequency response structural models, evaluateReaction evaluates reaction forces for all
frequency-steps.
For transient structural models, evaluateReaction evaluates reaction forces for all time-steps.
See Also
StructuralModel | StaticStructuralResults | interpolateDisplacement |
interpolateStress | interpolateStrain | interpolateVonMisesStress |
evaluatePrincipalStress | evaluatePrincipalStrain
5-455
5 Functions
evaluateStrain
Package: pde
Syntax
nodalStrain = evaluateStrain(structuralresults)
Description
nodalStrain = evaluateStrain(structuralresults) evaluates strain at nodal locations for
all time- or frequency-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-456
evaluateStrain
Specify Young's modulus, Poisson's ratio, and the 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);
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);
5-457
5 Functions
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")
Input Arguments
structuralresults — Solution of dynamic structural analysis problem
TransientStructuralResults object | FrequencyStructuralResults object
Output Arguments
nodalStrain — Strain at nodes
FEStruct object
5-458
evaluateStrain
Strain at the nodes, returned as an FEStruct object with the properties representing the
components of strain tensor at nodal locations. Properties of an FEStruct object are read-only.
Version History
Introduced in R2018a
See Also
StructuralModel | TransientStructuralResults | interpolateDisplacement |
interpolateVelocity | interpolateAcceleration | interpolateStress |
interpolateStrain | interpolateVonMisesStress | evaluateStress |
evaluateVonMisesStress | evaluateReaction | evaluatePrincipalStress |
evaluatePrincipalStrain
5-459
5 Functions
evaluateStress
Package: pde
Syntax
nodalStress = evaluateStress(structuralresults)
Description
nodalStress = evaluateStress(structuralresults) evaluates stress at nodal locations for
all time- or frequency-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-460
evaluateStress
Specify Young's modulus, Poisson's ratio, and the 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);
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);
5-461
5 Functions
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")
Input Arguments
structuralresults — Solution of dynamic structural analysis problem
TransientStructuralResults object | FrequencyStructuralResults object
Output Arguments
nodalStress — Stress at nodes
FEStruct object
5-462
evaluateStress
Stress at the nodes, returned as an FEStruct object with the properties representing the
components of a stress tensor at nodal locations. Properties of an FEStruct object are read-only.
Version History
Introduced in R2018a
See Also
StructuralModel | TransientStructuralResults | interpolateDisplacement |
interpolateVelocity | interpolateAcceleration | interpolateStress |
interpolateStrain | interpolateVonMisesStress | evaluateStrain |
evaluateVonMisesStress | evaluateReaction | evaluatePrincipalStress |
evaluatePrincipalStrain
5-463
5 Functions
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.
The first dimension of gradTx, gradTy, and, in 3-D case, gradTz corresponds to query points. The
second dimension corresponds to time-steps iT.
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')');
5-464
evaluateTemperatureGradient
geometryFromEdges(thermalmodel,g);
pdegplot(thermalmodel,"EdgeLabels","on")
xlim([-1.5 1.5])
axis equal
Assuming that this geometry represents an iron plate, the thermal conductivity is 79 . 5 W /(mK).
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:
5-465
5 Functions
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]);
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-466
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-467
5 Functions
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");
importGeometry(thermalmodel,"Block.stl");
pdegplot(thermalmodel,"FaceLabels","on","FaceAlpha",0.5)
title("Copper block, cm")
axis equal
5-468
evaluateTemperatureGradient
Assuming that this is a copper block, the thermal conductivity of the block is approximately
4 W /(cmK).
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.
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:
5-469
5 Functions
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.
Create a grid specified by x, y, and z coordinates, and evaluate temperature gradients to the grid.
[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")
ylabel("y")
zlabel("z")
Alternatively, you can specify the grid by using a matrix of query points.
5-470
evaluateTemperatureGradient
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")
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-471
5 Functions
g = @squareg;
geometryFromEdges(thermalmodel,g);
pdegplot(thermalmodel,"EdgeLabels","on")
xlim([-1.2 1.2])
ylim([-1.2 1.2])
axis equal
Assign the following thermal properties: thermal conductivity is 100 W /(m∘C), mass density is
7800 kg/m3, and specific heat is 500 J/(kg∘C).
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);
5-472
evaluateTemperatureGradient
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);
Define a line at convection boundary and compute temperature gradients across that line.
X = -1:0.1:1;
Y = ones(size(X));
Plot the interpolated gradient component gradTx along the x axis for the following values from the
time interval tlist.
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-473
5 Functions
Input Arguments
thermalresults — Solution of thermal problem
SteadyStateThermalResults object | TransientThermalResults object
evaluateTemperatureGradient converts query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns the temperature gradient 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 gradTx = reshape(gradTx,size(xq)).
Data Types: double
evaluateTemperatureGradient converts query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns the temperature gradient 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 gradTy = reshape(gradTy,size(yq)).
Data Types: double
evaluateTemperatureGradient converts query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns the temperature gradient 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 gradTz = reshape(gradTz,size(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. evaluateTemperatureGradient evaluates the temperature gradient at the coordinate
5-474
evaluateTemperatureGradient
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
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.
Version History
Introduced in R2017a
See Also
ThermalModel | SteadyStateThermalResults | TransientThermalResults |
evaluateHeatFlux | evaluateHeatRate | interpolateTemperature
5-475
5 Functions
evaluateVonMisesStress
Package: pde
Syntax
vmStress = evaluateVonMisesStress(structuralresults)
Description
vmStress = evaluateVonMisesStress(structuralresults) evaluates von Mises stress at
nodal locations for all time- or frequency-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-476
evaluateVonMisesStress
Specify Young's modulus, Poisson's ratio, and the 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);
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);
5-477
5 Functions
vmStress = evaluateVonMisesStress(structuralresults);
figure
pdeplot3D(structuralresults.Mesh,ColorMapData = vmStress(:,end))
title("von Mises Stress in the Beam for the Last Time-Step")
Input Arguments
structuralresults — Solution of dynamic structural analysis problem
TransientStructuralResults object | FrequencyStructuralResults object
Output Arguments
vmStress — Von Mises Stress at nodes
matrix
5-478
evaluateVonMisesStress
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 or frequency steps.
Version History
Introduced in R2018a
See Also
StructuralModel | TransientStructuralResults | interpolateDisplacement |
interpolateVelocity | interpolateAcceleration | interpolateStress |
interpolateStrain | interpolateVonMisesStress | evaluateStrain | evaluateStress |
evaluateReaction | evaluatePrincipalStress | evaluatePrincipalStrain
5-479
5 Functions
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, specified 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-184.
Data Types: double
Mesh elements, specified as an M-by-Ne matrix, where Ne is the number of elements in the mesh, and
M is:
Each column in Elements contains the indices of the nodes for that mesh element.
Data Types: double
Target maximum mesh element size, specified 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.
5-480
FEMesh Properties
Target minimum mesh element size, specified 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
Element polynomial order, specified as 'linear' or 'quadratic'. See Elements or “Mesh Data”
on page 2-184.
Data Types: char
Version History
Introduced in R2015a
See Also
generateMesh | meshToPet | PDEModel | findElements | findNodes | meshQuality | area |
volume
Topics
“Solve Problems Using PDEModel Objects” on page 2-3
“Finite Element Method Basics” on page 1-11
“Mesh Data” on page 2-184
5-481
5 Functions
extrude
Package: pde
Syntax
h = extrude(g,height)
h = extrude(g,FaceID,height)
Description
h = extrude(g,height) creates a 3-D discrete geometry by extruding a 2-D geometry along the z-
axis by the value of height. You can create a stacked multilayered 3-D discrete geometry by
specifying height as a vector of thicknesses of the layers.
All of the specified faces must be flat and have the same orientation. The extruded volumes must not
intersect with each other or with the existing geometry.
Examples
model = createpde;
g = importGeometry(model,"PlateHolePlanar.stl");
pdegplot(g,"FaceLabels","on")
5-482
extrude
Create a 3-D geometry by extruding the 2-D geometry along the z-axis by 5 units.
extrude(g,5)
ans =
DiscreteGeometry with properties:
NumCells: 1
NumFaces: 7
NumEdges: 15
NumVertices: 10
Vertices: [10x3 double]
pdegplot(g,"FaceLabels","on","FaceAlpha",0.5)
5-483
5 Functions
Create a stacked multilayered 3-D geometry by extruding a 2-D geometry along the z-axis.
model = createpde;
Import a geometry.
g = importGeometry(model,"PlateHolePlanar.stl")
g =
DiscreteGeometry with properties:
NumCells: 0
NumFaces: 1
NumEdges: 5
NumVertices: 5
Vertices: [5x3 double]
pdegplot(g,"FaceLabels","on")
5-484
extrude
Create a 3-D geometry consisting of three blocks with holes stacked on top of each other. The heights
of the blocks are 5, 10, and 20 units.
extrude(g,[5,10,20])
ans =
DiscreteGeometry with properties:
NumCells: 3
NumFaces: 19
NumEdges: 35
NumVertices: 20
Vertices: [20x3 double]
pdegplot(g,"CellLabels","on","FaceAlpha",0.5)
5-485
5 Functions
Extrude a 2-D geometry that has a vertex added by the addVertex function. The layers of the
extruded geometry all have a corresponding vertex, but there are no edges between these vertices.
model = createpde;
Import a geometry.
g = importGeometry(model,"PlateHolePlanar.stl");
pdegplot(g,"VertexLabels","on")
5-486
extrude
addVertex(g,"Coordinates",[10 12]);
pdegplot(g,"FaceLabels","on","VertexLabels","on")
5-487
5 Functions
Create a 3-D geometry consisting of three blocks with holes stacked on top of each other. The heights
of the blocks are 5, 10, and 20 units.
extrude(g,[5,10,20])
ans =
DiscreteGeometry with properties:
NumCells: 3
NumFaces: 19
NumEdges: 35
NumVertices: 24
Vertices: [24x3 double]
Plot the new geometry and display the vertex labels. The extrude function replicates the added
vertex V6 into three new vertices: V12, V18, and V24. It does not create edges between these
vertices.
pdegplot(g,"VertexLabels","on","FaceAlpha",0.5)
5-488
extrude
Extrude a 2-D geometry that has a face added by the addFace function.
model = createpde;
Import a geometry.
g = importGeometry(model,"PlateHolePlanar.stl");
Plot the geometry and display the face and edge labels.
pdegplot(g,"FaceLabels","on","EdgeLabels","on")
5-489
5 Functions
addFace(g,5)
ans =
DiscreteGeometry with properties:
NumCells: 0
NumFaces: 2
NumEdges: 5
NumVertices: 5
Vertices: [5x3 double]
pdegplot(g,"FaceLabels","on")
5-490
extrude
Create a 3-D geometry by extruding the 2-D geometry along the z-axis by 2 units.
extrude(g,2)
ans =
DiscreteGeometry with properties:
NumCells: 2
NumFaces: 9
NumEdges: 15
NumVertices: 10
Vertices: [10x3 double]
pdegplot(g,"CellLabels","on","FaceAlpha",0.5)
5-491
5 Functions
Import the geometry and plot it with the face and edge labels.
g = importGeometry("PlateHolePlanar.stl");
pdegplot(g,"FaceLabels","on","EdgeLabels","on")
5-492
extrude
Fill the hole in the center by adding a face. Plot the modified geometry.
addFace(g,5);
pdegplot(g,"FaceLabels","on")
5-493
5 Functions
Create a 3-D geometry by extruding the 2-D geometry along the z-axis by 2 units.
extrude(g,2);
Plot the new geometry with the cell and face labels.
pdegplot(g,"CellLabels","on","Facelabels","on","FaceAlpha",0.5)
5-494
extrude
extrude(g,4,5);
pdegplot(g,"CellLabels","on","FaceAlpha",0.5)
5-495
5 Functions
Now, call extrude again, and this time specify a vector of heights. The function extrudes all specified
faces by each of the specified heights, which creates multiple layers.
5-496
extrude
Input Arguments
g — Geometry
fegeometry object | DiscreteGeometry object | AnalyticGeometry object
Cell heights, specified as a positive real number or a vector of positive real numbers.
If height is a vector and g is a 2-D geometry, then height(i) specifies the height of the ith layer of
a multilayered (stacked) 3-D geometry. Each layer constitutes a new cell.
If g is a 3-D geometry, the function extrudes all specified faces into several layers, with height(i)
specifying the height of the ith layer.
Example: extrude(g,5.5)
5-497
5 Functions
Faces to extrude in 3-D geometry, specified as a positive real number or a vector of positive real
numbers. If height is a vector, then the function extrudes all specified faces into several layers,
same as it does for 2-D geometries.
Output Arguments
h — Resulting geometry
fegeometry object | handle
Tips
• After modifying a geometry, regenerate the mesh to ensure a proper mesh association with the
new geometry.
• If a 2-D geometry has new vertices added by using the addVertex function, extrude replicates
the new vertices on each new layer of the extruded 3-D geometry, but it does not connect these
vertices by edges.
• If g is an fegeometry or AnalyticGeometry object, and you want to replace it with the
modified geometry, assign the output to the original geometry, for example, g = extrude(g,20).
Version History
Introduced in R2020b
In addition to extruding 2-D geometries into 3-D geometries, the function now lets you extrude
specified faces of a 3-D geometry. The function extrudes specified faces along the direction normal to
the faces.
See Also
Functions
addVertex | addFace | pdegplot | importGeometry | generateMesh | mergeCells |
multicuboid | multicylinder | multisphere
5-498
extrude
Objects
fegeometry | DiscreteGeometry | AnalyticGeometry
5-499
5 Functions
faceEdges
Find edges belonging to specified faces
Syntax
EdgeID = faceEdges(g,RegionID)
EdgeID = faceEdges(g,RegionID,FilterType)
Description
EdgeID = faceEdges(g,RegionID) finds edges belonging to the faces with ID numbers listed in
RegionID.
Examples
gm = multicuboid(3,2,1)
gm =
DiscreteGeometry with properties:
NumCells: 1
NumFaces: 6
NumEdges: 12
NumVertices: 8
Vertices: [8x3 double]
pdegplot(gm,"FaceLabels","on","FaceAlpha",0.2)
5-500
faceEdges
edgeIDs = 1×8
1 2 3 4 5 6 7 8
figure
pdegplot(gm,"EdgeLabels","on","FaceAlpha",0.2)
5-501
5 Functions
Create a model and include this geometry. The geometry of the L-shaped membrane is described in
the file lshapeg.
model = createpde();
gm = geometryFromEdges(model,@lshapeg)
gm =
AnalyticGeometry with properties:
NumCells: 0
NumFaces: 3
NumEdges: 10
NumVertices: 8
Vertices: [8x2 double]
pdegplot(gm,"FaceLabels","on")
5-502
faceEdges
edgeIDs = 1×8
1 2 3 6 7 8 9 10
figure
pdegplot(gm,"EdgeLabels","on")
5-503
5 Functions
Find edges belonging to the side face of the inner cuboid in a geometry consisting of two nested
cuboids.
Create a geometry that consists of two nested cuboids of the same height.
gm =
DiscreteGeometry with properties:
NumCells: 2
NumFaces: 12
NumEdges: 24
NumVertices: 16
Vertices: [16x3 double]
pdegplot(gm,"FaceLabels","on","FaceAlpha",0.2)
5-504
faceEdges
Find all edges belonging to the side face of the inner cuboid.
edgeIDs = faceEdges(gm,6)
edgeIDs = 1×4
1 5 10 12
From all edges belonging to that face, return the edges belonging to only the internal faces. Internal
faces are faces shared between multiple cells.
edgeIDs = faceEdges(gm,6,"internal")
edgeIDs = 1×2
10 12
From all edges belonging to that face, return the edges belonging to the external faces.
edgeIDs = faceEdges(gm,6,"external")
edgeIDs = 1×2
1 5
5-505
5 Functions
pdegplot(gm,"EdgeLabels","on","FaceAlpha",0.2)
Input Arguments
g — Geometry
fegeometry object | DiscreteGeometry object | AnalyticGeometry object
RegionID — Face ID
positive number | vector of positive numbers
Face ID, specified as a positive number or a vector of positive numbers. Each number represents a
face ID.
• "internal" — Edges belonging to only internal faces. Internal faces are faces shared between
multiple cells.
5-506
faceEdges
• "external" — Edges belonging to only external faces. External faces are faces not shared
between multiple cells.
• "all" — All edges belonging to the specified cells.
Output Arguments
EdgeID — IDs of edges belonging to specified faces
positive number | vector of positive numbers
IDs of edges belonging to the specified faces, returned as a positive number or a vector of positive
numbers.
Version History
Introduced in R2021a
See Also
Functions
cellEdges | cellFaces | facesAttachedToEdges | nearestEdge | nearestFace
Objects
fegeometry | DiscreteGeometry | AnalyticGeometry
5-507
5 Functions
facesAttachedToEdges
Find faces attached to specified edges
Syntax
FaceID = facesAttachedToEdges(g,RegionID)
FaceID = facesAttachedToEdges(g,RegionID,FilterType)
Description
FaceID = facesAttachedToEdges(g,RegionID) finds faces attached to the edges with ID
numbers listed in RegionID.
Examples
gm = multicuboid(3,2,1)
gm =
DiscreteGeometry with properties:
NumCells: 1
NumFaces: 6
NumEdges: 12
NumVertices: 8
Vertices: [8x3 double]
pdegplot(gm,"EdgeLabels","on","FaceAlpha",0.2)
5-508
facesAttachedToEdges
faceIDs = 1×4
1 2 5 6
figure
pdegplot(gm,"FaceLabels","on","FaceAlpha",0.2)
5-509
5 Functions
Create a model and include this geometry. The geometry of the L-shaped membrane is described in
the file lshapeg.
model = createpde();
gm = geometryFromEdges(model,@lshapeg)
gm =
AnalyticGeometry with properties:
NumCells: 0
NumFaces: 3
NumEdges: 10
NumVertices: 8
Vertices: [8x2 double]
pdegplot(gm,"EdgeLabels","on")
5-510
facesAttachedToEdges
faceIDs = 1×2
1 2
figure
pdegplot(gm,"FaceLabels","on")
5-511
5 Functions
Find internal and external faces attached to the edges of the inner cuboid in a geometry consisting of
two nested cuboids.
Create a geometry that consists of two nested cuboids of the same height.
gm =
DiscreteGeometry with properties:
NumCells: 2
NumFaces: 12
NumEdges: 24
NumVertices: 16
Vertices: [16x3 double]
pdegplot(gm,"EdgeLabels","on","FaceAlpha",0.2)
5-512
facesAttachedToEdges
Find all faces attached to the top edges of the inner cuboid.
facesAttachedToEdges(gm,[5:8])
ans = 1×6
2 3 4 5 6 12
Find only the internal faces attached to the top edges of the inner cuboid. Internal faces are faces
shared between multiple cells.
facesAttachedToEdges(gm,[5:8],"internal")
ans = 1×4
3 4 5 6
Find only the external faces attached to the top edges of the inner cuboid.
facesAttachedToEdges(gm,[5:8],"external")
ans = 1×2
2 12
5-513
5 Functions
figure
pdegplot(gm,"FaceLabels","on","FaceAlpha",0.2)
Input Arguments
g — Geometry
fegeometry object | DiscreteGeometry object | AnalyticGeometry object
RegionID — Edge ID
positive number | vector of positive numbers
Edge ID, specified as a positive number or a vector of positive numbers. Each number represents an
edge ID.
• "internal" — Internal faces, that is, faces shared between multiple cells.
5-514
facesAttachedToEdges
• "external" — External faces, that is, faces not shared between multiple cells.
• "all" — All faces attached to the specified cells.
Output Arguments
FaceID — IDs of faces attached to specified edges
positive number | vector of positive numbers
IDs of faces attached to the specified edges, returned as a positive number or a vector of positive
numbers.
Version History
Introduced in R2021a
See Also
Functions
cellEdges | cellFaces | faceEdges | nearestEdge | nearestFace
Objects
fegeometry | DiscreteGeometry | AnalyticGeometry
5-515
5 Functions
findBodyLoad
Package: pde
Syntax
bl = findBodyLoad(bodyLoads,RegionType,RegionID)
Description
bl = findBodyLoad(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-516
findBodyLoad
Specify Young's modulus, Poisson's ratio, and the 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)
ans =
BodyLoadAssignment with properties:
RegionType: 'Cell'
RegionID: 1
GravitationalAcceleration: [3x1 double]
AngularVelocity: []
Temperature: []
TimeStep: []
Label: []
5-517
5 Functions
Input Arguments
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 by using
pdegplot.
Example: findBodyLoad(structuralmodel.BodyLoads,"Cell",1)
Data Types: double
Output Arguments
bl — Body load assignment
BodyLoadAssignment object
Version History
Introduced in R2017b
See Also
structuralBodyLoad
5-518
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-519
5 Functions
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.
applyBoundaryCondition(model,"neumann","Face",4:5,"g",[1;1;1]);
applyBoundaryCondition(model,"neumann","Face",6,"g",[-1;-1;-1]);
findBoundaryConditions(model.BoundaryConditions,"Face",1)
ans =
BoundaryCondition with properties:
BCType: 'dirichlet'
RegionType: 'Face'
RegionID: [1 2]
5-520
findBoundaryConditions
r: []
h: []
g: []
q: []
u: [0 0 0]
EquationIndex: []
Vectorized: 'off'
findBoundaryConditions(model.BoundaryConditions,"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(model.BoundaryConditions,"Face",5)
ans =
BoundaryCondition with properties:
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
5-521
5 Functions
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 by using
pdegplot with the "FaceLabels" (3-D) or "EdgeLabels" (2-D) value set to "on".
Example: findBoundaryConditions(model.BoundaryConditions,"Face",3)
Data Types: double
Output Arguments
BCregion — Boundary condition for a particular region
BoundaryCondition object
Version History
Introduced in R2016b
See Also
applyBoundaryCondition | BoundaryCondition
Topics
“Solve Problems Using PDEModel Objects” on page 2-3
5-522
findCoefficients
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-523
5 Functions
ca =
CoefficientAssignment with properties:
RegionType: 'face'
RegionID: [1 3]
m: 0
d: 0
c: 13
a: 0
f: 2
Input Arguments
coeffs — Model coefficients
EquationCoefficients property of a PDE model
5-524
findCoefficients
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
Output Arguments
CA — Coefficient assignment
CoefficientAssignment object
Version History
Introduced in R2016a
See Also
CoefficientAssignment | specifyCoefficients
Topics
“View, Edit, and Delete PDE Coefficients” on page 2-110
“Solve Problems Using PDEModel Objects” on page 2-3
5-525
5 Functions
findElectromagneticBC
Package: pde
Syntax
emBC = findElectromagneticBC(boundaryConditions,RegionType,RegionID)
Description
emBC = findElectromagneticBC(boundaryConditions,RegionType,RegionID) returns the
boundary conditions assigned to the specified region of the specified model.
Examples
emagmodel = createpde("electromagnetic","magnetostatic");
Include an L-shaped membrane geometry in the model and plot it with the face labels.
geometryFromEdges(emagmodel,@lshapeg);
pdegplot(emagmodel,"FaceLabels","on")
ylim([-1.1 1.1])
axis equal
5-526
findElectromagneticBC
ans =
ElectromagneticBCAssignment with properties:
RegionID: 1
RegionType: 'Edge'
Vectorized: 'off'
MagneticPotential: 1
emBC(2)
ans =
ElectromagneticBCAssignment with properties:
RegionID: 2
RegionType: 'Edge'
Vectorized: 'off'
MagneticPotential: 0
5-527
5 Functions
emagmodel = createpde("electromagnetic","electrostatic");
gm = importGeometry(emagmodel,"PlateHoleSolid.stl");
pdegplot(gm,"FaceLabels","on","FaceAlpha",0.3)
Apply the voltage boundary conditions on the side faces and the face bordering the hole.
electromagneticBC(emagmodel,"Voltage",0,"Face",3:6);
electromagneticBC(emagmodel,"Voltage",1000,"Face",7);
ans =
ElectromagneticBCAssignment with properties:
5-528
findElectromagneticBC
RegionID: [3 4 5 6]
RegionType: 'Face'
Vectorized: 'off'
Voltage: 0
emBC(2)
ans =
ElectromagneticBCAssignment with properties:
RegionID: [3 4 5 6]
RegionType: 'Face'
Vectorized: 'off'
Voltage: 0
emBC(3)
ans =
ElectromagneticBCAssignment with properties:
RegionID: 7
RegionType: 'Face'
Vectorized: 'off'
Voltage: 1000
Input Arguments
boundaryConditions — Boundary conditions of electromagnetic model
BoundaryConditions property
Geometric region type, specified as "Edge" for a 2-D model or "Face" for a 3-D model.
Data Types: char | string
RegionID — Region ID
vector of positive integers
Region ID, specified as a vector of positive integers. Find the edge or face IDs by using pdegplot
with the "EdgeLabels" or "FaceLabels" name-value argument set to "on".
Data Types: double
Output Arguments
emBC — Electromagnetic boundary condition assignment
ElectromagneticBCAssignment object
5-529
5 Functions
Version History
Introduced in R2021a
See Also
ElectromagneticModel | electromagneticBC | ElectromagneticBCAssignment Properties
5-530
findElectromagneticProperties
findElectromagneticProperties
Package: pde
Syntax
emProperties = findElectromagneticProperties(materialProperties,RegionType,
RegionID)
Description
emProperties = findElectromagneticProperties(materialProperties,RegionType,
RegionID) returns the electromagnetic material properties assigned to the specified region of the
specified model.
Examples
emagmodel = createpde("electromagnetic","electrostatic");
Include the L-shaped membrane geometry in the model and plot it with the face labels.
geometryFromEdges(emagmodel,@lshapeg);
pdegplot(emagmodel,"FaceLabels","on")
ylim([-1.1 1.1])
axis equal
5-531
5 Functions
emagmodel.VacuumPermittivity = 8.8541878128E-12;
electromagneticProperties(emagmodel,"RelativePermittivity",2.5, ...
"Face",1);
electromagneticProperties(emagmodel,"RelativePermittivity",2.25, ...
"Face",2);
electromagneticProperties(emagmodel,"RelativePermittivity",1, ...
"Face",3);
findElectromagneticProperties(emagmodel.MaterialProperties,"Face",1)
ans =
ElectromagneticMaterialAssignment with properties:
RegionType: 'Face'
RegionID: 1
RelativePermittivity: 2.5000
RelativePermeability: []
Conductivity: []
findElectromagneticProperties(emagmodel.MaterialProperties,"Face",2)
5-532
findElectromagneticProperties
ans =
ElectromagneticMaterialAssignment with properties:
RegionType: 'Face'
RegionID: 2
RelativePermittivity: 2.2500
RelativePermeability: []
Conductivity: []
findElectromagneticProperties(emagmodel.MaterialProperties,"Face",3)
ans =
ElectromagneticMaterialAssignment with properties:
RegionType: 'Face'
RegionID: 3
RelativePermittivity: 1
RelativePermeability: []
Conductivity: []
gm = multisphere([5 15]);
pdegplot(gm,"CellLabels","on","FaceAlpha",0.3)
5-533
5 Functions
emagmodel = createpde("electromagnetic","magnetostatic");
emagmodel.Geometry = gm;
emagmodel.VacuumPermeability = 1.2566370614E-6;
electromagneticProperties(emagmodel,"RelativePermittivity",2.5, ...
"Cell",1);
electromagneticProperties(emagmodel,"RelativePermittivity",2.25, ...
"Cell",2);
findElectromagneticProperties(emagmodel.MaterialProperties,"Cell",1)
ans =
ElectromagneticMaterialAssignment with properties:
RegionType: 'Cell'
RegionID: 1
5-534
findElectromagneticProperties
RelativePermittivity: 2.5000
RelativePermeability: []
Conductivity: []
findElectromagneticProperties(emagmodel.MaterialProperties,"Cell",2)
ans =
ElectromagneticMaterialAssignment with properties:
RegionType: 'Cell'
RegionID: 2
RelativePermittivity: 2.2500
RelativePermeability: []
Conductivity: []
Input Arguments
materialProperties — Material properties of electromagnetic model
MaterialProperties property
Geometric region type, specified as "Face" for a 2-D geometry or "Cell" for a 3-D geometry.
Data Types: char | string
RegionID — Region ID
vector of positive integers
Region ID, specified as a vector of positive integers. Find the face or cell IDs by using pdegplot with
the "FaceLabels" or "CellLabels" name-value argument set to "on".
Data Types: double
Output Arguments
emProperties — Material properties assignment
ElectromagneticMaterialAssignment object
Version History
Introduced in R2021a
5-535
5 Functions
See Also
electromagneticProperties | ElectromagneticModel | ElectromagneticMaterialAssignment
Properties
5-536
findElectromagneticSource
findElectromagneticSource
Package: pde
Syntax
emSource = findElectromagneticSource(sources,RegionType,RegionID)
Description
emSource = findElectromagneticSource(sources,RegionType,RegionID) returns the
change or current density emSource assigned to the specified region of the specified model.
Examples
emagmodel = createpde("electromagnetic","magnetostatic");
Include the L-shaped membrane geometry in the model and plot it with the face labels.
geometryFromEdges(emagmodel,@lshapeg);
pdegplot(emagmodel,"FaceLabels","on")
ylim([-1.1 1.1])
axis equal
5-537
5 Functions
electromagneticSource(emagmodel,"Face",1,"CurrentDensity",10);
electromagneticSource(emagmodel,"Face",2,"CurrentDensity",20);
electromagneticSource(emagmodel,"Face",3,"CurrentDensity",30);
findElectromagneticSource(emagmodel.Sources,"Face",1)
ans =
ElectromagneticSourceAssignment with properties:
RegionType: 'Face'
RegionID: 1
ChargeDensity: []
CurrentDensity: 10
Magnetization: []
findElectromagneticSource(emagmodel.Sources,"Face",2)
ans =
ElectromagneticSourceAssignment with properties:
RegionType: 'Face'
RegionID: 2
ChargeDensity: []
5-538
findElectromagneticSource
CurrentDensity: 20
Magnetization: []
findElectromagneticSource(emagmodel.Sources,"Face",3)
ans =
ElectromagneticSourceAssignment with properties:
RegionType: 'Face'
RegionID: 3
ChargeDensity: []
CurrentDensity: 30
Magnetization: []
5-539
5 Functions
emagmodel.Geometry = gm;
electromagneticSource(emagmodel,"Cell",1,"ChargeDensity",10);
findElectromagneticSource(emagmodel.Sources,"Cell",1)
ans =
ElectromagneticSourceAssignment with properties:
RegionType: 'Cell'
RegionID: 1
ChargeDensity: 10
CurrentDensity: []
Magnetization: []
findElectromagneticSource(emagmodel.Sources,"Cell",2)
ans =
RegionType
RegionID
ChargeDensity
CurrentDensity
Magnetization
Input Arguments
sources — Source in electromagnetic model
Sources property
Geometric region type, specified as "Face" for a 2-D model or "Cell" for a 3-D model.
Data Types: char | string
RegionID — Region ID
vector of positive integers
Region ID, specified as a vector of positive integers. Find the face or cell IDs by using pdegplot with
the "FaceLabels" or "CellLabels" name-value argument set to "on".
Data Types: double
5-540
findElectromagneticSource
Output Arguments
emSource — Electromagnetic source assignment
ElectromagneticSourceAssignment object
Version History
Introduced in R2021a
See Also
ElectromagneticModel | ElectromagneticSourceAssignment Properties |
electromagneticSource
5-541
5 Functions
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.
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-542
findElements
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-543
5 Functions
model = createpde;
importGeometry(model,"PlateHolePlanar.stl");
pdegplot(model)
5-544
findElements
Generate a mesh.
mesh = generateMesh(model,"Hmax",2,"Hmin",0.4)
mesh =
FEMesh with properties:
figure
pdemesh(model)
hold on
pdemesh(mesh.Nodes,mesh.Elements(:,Eb),"EdgeColor","green")
5-545
5 Functions
model = createpde;
importGeometry(model,"PlateHolePlanar.stl");
pdegplot(model)
5-546
findElements
Generate a mesh.
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-547
5 Functions
model = createpde;
importGeometry(model,"PlateHolePlanar.stl");
pdegplot(model)
5-548
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
En = 1×3
11 22 28
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-549
5 Functions
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 by using
pdegplot.
Example: findElements(mesh,"region","Face",1:3)
5-550
findElements
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.
Example: findElements(mesh,"box",[5 10],[10 20])
Data Types: double
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.
5-551
5 Functions
Output Arguments
elemIDs — Element IDs
positive integer | row vector of positive integers
Version History
Introduced in R2018a
See Also
findNodes | meshQuality | area | volume | FEMesh Properties
Topics
“Finite Element Method Basics” on page 1-11
5-552
findHeatSource
findHeatSource
Package: pde
Syntax
hsa = findHeatSource(heatSources,RegionType,RegionID)
Description
hsa = findHeatSource(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-553
5 Functions
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:
RegionType: 'face'
RegionID: 1
HeatSource: 10
Label: []
hsaFace2 =
HeatSourceAssignment with properties:
5-554
findHeatSource
RegionType: 'face'
RegionID: 2
HeatSource: 20
Label: []
hsaFace3 = hsa(2)
hsaFace3 =
HeatSourceAssignment with properties:
RegionType: 'face'
RegionID: 3
HeatSource: 30
Label: []
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
Vertices: [4x3 double]
thermalmodel = createpde("thermal");
thermalmodel.Geometry = gm;
pdegplot(thermalmodel,"CellLabels","on","FaceAlpha",0.5)
5-555
5 Functions
Specify that the cylinder C1 generates heat at 10 W /m3, the cylinder C2 generates heat at 20 W /m3,
and the cylinder C3 generates heat at 30 W /m3.
internalHeatSource(thermalmodel,10,"Cell",1);
internalHeatSource(thermalmodel,20,"Cell",2);
internalHeatSource(thermalmodel,30,"Cell",3);
hsaCell1 =
HeatSourceAssignment with properties:
RegionType: 'cell'
RegionID: 1
HeatSource: 10
Label: []
hsaCell2 =
HeatSourceAssignment with properties:
5-556
findHeatSource
RegionType: 'cell'
RegionID: 2
HeatSource: 20
Label: []
hsaCell3 = hsa(2)
hsaCell3 =
HeatSourceAssignment with properties:
RegionType: 'cell'
RegionID: 3
HeatSource: 30
Label: []
Input Arguments
heatSources — Internal heat source of the model
HeatSources property of a thermal model
Internal heat source of the model, specified as the HeatSources property of a ThermalModel
object.
Example: thermalmodel.HeatSources
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 by using the
pdegplot function.
Data Types: double
Output Arguments
hsa — Heat source assignment
HeatSourceAssignment object
Version History
Introduced in R2017a
5-557
5 Functions
See Also
HeatSourceAssignment | internalHeatSource
5-558
findInitialConditions
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-559
5 Functions
setInitialConditions(model,12,"Face",[1,2]);
setInitialConditions(model,13,"Face",[1,3]);
setInitialConditions(model,23,"Face",[2,3]);
ics = model.InitialConditions;
ic = findInitialConditions(ics,"Face",1)
ic =
GeometricInitialConditions with properties:
RegionType: 'face'
RegionID: [1 3]
InitialValue: 13
InitialDerivative: []
Input Arguments
ics — Model initial conditions
InitialConditions property of a PDE model
5-560
findInitialConditions
Model initial conditions, specified as the InitialConditions property of a PDE model. Initial
conditions can be complex numbers.
Example: model.InitialConditions
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
Version History
Introduced in R2016a
See Also
GeometricInitialConditions | NodalInitialConditions | setInitialConditions
Topics
“View, Edit, and Delete Initial Conditions” on page 2-122
“Solve Problems Using PDEModel Objects” on page 2-3
5-561
5 Functions
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
model = createpde;
Include the geometry of the built-in function lshapeg. Plot the geometry.
geometryFromEdges(model,@lshapeg);
pdegplot(model,"FaceLabels","on","EdgeLabels","on")
5-562
findNodes
Generate a mesh.
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-563
5 Functions
figure
pdemesh(model,"NodeLabels","on")
hold on
plot(mesh.Nodes(1,Ne57),mesh.Nodes(2,Ne57),"or","MarkerFaceColor","g")
5-564
findNodes
model = createpde;
importGeometry(model,"PlateHolePlanar.stl");
pdegplot(model)
5-565
5 Functions
Generate a mesh.
figure
pdemesh(model)
hold on
plot(mesh.Nodes(1,Nb),mesh.Nodes(2,Nb),"or","MarkerFaceColor","g")
5-566
findNodes
model = createpde;
importGeometry(model,"PlateHolePlanar.stl");
pdegplot(model)
5-567
5 Functions
Generate a mesh.
Find the nodes located within radius 2 from the center [5 10].
Nb = findNodes(mesh,"radius",[5 10],2);
figure
pdemesh(model)
hold on
plot(mesh.Nodes(1,Nb),mesh.Nodes(2,Nb),"or","MarkerFaceColor","g")
5-568
findNodes
Find the node closest to a specified point and highlight it on the mesh plot.
model = createpde;
importGeometry(model,"PlateHolePlanar.stl");
pdegplot(model)
5-569
5 Functions
Generate a mesh.
mesh = generateMesh(model,"Hmax",2,"Hmin",0.4);
N_ID = findNodes(mesh,"nearest",[15;10])
N_ID = 10
figure
pdemesh(model)
hold on
plot(mesh.Nodes(1,N_ID),mesh.Nodes(2,N_ID),"or","MarkerFaceColor","g")
5-570
findNodes
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 by using
pdegplot.
Example: findNodes(mesh,"region","Face",1:3)
5-571
5 Functions
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.
Example: findNodes(mesh,"box",[5 10],[10 20])
Data Types: double
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
Cartesian coordinates of query points, specified as a 2-by-N or 3-by-N matrix. These matrices contain
the coordinates of the query points. Here, N is the number of query points.
Example: findNodes(mesh,"nearest",[15 10.5 1; 12 10 1.2])
5-572
findNodes
Output Arguments
nodes — Node IDs
positive integer | row vector of positive integers
Version History
Introduced in R2018a
See Also
findElements | meshQuality | area | volume | FEMesh Properties
Topics
“Finite Element Method Basics” on page 1-11
5-573
5 Functions
findStructuralBC
Package: pde
Find structural boundary conditions and boundary loads assigned to geometric region
Syntax
sbca = findStructuralBC(boundaryConditions,RegionType,RegionID)
Description
sbca = findStructuralBC(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-574
findStructuralBC
structuralBoundaryLoad(structuralmodel,"Face",1, ...
"SurfaceTraction", ...
[100;10;300]);
structuralBoundaryLoad(structuralmodel,"Face",3,"Pressure",300);
structuralBC(structuralmodel,"Face",[5,6],"Constraint","free");
sbcaFace1 =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 1
Vectorized: 'off'
5-575
5 Functions
Displacement: []
XDisplacement: []
YDisplacement: []
ZDisplacement: []
Constraint: []
Radius: []
Reference: []
Label: []
Boundary Loads
Force: []
SurfaceTraction: [3x1 double]
Pressure: []
TranslationalStiffness: []
Label: []
sbcaFace3 = sbca(2)
sbcaFace3 =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 3
Vectorized: 'off'
Boundary Loads
Force: []
SurfaceTraction: []
Pressure: 300
TranslationalStiffness: []
Label: []
sbcaFace5 =
StructuralBC with properties:
RegionType: 'Face'
RegionID: [5 6]
Vectorized: 'off'
5-576
findStructuralBC
XDisplacement: []
YDisplacement: []
ZDisplacement: []
Constraint: "free"
Radius: []
Reference: []
Label: []
Boundary Loads
Force: []
SurfaceTraction: []
Pressure: []
TranslationalStiffness: []
Label: []
sbcaFace6 = sbca(2)
sbcaFace6 =
StructuralBC with properties:
RegionType: 'Face'
RegionID: [5 6]
Vectorized: 'off'
Boundary Loads
Force: []
SurfaceTraction: []
Pressure: []
TranslationalStiffness: []
Label: []
Input Arguments
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.
5-577
5 Functions
Example: findStructuralBC(structuralmodel.BoundaryConditions,"Edge",1)
Data Types: char | string
Geometric region ID, specified as a vector of positive integers. Find the region IDs by using
pdegplot.
Example: findStructuralBC(structuralmodel.BoundaryConditions,"Face",1:3)
Data Types: double
Output Arguments
sbca — Structural boundary conditions and boundary loads assignment
StructuralBC object
Structural boundary conditions and boundary loads assignment, returned as a StructuralBC object.
For details, see StructuralBC Properties.
Version History
Introduced in R2017b
See Also
structuralBC | structuralBoundaryLoad
5-578
findStructuralIC
findStructuralIC
Package: pde
Syntax
sica = findStructuralIC(initialConditions,RegionType,RegionID)
Description
sica = findStructuralIC(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-579
5 Functions
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:
RegionType: 'Cell'
RegionID: 1
InitialDisplacement: [3x1 double]
InitialVelocity: [3x1 double]
SICACell1.InitialDisplacement
ans = 3×1
5-580
findStructuralIC
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-581
5 Functions
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);
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)
5-582
findStructuralIC
ans =
NodalStructuralICs with properties:
sica =
NodalStructuralICs with properties:
Input Arguments
initialConditions — Initial conditions
InitialConditions property of a StructuralModel object
5-583
5 Functions
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 by using
pdegplot.
Data Types: double
Output Arguments
sica — Structural initial condition assignment
GeometricStructuralICs object | NodalStructuralICs object
Version History
Introduced in R2018a
See Also
structuralIC | GeometricStructuralICs Properties | NodalStructuralICs Properties |
StructuralModel
5-584
findStructuralProperties
findStructuralProperties
Package: pde
Syntax
smpa = findStructuralProperties(materialProperties,RegionType,RegionID)
Description
smpa = findStructuralProperties(materialProperties,RegionType,RegionID) returns
the structural material properties assigned to the specified region. Structural properties include
Young's modulus, Poisson's ratio, the mass density, the coefficient of thermal expansion, and the
hysteretic damping parameter 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-585
5 Functions
Assign different values of 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:
RegionType: 'Cell'
RegionID: 1
YoungsModulus: 2.0000e+11
PoissonsRatio: 0.3000
MassDensity: []
CTE: []
HystereticDamping: []
5-586
findStructuralProperties
mC2 =
StructuralMaterialAssignment with properties:
RegionType: 'Cell'
RegionID: 2
YoungsModulus: 2.1000e+11
PoissonsRatio: 0.3000
MassDensity: []
CTE: []
HystereticDamping: []
mC3 = mC23(2)
mC3 =
StructuralMaterialAssignment with properties:
RegionType: 'Cell'
RegionID: 3
YoungsModulus: 1.1000e+11
PoissonsRatio: 0.3500
MassDensity: []
CTE: []
HystereticDamping: []
Input Arguments
materialProperties — Material properties
MaterialProperties property of StructuralModel object
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 by using
pdegplot.
Example:
findStructuralProperties(structuralmodel.MaterialProperties,"Face",1:3)
5-587
5 Functions
Output Arguments
smpa — Material properties assignment
StructuralMaterialAssignment object
Version History
Introduced in R2017b
See Also
structuralProperties | StructuralMaterialAssignment Properties
5-588
findThermalBC
findThermalBC
Package: pde
Syntax
tbca = findThermalBC(boundaryConditions,RegionType,RegionID)
Description
tbca = findThermalBC(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-589
5 Functions
thermalBC(thermalmodel,"Edge",[1 3],"Temperature",100);
thermalBC(thermalmodel,"Edge",4,"HeatFlux",20);
tbcaEdge1 = findThermalBC(thermalmodel.BoundaryConditions,"Edge",1)
tbcaEdge1 =
ThermalBC with properties:
RegionType: 'Edge'
RegionID: [1 3]
Temperature: 100
HeatFlux: []
ConvectionCoefficient: []
Emissivity: []
AmbientTemperature: []
Vectorized: 'off'
Label: []
5-590
findThermalBC
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'
Label: []
tbcaEdge4 = tbca(2)
tbcaEdge4 =
ThermalBC with properties:
RegionType: 'Edge'
RegionID: 4
Temperature: []
HeatFlux: 20
ConvectionCoefficient: []
Emissivity: []
AmbientTemperature: []
Vectorized: 'off'
Label: []
thermalmodel = createpde("thermal","transient");
gm = importGeometry(thermalmodel,"Block.stl");
pdegplot(thermalmodel,"FaceLabels","on","FaceAlpha",0.5)
5-591
5 Functions
thermalBC(thermalmodel,"Face",1,"Temperature",100);
thermalBC(thermalmodel,"Face",3,"Temperature",300);
thermalBC(thermalmodel,"Face",[5,6],...
"ConvectionCoefficient",5,...
"AmbientTemperature",27);
tbca = findThermalBC(thermalmodel.BoundaryConditions,"Face",[1,3]);
tbcaFace1 = tbca(1)
tbcaFace1 =
ThermalBC with properties:
RegionType: 'Face'
RegionID: 1
Temperature: 100
HeatFlux: []
ConvectionCoefficient: []
Emissivity: []
AmbientTemperature: []
Vectorized: 'off'
5-592
findThermalBC
Label: []
tbcaFace3 = tbca(2)
tbcaFace3 =
ThermalBC with properties:
RegionType: 'Face'
RegionID: 3
Temperature: 300
HeatFlux: []
ConvectionCoefficient: []
Emissivity: []
AmbientTemperature: []
Vectorized: 'off'
Label: []
tbcaFace5 = findThermalBC(thermalmodel.BoundaryConditions,"Face",5)
tbcaFace5 =
ThermalBC with properties:
RegionType: 'Face'
RegionID: [5 6]
Temperature: []
HeatFlux: []
ConvectionCoefficient: 5
Emissivity: []
AmbientTemperature: 27
Vectorized: 'off'
Label: []
tbcaFace6 = findThermalBC(thermalmodel.BoundaryConditions,"Face",6)
tbcaFace6 =
ThermalBC with properties:
RegionType: 'Face'
RegionID: [5 6]
Temperature: []
HeatFlux: []
ConvectionCoefficient: 5
Emissivity: []
AmbientTemperature: 27
Vectorized: 'off'
Label: []
Input Arguments
boundaryConditions — Boundary conditions of a thermal model
BoundaryConditions property of a thermal model
5-593
5 Functions
Geometric region type, specified as "Face" for 3-D geometry or "Edge" for 2-D geometry.
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".
Data Types: double
Output Arguments
tbca — Thermal boundary condition for a particular region
ThermalBC object
Version History
Introduced in R2017a
See Also
thermalBC | ThermalBC
5-594
findThermalIC
findThermalIC
Package: pde
Syntax
tica = findThermalIC(initialConditions,RegionType,RegionID)
Description
tica = findThermalIC(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-595
5 Functions
thermalIC(thermalmodel,10,"Face",1);
thermalIC(thermalmodel,20,"Face",2);
thermalIC(thermalmodel,30,"Face",3);
ticaFace1 = findThermalIC(thermalmodel.InitialConditions,"Face",1)
ticaFace1 =
GeometricThermalICs with properties:
RegionType: 'face'
RegionID: 1
InitialTemperature: 10
ticaFace2 =
GeometricThermalICs with properties:
RegionType: 'face'
RegionID: 2
5-596
findThermalIC
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
Vertices: [6x3 double]
thermalmodel = createpde("thermal","transient");
thermalmodel.Geometry = gm;
pdegplot(thermalmodel,"CellLabels","on","FaceAlpha",0.5)
5-597
5 Functions
thermalIC(thermalmodel,0,"Cell",1);
thermalIC(thermalmodel,100,"Cell",2);
thermalIC(thermalmodel,0,"Cell",3);
ticaCell1 = findThermalIC(thermalmodel.InitialConditions,"Cell",1)
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
5-598
findThermalIC
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
Specify material properties, heat source, set initial and boundary conditions.
5-599
5 Functions
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)
result1 =
TransientThermalResults with properties:
tica = findThermalIC(thermalmodel.InitialConditions,"Face",1)
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);
tlist = 10:0.5:15;
result2 = solve(thermalmodel,tlist);
tica = findThermalIC(thermalmodel.InitialConditions,"Face",1)
tica =
NodalThermalICs with properties:
pdeplot(thermalmodel,"XYData",tica.InitialTemperature)
5-600
findThermalIC
Input Arguments
initialConditions — Initial conditions of a thermal model
InitialConditions property of a thermal model
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
5-601
5 Functions
Output Arguments
tica — Thermal initial condition for a particular region
GeometricThermalICs object | NodalThermalICs object
Version History
Introduced in R2017a
See Also
GeometricThermalICs | NodalThermalICs | thermalIC
5-602
findThermalProperties
findThermalProperties
Package: pde
Syntax
tmpa = findThermalProperties(materialProperties,RegionType,RegionID)
Description
tmpa = findThermalProperties(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-603
5 Functions
• Thermal conductivity is 10 W/ m ⋅∘ C
• Mass density is 1 kg/m3
• Specific heat is 0 . 1 J/ kg ⋅∘ C
thermalProperties(thermalmodel,"ThermalConductivity",10,...
"MassDensity",1,...
"SpecificHeat",0.1,...
"Face",1);
• Thermal conductivity is 20 W/ m ⋅∘ C
• Mass density is 2 kg/m3
• Specific heat is 0 . 2 J/ kg ⋅∘ C
thermalProperties(thermalmodel,"ThermalConductivity",20,...
"MassDensity",2,...
"SpecificHeat",0.2,...
"Face",2);
5-604
findThermalProperties
• Thermal conductivity is 30 W/ m ⋅∘ C )
• Mass density is 3 kg/m3
• Specific heat is 0 . 3 J/ kg ⋅∘ C
thermalProperties(thermalmodel,"ThermalConductivity",30,...
"MassDensity",3,...
"SpecificHeat",0.3,...
"Face",3);
mpaFace1 =
ThermalMaterialAssignment with properties:
RegionType: 'face'
RegionID: 1
ThermalConductivity: 10
MassDensity: 1
SpecificHeat: 0.1000
mpaFace2 =
ThermalMaterialAssignment with properties:
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
5-605
5 Functions
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
Vertices: [4x3 double]
thermalmodel = createpde("thermal");
thermalmodel.Geometry = gm;
pdegplot(thermalmodel,"CellLabels","on","FaceAlpha",0.5)
5-606
findThermalProperties
mpaCell1 =
ThermalMaterialAssignment with properties:
RegionType: 'cell'
RegionID: 1
ThermalConductivity: 10
MassDensity: []
SpecificHeat: []
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
materialProperties — Material properties of the model
MaterialProperties property of a thermal model
5-607
5 Functions
Geometric region ID, specified as a vector of positive integers. Find the region IDs by using
pdegplot.
Example: findThermalProperties(thermalmodel.MaterialProperties,"Face",1:3)
Data Types: double
Output Arguments
tmpa — Material properties assignment
ThermalMaterialAssignment object
Version History
Introduced in R2017a
See Also
ThermalMaterialAssignment | thermalProperties | ThermalModel
5-608
generateMesh
generateMesh
Package: pde
Syntax
mesh = generateMesh(model)
femodel = generateMesh(femodel)
___ = generateMesh( ___ ,Name,Value)
Description
mesh = generateMesh(model) creates a mesh for the geometry stored in the model object. The
toolbox stores the mesh in the Mesh property of the structural, thermal, electromagnetic model, or
PDEModel.
model must contain a geometry. For details about creating a geometry and including it in a model,
see “Geometry and Mesh” and the geometry functions listed there.
femodel = generateMesh(femodel) creates a mesh for the geometry stored in the femodel
object. The toolbox stores the mesh in the Geometry.Mesh property. Assigning the result to the
model updates the mesh stored in the Geometry property of the model.
___ = generateMesh( ___ ,Name,Value) modifies the mesh generation according to the
Name,Value arguments. This syntax works with the model and femodel arguments.
Examples
model = createpde(1);
geometryFromEdges(model,@lshapeg);
generateMesh(model);
pdeplot(model)
5-609
5 Functions
model = createpde(1);
importGeometry(model,"BracketTwoHoles.stl");
generateMesh(model)
ans =
FEMesh with properties:
5-610
generateMesh
pdeplot3D(model)
Create a mesh with target maximum element size 5 instead of the default 7.3485.
generateMesh(model,"Hmax",5)
ans =
FEMesh with properties:
pdeplot3D(model)
5-611
5 Functions
Generate a 2-D mesh with finer spots around the specified edges and vertices.
Create a model.
model = createpde;
Create and plot a 2-D geometry representing a circle with a diamond-shaped hole in its center.
g = geometryFromEdges(model,@scatterg);
pdegplot(g,"VertexLabels","on","EdgeLabels","on")
5-612
generateMesh
Generate a mesh for this geometry using the default mesh parameters.
m1 = generateMesh(model)
m1 =
FEMesh with properties:
pdeplot(m1)
5-613
5 Functions
Generate a mesh with the target size on edge 1, which is smaller than the target minimum element
size, MinElementSize, of the default mesh.
m2 = generateMesh(model,"Hedge",{1,0.001})
m2 =
FEMesh with properties:
pdeplot(m2)
5-614
generateMesh
Generate a mesh specifying the target sizes for edge 1 and vertices 6 and 7.
m3 = generateMesh(model,"Hedge",{1,0.001},"Hvertex",{[6 7],0.002})
m3 =
FEMesh with properties:
pdeplot(m3)
5-615
5 Functions
Input Arguments
model — Model container
PDEModel object | ThermalModel object | StructuralModel object | ElectromagneticModel
object
5-616
generateMesh
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: generateMesh(model,"Hmax",0.25);
A triangle or tetrahedron representing a linear element has nodes at the corners. A triangle or
tetrahedron representing a quadratic element has nodes at its corners and edge centers. The center
nodes in quadratic meshes are always added at half-distance between corners. For geometries with
curved surfaces and edges, center nodes might not appear on the edge or surface itself.
In general, "quadratic" elements produce more accurate solutions. Override the default
"quadratic" only to solve a 3-D magnetostatic problem, to save memory, or to solve a 2-D problem
using a legacy solver. Legacy PDE solvers use linear triangular mesh for 2-D geometries.
Example: generateMesh(model,"GeometricOrder","linear");
Data Types: char | string
Mesh growth rate, specified as a number greater than or equal to 1 and less than or equal to 2.
Example: generateMesh(model,"Hgrad",1.3);
Data Types: double
Hmax is an approximate upper bound on the mesh edge lengths. Occasionally, generateMesh can
create a mesh with some elements that exceed Hmax.
generateMesh estimates the default value of Hmax from overall dimensions of the geometry.
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
5-617
5 Functions
Hmin is an approximate lower bound on the mesh edge lengths. Occasionally, generateMesh can
create a mesh with some elements that are smaller than Hmin.
generateMesh estimates the default value of Hmin from overall dimensions of the geometry.
Example: generateMesh(model,"Hmin",0.05);
Data Types: double
Target size on selected faces, specified as a cell array containing an even number of elements. Odd-
indexed elements are positive integers or vectors of positive integers specifying face IDs. Even-
indexed elements are positive numbers specifying the target size for the corresponding faces.
Example: generateMesh(model,"Hmax",0.25,"Hface",{[1 2],0.1,[3 4 5],0.05})
Data Types: double
Target size around selected edges, specified as a cell array containing an even number of elements.
Odd-indexed elements are positive integers or vectors of positive integers specifying edge IDs. Even-
indexed elements are positive numbers specifying the target sizes for the corresponding edges.
Example: generateMesh(model,"Hmax",0.25,"Hedge",{[1 2],0.01,3,0.05})
Data Types: double
Target size around selected vertices, specified as a cell array containing an even number of elements.
Odd-indexed elements are positive integers or vectors of positive integers specifying vertex IDs.
Even-indexed elements are positive numbers specifying the target sizes for the corresponding
vertices.
Example: generateMesh(model,"Hmax",0.25,"Hvertex",{1,0.02})
Data Types: double
Output Arguments
mesh — Mesh description
FEMesh object
More About
Element
5-618
generateMesh
For 2-D problems, an element is a triangle in the model.Mesh.Element property. If the triangle
represents a linear element, it has nodes only at the triangle corners. If the triangle represents a
quadratic element, then it has nodes at the triangle corners and edge centers.
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.
Tips
• 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 or node and element counts.
• generateMesh uses the following set of rules when you specify local element sizes with Hface,
Hedge, or Hvertex. These rules are valid for both the default and custom values of Hmin and
Hmax.
• If you specify local sizes for regions near each other, generateMesh uses the minimum size.
For example, if you specify size 1 on an edge and size 0.5 on one of its vertices, the function
gradually reduces the element sizes in the proximity of that vertex.
• If you specify local sizes smaller than Hmin, generateMesh ignores Hmin in those localities.
• If you specify local sizes larger than Hmax, generateMesh ignores the specified local sizes.
Hmax is not exceeded anywhere in the mesh.
Version History
Introduced in R2015a
The mesh generator accepts the femodel object that defines structural mechanics, thermal, and
electromagnetic problems.
You can now specify local target mesh size around geometric vertices, edges, and faces. The function
generates a mesh with the element sizes around the specified regions as close to the target sizes as
possible, and gradually blends the mesh between regions with different element sizes.
The mesh generator now uses new mesh generation algorithm for 2-D geometries. It also lets you
specify mesh growth rate by using the Hgrad argument.
Resulting meshes can differ from meshes generated in previous releases. For example, meshes
generated with the default size controls can have fewer elements than before. Also, generateMesh
creates quadratic meshes for 2-D problems by default. In previous releases, the default mesh for 2-D
geometries is a linear mesh.
5-619
5 Functions
generateMesh ignores the Jiggle, JiggleIter, and MesherVersion arguments. The mesher
produces good quality meshes without jiggling the nodes.
See Also
Functions
geometryFromEdges | importGeometry
Objects
fegeometry | femodel | PDEModel | StructuralModel | ThermalModel |
ElectromagneticModel
Properties
FEMesh
Topics
“Solve Problems Using PDEModel Objects” on page 2-3
“Finite Element Method Basics” on page 1-11
“Mesh Data” on page 2-184
“Mesh Data as [p,e,t] Triples” on page 2-181
5-620
GeometricInitialConditions Properties
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, specified as 'face' for a 2-D region, or 'cell' for a 3-D region.
Data Types: char | string
RegionID — Region ID
vector of positive integers
Region ID, specified as a vector of positive integers. To determine which ID corresponds to which
portion of the geometry, use the pdegplot function. Set the 'FacenLabels' name-value pair to
'on'.
Data Types: double
Initial value, specified as a scalar, vector, or function handle. For details, see
setInitialConditions.
Data Types: double | function_handle
Complex Number Support: Yes
Initial derivative, specified as a scalar, vector, or function handle. For details, see
setInitialConditions.
Data Types: double | function_handle
Complex Number Support: Yes
5-621
5 Functions
Version History
Introduced in R2016a
See Also
findInitialConditions | setInitialConditions | NodalInitialConditions
Topics
“Set Initial Conditions” on page 2-113
“View, Edit, and Delete Initial Conditions” on page 2-122
“Solve Problems Using PDEModel Objects” on page 2-3
5-622
GeometricStructuralICs Properties
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, 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 | string
Geometric region ID, specified as a vector of positive integers. Find the region IDs by using
pdegplot.
Data Types: double
Initial displacement, specified as a numeric vector or function handle. For details, see
structuralIC.
Data Types: double | function_handle
Initial velocity, specified as a numeric vector or function handle. For details, see structuralIC.
Data Types: double | function_handle
Version History
Introduced in R2018a
5-623
5 Functions
See Also
structuralIC | findStructuralIC | NodalStructuralICs Properties
5-624
GeometricThermalICs Properties
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, specified as 'Vertex', 'Edge', or 'Face' for a 2-D or 3-D region, or 'Cell' for a 3-D
region.
Data Types: char | string
RegionID — Region ID
vector of positive integers
Region ID, specified as a vector of positive integers. To determine which ID corresponds to which
portion of the geometry, use the pdegplot function and setting the 'FaceLabels' name-value pair
to 'on'.
Data Types: double
Initial temperature, specified as a scalar, vector, or function handle. For details, see thermalIC.
Data Types: double | function_handle
Version History
Introduced in R2017a
See Also
thermalIC | findThermalIC | NodalThermalICs
5-625
5 Functions
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, specified as a scalar, vector, or function handle. For details, see
setInitialConditions.
Data Types: double | function_handle
Complex Number Support: Yes
Initial derivative, specified as a scalar, vector, or function handle. For details, see
setInitialConditions.
Data Types: double | function_handle
Complex Number Support: Yes
Version History
Introduced in R2016b
See Also
findInitialConditions | setInitialConditions | GeometricInitialConditions
Topics
“Set Initial Conditions” on page 2-113
“View, Edit, and Delete Initial Conditions” on page 2-122
“Solve Problems Using PDEModel Objects” on page 2-3
5-626
NodalStructuralICs Properties
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, specified as a numeric vector or function handle. For details, see
structuralIC.
Data Types: double | function_handle
Initial velocity, specified as a numeric vector or function handle. For details, see structuralIC.
Data Types: double | function_handle
Version History
Introduced in R2018a
See Also
structuralIC | findStructuralIC | GeometricStructuralICs Properties
5-627
5 Functions
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, specified as a scalar, vector, or function handle. For details, see thermalIC.
Data Types: double | function_handle
Version History
Introduced in R2017a
See Also
thermalIC | findThermalIC | GeometricThermalICs
5-628
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
Create a decomposed solid geometry model representing a rectangle and include it in a PDE model.
model = createpde;
R1 = [3,4,-1,1,1,-1,0.5,0.5,-0.75,-0.75]';
g = decsg(R1);
geometryFromEdges(model,g);
pdegplot(model,EdgeLabels="on")
axis equal
xlim([-1.1,1.1])
ylim([-0.9,0.6])
5-629
5 Functions
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)];
gm = [R1,C1];
sf = 'R1-C1';
ns = char('R1','C1');
ns = ns';
g = decsg(gm,sf,ns);
5-630
geometryFromEdges
geometryFromEdges(model,g);
pdegplot(model,EdgeLabels="on")
axis equal
xlim([-1.1,1.1])
The toolbox provides the several geometry functions. Specify them by using the following function
handles.
model = createpde;
g = geometryFromEdges(model,@cardg);
pdegplot(model)
5-631
5 Functions
clear model
model = createpde;
g = geometryFromEdges(model,@circleg);
pdegplot(model)
5-632
geometryFromEdges
clear model
model = createpde;
g = geometryFromEdges(model,@cirsg);
pdegplot(model)
5-633
5 Functions
clear model
model = createpde;
g = geometryFromEdges(model,@crackg);
pdegplot(model)
5-634
geometryFromEdges
clear model
model = createpde;
g = geometryFromEdges(model,@lshapeg);
pdegplot(model)
5-635
5 Functions
clear model
model = createpde;
g = geometryFromEdges(model,@scatterg);
pdegplot(model)
5-636
geometryFromEdges
clear model
model = createpde;
g = geometryFromEdges(model,@squareg);
pdegplot(model)
5-637
5 Functions
Input Arguments
model — Model container
PDEModel object | ThermalModel object | StructuralModel object | ElectromagneticModel
object
g — Geometry description
decomposed geometry matrix | name of a geometry function | handle to a geometry function
A geometry function must return the same result for the same input arguments in every function call.
Thus, it must not contain functions and expressions designed to return a variety of results, such as
random number generators.
5-638
geometryFromEdges
Example: geometryFromEdges(model,@circleg)
Data Types: double | char | function_handle
Output Arguments
pg — Geometry object
AnalyticGeometry object
Version History
Introduced in R2015a
See Also
Objects
AnalyticGeometry | PDEModel
Topics
“Solve PDEs with Constant Boundary Conditions” on page 2-134
“Solve Problems Using PDEModel Objects” on page 2-3
5-639
5 Functions
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.
Examples
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-640
geometryFromMesh
Create a geometric block from the convex hull of a mesh grid of points.
5-641
5 Functions
pdegplot(model,"FaceLabels","on","FaceAlpha",0.5)
This example shows how to create a 2-D multidomain geometry from a planar mesh.
The MultidomainMesh2D file, which is included in Partial Differential Equation Toolbox™, contains a
2-D mesh. Load information about nodes, elements, and element-to-domain correspondence into your
workspace.
load MultidomainMesh2D
model = createpde;
geometryFromMesh(model,nodes,elements,ElementIdToRegionId);
pdegplot(model,FaceLabels="on")
5-642
geometryFromMesh
Load information about nodes, elements, and element-to-domain correspondence into your
workspace. The file MultidomainMesh3D ships with your software.
load MultidomainMesh3D
model = createpde;
geometryFromMesh(model,nodes,elements,ElementIdToRegionId);
pdegplot(model,"CellLabels","on")
5-643
5 Functions
Input Arguments
model — Model container
PDEModel object | ThermalModel object | StructuralModel object | ElectromagneticModel
object
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.
5-644
geometryFromMesh
Mesh elements, specified as an integer matrix with 3, 4, 6, or 10 rows, and Nelements columns,
where Nelements is the number of elements in the mesh.
• Linear planar mesh or linear 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 planar mesh or quadratic mesh on the geometry surface has size 6-by-Nelements. Each
column of elements contains the indices of the triangle corner nodes and edge centers for a
surface element. In this case, the resulting geometry does not contain a full mesh. Create the
mesh using the generateMesh function.
• 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-184.
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
Output Arguments
G — Geometry
handle to model.Geometry
• If elements is a 3-by-Nelements matrix representing a surface mesh, then mesh is []. In this
case, create a mesh for the geometry using the generateMesh function.
• If elements is a matrix with more than three rows representing a volume mesh, then mesh has
the same nodes and elements as the inputs. You can get a different mesh for the geometry by
using the generateMesh function.
5-645
5 Functions
Version History
Introduced in R2015b
The function now lets you create a multidomain geometry by specifying the subdomain ID for each
element of the mesh.
See Also
alphaShape | DiscreteGeometry | generateMesh | importGeometry
Topics
“STL File Import” on page 2-43
“Solve Problems Using PDEModel Objects” on page 2-3
5-646
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, specified as 'Face' for a 2-D region, or 'Cell' for a 3-D region.
Data Types: char | string
RegionID — Region ID
vector of positive integers
Region ID, specified as a vector of positive integers. To determine which ID corresponds to which
portion of the geometry, use the pdegplot function. Set the 'FaceLabels' name-value pair to
'on'.
Data Types: double
Heat source value, specified as a number or a function handle. A heat source with a negative value is
called a heat sink.
Data Types: double | function_handle
Version History
Introduced in R2017a
5-647
5 Functions
See Also
findHeatSource | internalHeatSource
5-648
hyperbolic
hyperbolic
(Not recommended) Solve hyperbolic PDE problem
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')
Description
Hyperbolic equation solver
∂2 u
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.
∂2 u
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.
5-649
5 Functions
u = hyperbolic( ___ ,rtol) and u = hyperbolic( ___ ,rtol,atol) modify the solution
process by passing to the ODE solver a relative tolerance rtol, and optionally an absolute tolerance
atol.
u = hyperbolic( ___ ,'Stats','off') turns off the display of internal ODE solver statistics
during the solution process.
Examples
Hyperbolic Equation
∂2 u
= Δu
∂t2
model = createpde;
geometryFromEdges(model,@squareg);
pdegplot(model,'EdgeLabels','on')
ylim([-1.1,1.1])
axis equal
5-650
hyperbolic
∇u ⋅ n = 0
for y = ± 1. (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;
5-651
5 Functions
generateMesh(model,'GeometricOrder','linear','Hmax',0.1);
u1 = hyperbolic(u0,ut0,tlist,model,c,a,f,d);
figure
pdeplot(model,'XYData',u1(:,1))
figure
pdeplot(model,'XYData',u1(:,end))
5-652
hyperbolic
For a version of this example with animation, see “Wave Equation on Square Domain” on page 3-346.
∂2 u
= Δu
∂t2
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-653
5 Functions
∇u ⋅ n = 0
for y = ± 1. (The Neumann boundary condition is the default condition, so the second specification is
redundant.)
5-654
hyperbolic
[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))
figure
pdeplot(p,e,t,'XYData',u(:,end))
5-655
5 Functions
For a version of this example with animation, see “Wave Equation on Square Domain” on page 3-346.
model = createpde();
importGeometry(model,'BracketWithHole.stl');
figure
pdegplot(model,'FaceLabels','on')
view(30,30)
title('Bracket with Face Labels')
5-656
hyperbolic
figure
pdegplot(model,'FaceLabels','on')
view(-134,-32)
title('Bracket with Face Labels, Rear View')
5-657
5 Functions
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 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);
5-658
hyperbolic
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 clim
command.
umax = max(max(u));
umin = min(min(u));
subplot(2,2,1)
pdeplot3D(model,'ColorMapData',u(:,5))
clim([umin umax])
title('Time 1/2')
subplot(2,2,2)
pdeplot3D(model,'ColorMapData',u(:,10))
clim([umin umax])
title('Time 1')
subplot(2,2,3)
pdeplot3D(model,'ColorMapData',u(:,15))
clim([umin umax])
title('Time 3/2')
subplot(2,2,4)
pdeplot3D(model,'ColorMapData',u(:,20))
clim([umin umax])
title('Time 2')
5-659
5 Functions
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.
model = createpde();
importGeometry(model,'BracketWithHole.stl');
figure
pdegplot(model,'FaceLabels','on')
view(30,30)
title('Bracket with Face Labels')
5-660
hyperbolic
figure
pdegplot(model,'FaceLabels','on')
view(-134,-32)
title('Bracket with Face Labels, Rear View')
5-661
5 Functions
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 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);
5-662
hyperbolic
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')
Input Arguments
u0 — Initial condition
vector | character vector | character array | string scalar | string vector
5-663
5 Functions
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.
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.
char('x.^2 + 5*cos(x.*y)',...
'tanh(x.*y)./(1+z.^2)')
Example: p(1,:).^2+5*cos(p(2,:).*p(1,:))
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
5-664
hyperbolic
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
∂2 u
d − ∇ ⋅ c ∇u + au = f
∂t2
∂2 u
d − ∇ ⋅ c ⊗ ∇u + au = f
∂t2
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
∂2 u
d − ∇ ⋅ c ∇u + au = f
∂t2
∂2 u
d − ∇ ⋅ c ⊗ ∇u + au = f
∂t2
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
∂2 u
d − ∇ ⋅ c ∇u + au = f
∂t2
∂2 u
d − ∇ ⋅ c ⊗ ∇u + au = f
∂t2
5-665
5 Functions
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
∂2 u
d − ∇ ⋅ c ∇u + au = f
∂t2
∂2 u
d − ∇ ⋅ c ⊗ ∇u + au = f
∂t2
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.
Example: b = 'circleb1', b = "circleb1", or b = @circleb1
Data Types: double | char | string | function_handle
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 as [p,e,t] Triples” on page 2-181.
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 as [p,e,t] Triples” on page 2-181.
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)
5-666
hyperbolic
t — Mesh triangles
matrix
Mesh triangles, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For a description of the (p,e,t) matrices, see “Mesh Data as [p,e,t] Triples” on page 2-181.
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-
210. Typically, Kc is the output of assempde.
Fc — Load vector
vector
Load vector, specified as a vector. See “Elliptic Equations” on page 5-210. Typically, Fc is the output
of assempde.
B — Dirichlet nullspace
sparse matrix
Dirichlet nullspace, returned as a sparse matrix. See “Algorithms” on page 5-210. Typically, B is the
output of assempde.
ud — Dirichlet vector
vector
Dirichlet vector, returned as a vector. See “Algorithms” on page 5-210. 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-210.
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.
5-667
5 Functions
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:
2
d v dv
BT MB + BT DB + Kv = F
dt 2 dt
with initial condition u0 and initial derivative ut0. Then hyperbolic returns the solution
u = B*v + ud.
For an example using D, see “Dynamics of Damped Cantilever Beam” on page 3-20.
Example: alpha*M + beta*K
Data Types: double
Complex Number Support: Yes
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 “3-D Solution and Gradient Plots with
MATLAB Functions” on page 3-391.
5-668
hyperbolic
Algorithms
Hyperbolic Equations
∂2 u ∂u
m +d − ∇ · c ∇u + au = f
∂t 2 ∂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
∂2 u
m − ∇ ⋅ c ∇u + au = f
∂t2
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
2
d U
M + KU = F
dt2
Ui 0 = u0 xi ∀i
d
U 0 = v0 xi ∀i
dt i
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.
The finite element method for 3-D geometry is similar to the 2-D method described in “Elliptic
Equations” on page 5-210. The main difference is that the elements in 3-D geometry are tetrahedra,
which means that the basis functions are different from those in 2-D geometry.
5-669
5 Functions
It is convenient to map a tetrahedron to a canonical tetrahedron with a local coordinate system (r,s,t).
ϕ1 = 1 − r − s − t
ϕ2 = r
ϕ3 = s
ϕ4 = t
For a quadratic tetrahedron, there are additional nodes at the edge midpoints.
5-670
hyperbolic
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
− ∇ ⋅ c ⊗ ∇u + au = f
∂u
d − ∇ ⋅ c ⊗ ∇u + au = f
∂t
5-671
5 Functions
∂2 u
d − ∇ ⋅ c ⊗ ∇u + au = f
∂t2
− ∇ ⋅ c ⊗ ∇u + au = λdu
For 2-D systems, the notation ∇ ⋅ (c ⊗ ∇u) represents an N-by-1 matrix with an (i,1)-component
N
∂ ∂ ∂ ∂ ∂ ∂ ∂ ∂
∑ c
∂x i, j, 1, 1 ∂x
+ c
∂x i, j, 1, 2 ∂y
+ c
∂y i, j, 2, 1 ∂x
+ c u
∂y i, j, 2, 2 ∂y j
j=1
For 3-D systems, the notation ∇ ⋅ (c ⊗ ∇u) represents an N-by-1 matrix with an (i,1)-component
N
∂ ∂ ∂ ∂ ∂ ∂
∑ c
∂x i, j, 1, 1 ∂x
+ c
∂x i, j, 1, 2 ∂y
+ c u
∂x i, j, 1, 3 ∂z j
j=1
N
∂ ∂ ∂ ∂ ∂ ∂
+ ∑ c
∂y i, j, 2, 1 ∂x
+ c
∂y i, j, 2, 2 ∂y
+ c u
∂y i, j, 2, 3 ∂z j
j=1
N
∂ ∂ ∂ ∂ ∂ ∂
+ ∑ c
∂z i, j, 3, 1 ∂x
+ c
∂z i, j, 3, 2 ∂y
+ c u
∂z i, j, 3, 3 ∂z 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′μ
For 2-D systems, the notation n · c ⊗ ∇u represents an N-by-1 matrix with (i,1)-component
N
∂ ∂ ∂ ∂
∑ cos(α)ci, j, 1, 1
∂x
+ cos(α)ci, j, 1, 2
∂y
+ sin(α)ci, j, 2, 1
∂x
+ sin(α)ci, j, 2, 2 u
∂y j
j=1
For 3-D systems, the notation n · c ⊗ ∇u represents an N-by-1 matrix with (i,1)-component
5-672
hyperbolic
N
∂ ∂ ∂
∑ cos(α)ci, j, 1, 1
∂x
+ cos(α)ci, j, 1, 2
∂y
+ cos(α)ci, j, 1, 3 u
∂z j
j=1
N
∂ ∂ ∂
+ ∑ cos(β)ci, j, 2, 1
∂x
+ cos(β)ci, j, 2, 2
∂y
+ cos(β)ci, j, 2, 3 u
∂z j
j=1
N
∂ ∂ ∂
+ ∑ cos(γ)ci, j, 3, 1
∂x
+ cos(γ)ci, j, 3, 2
∂y
+ cos(γ)ci, j, 3, 3 u
∂z 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′μ, 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.
Partial Differential Equation Toolbox software supports two implementations of Dirichlet conditions.
The simplest is the “Stiff Spring” model, so named for its interpretation in solid mechanics. See
“Elliptic Equations” on page 5-210 for the scalar case, which is equivalent to a diagonal h-matrix. For
the general case, Dirichlet conditions
hu = r
L(h′hu − h′r)
to the equations KU = F, where L is a large number such as 104 times a representative size of the
elements of K.
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
HU = R.
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
5-673
5 Functions
B´ KBV = B´ F – B´Kud
Version History
Introduced before R2006a
hyperbolic is not recommended. Use solvepde instead. There are no plans to remove
hyperbolic.
R2012b: Coefficients of hyperbolic PDEs as functions of the solution and its gradient
You can now solve hyperbolic equations whose coefficients depend on the solution u or on the
gradient of u.
See Also
solvepde
5-674
importGeometry
importGeometry
Package: pde
Syntax
gm = importGeometry(geometryfile)
gm = importGeometry(model,geometryfile)
importGeometry(model, ___ )
___ = importGeometry( ___ ,"MaxRelativeDeviation",d)
Description
gm = importGeometry(geometryfile) creates a geometry object from the specified STL or STEP
geometry file. A geometry imported from an STL file can be 3-D or planar. A geometry imported from
a STEP file must be 3-D.
importGeometry(model, ___ ) creates a geometry object from the specified STL or STEP
geometry file and includes the geometry in the model container.
Examples
gm = importGeometry("ForearmLink.stl");
pdegplot(gm)
5-675
5 Functions
Import a planar STL geometry and include it in a PDE model. When importing a planar geometry,
importGeometry converts it to a 2-D geometry by mapping it to the xy-plane.
model = createpde;
importGeometry(model,"PlateHolePlanar.stl")
ans =
DiscreteGeometry with properties:
NumCells: 0
NumFaces: 1
NumEdges: 5
NumVertices: 5
Vertices: [5x3 double]
5-676
importGeometry
pdegplot(model,"EdgeLabels","on")
gm = importGeometry("BlockWithHole.step");
pdegplot(gm,"FaceAlpha",0.3)
5-677
5 Functions
Now import the same geometry while specifying the relative sag. You can use this parameter to
control the accuracy of the geometry import.
gm = importGeometry("BlockWithHole.step","MaxRelativeDeviation",10);
figure
pdegplot(gm,"FaceAlpha",0.3)
5-678
importGeometry
Input Arguments
model — Model container
PDEModel object | ThermalModel object | StructuralModel object | ElectromagneticModel
object
Path to STL or STEP file, specified as a string scalar or a character vector ending with the file
extension ".stl", ".stp", or ".step". Use can also use the uppercase extensions ".STL", ".STP"
or ".STEP", or any combinations of uppercase and lowercase letters in these extensions.
Example: "../geometries/Carburetor.stl"
Data Types: string | char
5-679
5 Functions
d — Relative sag
1 (default) | number in the range [0.1, 10]
Relative sag for importing a STEP geometry, specified as a number in the range [0.1, 10]. A relative
sag is the ratio between the local absolute sag and the local mesh edge length. The absolute sag is
the maximal gap between the mesh and the geometry.
Example: gm = importGeometry("AngleBlock.step","MaxRelativeDeviation",5)
Data Types: double
Output Arguments
gm — Geometry
DiscreteGeometry object
Limitations
• importGeometry does not allow you to import a multidomain 2-D or 3-D geometry where
subdomains have any common points. If the subdomains of the geometry have common points, the
toolbox still treats these subdomains as disconnected, without any common interface between
them. Each subdomain has its own mesh.
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. See “Multidomain Geometry Reconstructed from Mesh” on page 2-
82.
Tips
• The STL format approximates the boundary of a CAD geometry by using a collection of triangles,
and the importGeometry function reconstructs the faces and edges from this data.
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.
5-680
importGeometry
• Because STL geometries are only approximations of the original CAD geometries, the areas and
volumes of the STL and CAD geometries can differ.
Version History
Introduced in R2015a
You can now import a geometry from a STEP file. When importing from a STEP file, you can control
the accuracy of the geometry import by specifying the relative sag value.
You can now create a geometry object from an STL geometry file without attaching the imported
geometry to any model. The new syntax is g = importGeometry('geometryfile.stl').
You can now import a planar STL geometry and convert it to a 2-D geometry by mapping it to the xy-
plane.
When importing an STL geometry for a 3-D problem, the function can now recognize and reconstruct
more geometric vertices, edges, and faces of the original CAD geometry in some instances. In these
cases, the resulting geometry is a closer match to the original CAD geometry.
Detailed geometries can now contain more faces and edges than in previous releases. As a result, in
rare instances, the new faces and edges can cause renumbering of the existing ones. If your code
imports an STL geometry, visually check the geometry to ensure that you are assigning boundary and
initial conditions to the intended regions.
See Also
Functions
geometryFromMesh | pdegplot
5-681
5 Functions
Objects
DiscreteGeometry | PDEModel | StructuralModel | ThermalModel | ElectromagneticModel
Topics
“STL File Import” on page 2-43
“STEP File Import” on page 2-58
“Multidomain Geometry Reconstructed from Mesh” on page 2-82
“Sphere in Cube” on page 2-74
“Geometry from Triangulated Mesh” on page 2-62
5-682
initmesh
initmesh
Package: 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 generateMesh.
Syntax
[p,e,t] = initmesh(g)
[p,e,t] = initmesh(g,Name,Value)
Description
[p,e,t] = initmesh(g) generates a triangular mesh for a 2-D geometry. The function uses a
Delaunay triangulation algorithm.
[p,e,t] = initmesh(g,Name,Value) generates a 2-D mesh using one or more Name,Value pair
arguments.
Examples
[p,e,t] = initmesh("lshapeg");
pdemesh(p,e,t)
5-683
5 Functions
Generate a triangular mesh of the L-shaped membrane with the target maximum mesh edge length of
0.1.
[p,e,t] = initmesh("lshapeg","Hmax",0.1);
pdemesh(p,e,t)
5-684
initmesh
Input Arguments
g — Geometry description
decomposed geometry matrix | geometry function | handle to geometry function
A geometry function must return the same result for the same input arguments in every function call.
Thus, it must not contain functions and expressions designed to return a variety of results, such as
random number generators.
Data Types: double | char | string | function_handle
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: [p,e,t] = initmesh("lshapeg","Hmax",0.1);
5-685
5 Functions
Target maximum mesh edge length, specified as the comma-separated pair consisting of "Hmax" and
a positive real number.
Hmax is an approximate upper bound on the mesh edge lengths. initmesh estimates the default
value of Hmax from overall dimensions of the geometry.
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 initmesh can take additional
time to respond to the interrupt.
Example: [p,e,t] = initmesh(g,"Hmax",0.25);
Data Types: double
Mesh growth rate, specified as the comma-separated pair consisting of "Hgrad" and a number
strictly greater than 1 and less than 2.
Example: [p,e,t] = initmesh(g,"Hgrad",1.5);
Data Types: double
Toggle to preserve bounding box, specified as the comma-separated pair consisting of "Box" and
"on" or "off". By turning on "Box" you can get a good idea of how the mesh generation algorithm
works within the bounding box.
Example: [p,e,t] = initmesh(g,"Box","on");
Data Types: char | string
Toggle to use edge triangulation, specified as the comma-separated pair consisting of "Init" and
"on" or "off". By turning on Init you can see the initial triangulation of the boundaries. For
example, use these commands to determine the subdomain number n of the point xy.
[p,e,t] = initmesh(g,"Hmax",Inf,"Init","on");
[uxy,tn,a2,a3] = tri2grid(p,t,zeros(size(p,2)),x,y);
n = t(4,tn);
If the point is outside the geometry, tn is NaN, and the command n = t(4,tn) results in a failure.
Data Types: char | string
Toggle to call jigglemesh after creating the mesh, specified as the comma-separated pair consisting
of "Jiggle" and "mean", "minimum""on", or "off".
5-686
initmesh
Maximum number of iterations for jigglemesh, specified as the comma-separated pair consisting of
"JiggleIter" and a positive integer.
Example: [p,e,t] = initmesh(g,"Jiggle","on","JiggleIter",50);
Data Types: double
Algorithm for generating initial mesh, specified as the comma-separated pair consisting of
"MesherVersion" and either "R2013a" or "preR2013a". The "R2013a" algorithm runs faster,
and can triangulate more geometries than the "preR2013a" algorithm. Both algorithms use
Delaunay triangulation.
Data Types: char | string
Output Arguments
p — Mesh points
2-by-Np matrix
Mesh points, returned as a 2-by-Np matrix. 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) and the y-coordinate of point k in p(2,k). For
details, see “Mesh Data as [p,e,t] Triples” on page 2-181.
e — Mesh edges
7-by-Ne matrix
Mesh edges, returned as a 7-by-Ne matrix, where Ne is the number of boundary 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 as [p,e,t] Triples” on page 2-181.
t — Mesh elements
4-by-Nt matrix
Mesh elements, returned as a 4-by-Nt matrix. Nt is the number of triangles in the mesh.
The t(i,k), with i ranging from 1 through end - 1, contain indices to the corner points of element
k. For details, see “Mesh Data as [p,e,t] Triples” on page 2-181. The last row, t(end,k), contains the
subdomain number of the element.
5-687
5 Functions
Version History
Introduced before R2006a
initmesh provides an enhancement option for increased meshing speed and robustness. Choose the
enhanced algorithm by setting the MesherVersion name-value pair to 'R2013a'. The default
MesherVersion value of 'preR2013a' gives the same mesh as previous toolbox versions.
The enhancement is available inpdeModeler from the Mesh > Parameters > Mesher version
menu.
References
[1] George, P. L. Automatic Mesh Generation — Application to Finite Element Methods. Wiley, 1991.
See Also
decsg | jigglemesh | refinemesh | adaptmesh
Topics
“Mesh Data as [p,e,t] Triples” on page 2-181
5-688
internalHeatSource
internalHeatSource
Package: pde
Syntax
internalHeatSource(thermalmodel,heatSourceValue)
internalHeatSource(thermalmodel,heatSourceValue,RegionType,RegionID)
internalHeatSource( ___ ,"Label",labeltext)
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.
internalHeatSource( ___ ,"Label",labeltext) adds a label for the internal heat source to be
used by the linearizeInput function. This function lets you pass internal heat sources to the
linearize function that extracts sparse linear models for use with Control System Toolbox™.
Examples
thermalmodel = createpde("thermal","transient");
gm = importGeometry(thermalmodel,"SquareBeam.stl");
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)
5-689
5 Functions
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
Label: []
thermalModel = createpde("thermal","transient");
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
5-690
internalHeatSource
HeatSource: 25
Label: []
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);
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 = 2000y.
q = @(location,state)2000*location.y;
ans =
HeatSourceAssignment with properties:
RegionType: 'face'
RegionID: 1
HeatSource: @(location,state)2000*location.y
Label: []
Use a function handle to specify an internal heat source that depends on time.
Create a thermal model for transient analysis and include the geometry. The geometry is a
rectangular strip.
thermalmodel = createpde("thermal","transient");
g = decsg([3 4 -1.5 1.5 1.5 -1.5 0 0 .2 .2]');
geometryFromEdges(thermalmodel,g);
5-691
5 Functions
thermalBC(thermalmodel,"Edge",2,"Temperature",100);
thermalBC(thermalmodel,"Edge",3,...
"ConvectionCoefficient",50,...
"AmbientTemperature",100);
thermalIC(thermalmodel,0);
Specify that the entire geometry generates heat at the rate 20000t during the first 500 seconds, and
then the heat source turns off. For details, see Time-Dependent Heat Source Function on page 5-
694.
internalHeatSource(thermalmodel,@heatSource);
Generate the mesh, solve the model using the solution times from 0 to 50000 seconds, and plot the
results.
generateMesh(thermalmodel);
tfinal = 50000;
tlist = 0:100:tfinal;
result = solve(thermalmodel,tlist);
T = result.Temperature;
figure
subplot(2,1,1)
pdeplot(thermalmodel,"XYData",T(:,6),"Contour","on")
axis equal
title(sprintf("Temperature at %g s",tlist(6)))
subplot(2,1,2)
pdeplot(thermalmodel,"XYData",T(:,end),"Contour","on")
axis equal
title(sprintf("Temperature at %g s",tfinal))
5-692
internalHeatSource
Always ensure that your function returns a matrix of NaN of the correct size when state.time is
NaN. The solver properly recognizes a time-dependent problem by passing NaN state values and
looking for returned NaN values. Without this condition, the solver might fail or return incorrect
results.
internalHeatSource(thermalmodel,@heatSourceInvalid);
result = solve(thermalmodel,tlist);
T = result.Temperature;
figure
subplot(2,1,1)
pdeplot(thermalmodel,"XYData",T(:,6),"Contour","on")
axis equal
title(sprintf("Temperature at %g s",tlist(6)))
subplot(2,1,2)
pdeplot(thermalmodel,"XYData",T(:,end),"Contour","on")
axis equal
title(sprintf("Temperature at %g s",tfinal))
5-693
5 Functions
function Q = heatSource(location,state)
Q = zeros(1,numel(location.x));
if(isnan(state.time))
% Returning a NaN when time=NaN tells
% the solver that the heat source is a function of time.
Q(1,:) = NaN;
return
end
if state.time < 500
Q(1,:) = 20000*state.time;
end
end
Input Arguments
thermalmodel — Thermal model
ThermalModel object
5-694
internalHeatSource
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
Geometric region ID, specified as a vector of positive integers. Find the region IDs by using
pdegplot.
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. For details, see “More About” on
page 5-695.
Example: internalHeatSource(thermalmodel,25)
Data Types: double | function_handle
Label for the internal heat source, specified as a character vector or a string.
Data Types: char | string
Output Arguments
heatSource — Handle to heat source
HeatSourceAssignment object
heatSourceValue associates the heat source value with the geometric region.
More About
Specifying Nonconstant Parameters of a Thermal Model
Use a function handle to specify these thermal parameters when they depend on space, temperature,
and time:
5-695
5 Functions
For example, use function handles to specify the thermal conductivity, internal heat source,
convection coefficient, and initial temperature for this model.
thermalProperties(model,"ThermalConductivity", ...
@myfunConductivity)
internalHeatSource(model,"Face",2,@myfunHeatSource)
thermalBC(model,"Edge",[3,4], ...
"ConvectionCoefficient",@myfunBC, ...
"AmbientTemperature",27)
thermalIC(model,@myfunIC)
For all parameters, except the initial temperature, the function must be of the form:
The solver computes and populates the data in the location and state structure arrays and passes
this data to your function. You can define your function so that its output depends on this data. You
can use any names instead of location and state, but the function must have exactly two
arguments (or one argument if the function specifies the initial temperature).
Furthermore, for boundary conditions, the solver passes these data in the location structure:
5-696
internalHeatSource
Thermal material properties (thermal conductivity, mass density, and specific heat) and internal heat
source get these data from the solver:
Boundary conditions (temperature on the boundary, heat flux, convection coefficient, and radiation
emissivity coefficient) get these data from the solver:
For all thermal parameters, except for thermal conductivity, your function must return a row vector
thermalVal with the number of columns equal to the number of evaluation points, for example, M =
length(location.y).
For thermal conductivity, your function must return a matrix thermalVal 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, for example, M =
length(location.y). For details about dimensions of the matrix, see “c Coefficient for
specifyCoefficients” on page 2-91.
If properties depend on the time or temperature, ensure that your function returns a matrix of NaN of
the correct size when state.u or state.time are NaN. Solvers check whether a problem is time
dependent by passing NaN state values and looking for returned NaN values.
To use additional arguments in your function, wrap your function (that takes additional arguments)
with an anonymous function that takes only the location and state arguments. For example:
thermalVal = ...
@(location,state) myfunWithAdditionalArgs(location,state,arg1,arg2...)
5-697
5 Functions
thermalBC(model,"Edge",3,"Temperature",thermalVal)
Version History
Introduced in R2017a
R2021b: Label to extract sparse linear models for use with Control System Toolbox
Now you can add a label for the internal heat source to be used by the linearizeInput function.
This function lets you pass internal heat sources to the linearize function that extracts sparse
linear models for use with Control System Toolbox.
See Also
thermalBC | thermalProperties | HeatSourceAssignment Properties
5-698
interpolateAcceleration
interpolateAcceleration
Package: pde
Interpolate acceleration at arbitrary spatial locations for all time or frequency steps for dynamic
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 or frequency
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-699
5 Functions
Specify Young's modulus, Poisson's ratio, and the 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.
structuralBC(structuralmodel,"Face",3,...
"YDisplacement",1E-4, ...
"Frequency",50);
Generate a mesh.
generateMesh(structuralmodel,"Hmax",0.01);
5-700
interpolateAcceleration
Input Arguments
structuralresults — Solution of dynamic structural analysis problem
TransientStructuralResults object | FrequencyStructuralResults object
5-701
5 Functions
[xq(i),yq(i),zq(i)]. Therefore, xq, yq, and (if present) zq must have the same number of
entries.
interpolateAcceleration converts the query points to column vectors xq(:), yq(:), and (if
present) zq(:). The function returns accelerations as an FEStruct object with the properties
containing vectors 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 intrpAccel = reshape(intrpAccel.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. interpolateAcceleration evaluates accelerations 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
intrpAccel — Accelerations at query points
FEStruct object
Accelerations at the query points, returned as an FEStruct object with the properties representing
spatial components of acceleration at the query points. For query points that are outside the
geometry, intrpAccel returns NaN. Properties of an FEStruct object are read-only.
Version History
Introduced in R2018a
5-702
interpolateAcceleration
See Also
StructuralModel | TransientStructuralResults | interpolateDisplacement |
interpolateVelocity | interpolateStress | interpolateStrain |
interpolateVonMisesStress | evaluateStress | evaluateStrain |
evaluateVonMisesStress | evaluateReaction | evaluatePrincipalStress |
evaluatePrincipalStrain
5-703
5 Functions
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 transient and
frequency response structural models, interpolateDisplacement returns the interpolated
displacement values for all time- or frequency-steps, respectively.
Examples
structuralmodel = createpde("structural","static-planestrain");
geometryFromEdges(structuralmodel,@squareg);
pdegplot(structuralmodel,"EdgeLabels","on")
axis equal
5-704
interpolateDisplacement
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-705
5 Functions
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.
gm = multicylinder([0.01,0.015],0.05);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,"FaceLabels","on", ...
"CellLabels","on", ...
"FaceAlpha",0.5)
5-706
interpolateDisplacement
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]);
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel)
structuralresults =
StaticStructuralResults with properties:
5-707
5 Functions
[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)))
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-708
interpolateDisplacement
Interpolate the displacement 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.
gm = multicuboid(0.06,0.005,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,"FaceLabels","on","FaceAlpha",0.5)
view(50,20)
5-709
5 Functions
Specify Young's modulus, Poisson's ratio, and the 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);
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);
5-710
interpolateDisplacement
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")
Input Arguments
structuralresults — Solution of structural analysis problem
StaticStructuralResults object | TransientStructuralResults object |
FrequencyStructuralResults object
5-711
5 Functions
interpolateDisplacement converts query points to column vectors xq(:), yq(:), and (if
present) zq(:). The function returns displacements as an FEStruct object with the properties
containing vectors 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 intrpDisp = reshape(intrpDisp.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. 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
FEStruct object
Displacements at the query points, returned as an FEStruct object with the properties representing
spatial components of displacement at the query points. For query points that are outside the
geometry, intrpDisp returns NaN. Properties of an FEStruct object are read-only.
5-712
interpolateDisplacement
Version History
Introduced in R2017b
For transient structural models, interpolateDisplacement interpolates displacement for all time-
steps.
See Also
StructuralModel | StaticStructuralResults | TransientStructuralResults |
interpolateVelocity | interpolateAcceleration | interpolateStress |
interpolateStrain | interpolateVonMisesStress | evaluateStress | evaluateStrain |
evaluateVonMisesStress | evaluateReaction | evaluatePrincipalStress |
evaluatePrincipalStrain
5-713
5 Functions
interpolateElectricField
Package: pde
Syntax
Eintrp = interpolateElectricField(results,xq,yq)
Eintrp = interpolateElectricField(results,xq,yq,zq)
Eintrp = interpolateElectricField(results,querypoints)
Description
Eintrp = interpolateElectricField(results,xq,yq) returns the interpolated electric field
values at the 2-D points specified in xq and yq.
Examples
emagmodel = createpde("electromagnetic","electrostatic");
Create a square geometry and include it in the model. Plot the geometry with the edge labels.
R1 = [3,4,-1,1,1,-1,1,1,-1,-1]';
g = decsg(R1,'R1',('R1')');
geometryFromEdges(emagmodel,g);
pdegplot(emagmodel,"EdgeLabels","on")
xlim([-1.5 1.5])
axis equal
5-714
interpolateElectricField
emagmodel.VacuumPermittivity = 8.8541878128E-12;
electromagneticProperties(emagmodel,"RelativePermittivity",1);
electromagneticBC(emagmodel,"Voltage",0,"Edge",[1 3]);
electromagneticBC(emagmodel,"Voltage",1000,"Edge",[2 4]);
electromagneticSource(emagmodel,"ChargeDensity",5E-9);
generateMesh(emagmodel);
R = solve(emagmodel);
pdeplot(emagmodel,"FlowData",[R.ElectricField.Ex ...
R.ElectricField.Ey])
axis equal
5-715
5 Functions
Interpolate the resulting electric field 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,51);
[X,Y] = meshgrid(v);
Eintrp = interpolateElectricField(R,X,Y)
Eintrp =
FEStruct with properties:
Reshape Eintrp.Ex and Eintrp.Ey and plot the resulting electric field.
EintrpX = reshape(Eintrp.Ex,size(X));
EintrpY = reshape(Eintrp.Ey,size(Y));
figure
quiver(X,Y,EintrpX,EintrpY,"Color","red")
5-716
interpolateElectricField
Alternatively, you can specify the grid by using a matrix of query points.
querypoints = [X(:),Y(:)]';
Eintrp = interpolateElectricField(R,querypoints);
emagmodel = createpde("electromagnetic","electrostatic");
importGeometry(emagmodel,"PlateHoleSolid.stl");
pdegplot(emagmodel,"FaceLabels","on","FaceAlpha",0.3)
5-717
5 Functions
emagmodel.VacuumPermittivity = 8.8541878128E-12;
electromagneticProperties(emagmodel,"RelativePermittivity",1);
electromagneticSource(emagmodel,"ChargeDensity",5E-9);
Apply the voltage boundary conditions on the side faces and the face bordering the hole.
electromagneticBC(emagmodel,"Voltage",0,"Face",3:6);
electromagneticBC(emagmodel,"Voltage",1000,"Face",7);
generateMesh(emagmodel);
R = solve(emagmodel)
R =
ElectrostaticResults with properties:
5-718
interpolateElectricField
pdeplot3D(emagmodel,"FlowData",[R.ElectricField.Ex ...
R.ElectricField.Ey ...
R.ElectricField.Ez])
Interpolate the resulting electric field to a grid covering the central portion of the geometry, for x, y,
and z.
x = linspace(3,7,7);
y = linspace(0,1,7);
z = linspace(8,12,7);
[X,Y,Z] = meshgrid(x,y,z);
Eintrp = interpolateElectricField(R,X,Y,Z)
Eintrp =
FEStruct with properties:
5-719
5 Functions
Input Arguments
results — Solution of electrostatic or DC conduction problem
ElectrostaticResults object | ConductionResults object
5-720
interpolateElectricField
interpolateElectricField converts the query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns electric field values as 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 EintrpX = reshape(Eintrp.Ex,size(xq)).
Example: xq = [0.5 0.5 0.75 0.75]
Data Types: double
interpolateElectricField converts the query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns electric field values as 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 EintrpY = reshape(Eintrp.Ey,size(yq)).
Example: yq = [1 2 0 0.5]
Data Types: double
interpolateElectricField converts the query points to column vectors xq(:), yq(:), and
zq(:). It returns electric field values as 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 EintrpZ = reshape(Eintrp.Ez,size(zq)).
Example: zq = [1 1 0 1.5]
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. interpolateElectricField evaluates the electric field at the coordinate points
querypoints(:,i) for every i, so each column of querypoints contains exactly one 2-D or 3-D
query point.
Example: For a 2-D geometry, querypoints = [0.5 0.5 0.75 0.75; 1 2 0 0.5]
Data Types: double
5-721
5 Functions
Output Arguments
Eintrp — Electric field at query points
FEStruct object
Electric field at query points, returned as an FEStruct object with the properties representing the
spatial components of the electric field at the query points. For query points that are outside the
geometry, Eintrp.Ex(i), Eintrp.Ey(i), and Eintrp.Ez(i) are NaN. Properties of an FEStruct
object are read-only.
Version History
Introduced in R2021a
The function now interpolates electric field in DC conduction results in addition to electrostatic
results.
See Also
solve | interpolateElectricFlux | interpolateElectricPotential |
interpolateCurrentDensity | ElectromagneticModel | ElectrostaticResults |
ConductionResults
5-722
interpolateElectricFlux
interpolateElectricFlux
Package: pde
Syntax
Dintrp = interpolateElectricFlux(electrostaticresults,xq,yq)
Dintrp = interpolateElectricFlux(electrostaticresults,xq,yq,zq)
Dintrp = interpolateElectricFlux(electrostaticresults,querypoints)
Description
Dintrp = interpolateElectricFlux(electrostaticresults,xq,yq) returns the
interpolated electric flux density at the 2-D points specified in xq and yq.
Examples
emagmodel = createpde("electromagnetic","electrostatic");
Create a square geometry and include it in the model. Plot the geometry with the edge labels.
R1 = [3,4,-1,1,1,-1,1,1,-1,-1]';
g = decsg(R1, 'R1', ('R1')');
geometryFromEdges(emagmodel,g);
pdegplot(emagmodel,"EdgeLabels","on")
xlim([-1.5 1.5])
axis equal
5-723
5 Functions
emagmodel.VacuumPermittivity = 8.8541878128E-12;
electromagneticProperties(emagmodel,"RelativePermittivity",1);
electromagneticBC(emagmodel,"Voltage",0,"Edge",[1 3]);
electromagneticBC(emagmodel,"Voltage",1000,"Edge",[2 4]);
electromagneticSource(emagmodel,"ChargeDensity",5E-9);
generateMesh(emagmodel);
R = solve(emagmodel);
pdeplot(emagmodel,"FlowData",[R.ElectricFluxDensity.Dx ...
R.ElectricFluxDensity.Dy])
axis equal
5-724
interpolateElectricFlux
Interpolate the resulting electric flux density 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,51);
[X,Y] = meshgrid(v);
Dintrp = interpolateElectricFlux(R,X,Y)
Dintrp =
FEStruct with properties:
Reshape Dintrp.Dx and Dintrp.Dy and plot the resulting electric flux density.
DintrpX = reshape(Dintrp.Dx,size(X));
DintrpY = reshape(Dintrp.Dy,size(Y));
figure
quiver(X,Y,DintrpX,DintrpY,"Color","red")
5-725
5 Functions
Alternatively, you can specify the grid by using a matrix of query points.
querypoints = [X(:),Y(:)]';
Dintrp = interpolateElectricFlux(R,querypoints);
emagmodel = createpde("electromagnetic","electrostatic");
importGeometry(emagmodel,"PlateHoleSolid.stl");
pdegplot(emagmodel,"FaceLabels","on","FaceAlpha",0.3)
5-726
interpolateElectricFlux
emagmodel.VacuumPermittivity = 8.8541878128E-12;
electromagneticProperties(emagmodel,"RelativePermittivity",1);
electromagneticSource(emagmodel,"ChargeDensity",5E-9);
Apply the voltage boundary conditions on the side faces and the face bordering the hole.
electromagneticBC(emagmodel,"Voltage",0,"Face",3:6);
electromagneticBC(emagmodel,"Voltage",1000,"Face",7);
generateMesh(emagmodel);
R = solve(emagmodel)
R =
ElectrostaticResults with properties:
5-727
5 Functions
pdeplot3D(emagmodel,"FlowData",[R.ElectricFluxDensity.Dx ...
R.ElectricFluxDensity.Dy ...
R.ElectricFluxDensity.Dz])
Interpolate the resulting electric flux density to a grid covering the central portion of the geometry,
for x, y, and z.
x = linspace(3,7,7);
y = linspace(0,1,7);
z = linspace(8,12,7);
[X,Y,Z] = meshgrid(x,y,z);
Dintrp = interpolateElectricFlux(R,X,Y,Z)
Dintrp =
FEStruct with properties:
5-728
interpolateElectricFlux
Input Arguments
electrostaticresults — Solution of electrostatic problem
ElectrostaticResults object
5-729
5 Functions
interpolateElectricFlux converts the query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns electric flux density as 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 DintrpX = reshape(Dintrp.Dx,size(xq)).
Example: xq = [0.5 0.5 0.75 0.75]
Data Types: double
interpolateElectricFlux converts the query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns electric flux density as 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 DintrpY = reshape(Dintrp.Dy,size(yq)).
Example: yq = [1 2 0 0.5]
Data Types: double
interpolateElectricFlux converts the query points to column vectors xq(:), yq(:), and
zq(:). It returns electric flux density values as 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 DintrpZ = reshape(Dintrp.Dz,size(zq)).
Example: zq = [1 1 0 1.5]
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. interpolateElectricFlux evaluates the electric flux density at the coordinate points
querypoints(:,i) for every i, so each column of querypoints contains exactly one 2-D or 3-D
query point.
Example: For a 2-D geometry, querypoints = [0.5 0.5 0.75 0.75; 1 2 0 0.5]
Data Types: double
5-730
interpolateElectricFlux
Output Arguments
Dintrp — Electric flux density at query points
FEStruct
Electric flux density at query points, returned as an FEStruct object with the properties
representing the spatial components of the electric flux density at the query points. For query points
that are outside the geometry, Dintrp.Dx(i), Dintrp.Dy(i), and Dintrp.Dz(i) are NaN.
Properties of an FEStruct object are read-only.
Version History
Introduced in R2021a
See Also
solve | interpolateElectricField | interpolateElectricPotential |
ElectromagneticModel | ElectrostaticResults
5-731
5 Functions
interpolateCurrentDensity
Package: pde
Syntax
Jintrp = interpolateCurrentDensity(results,xq,yq)
Jintrp = interpolateCurrentDensity(results,xq,yq,zq)
Jintrp = interpolateCurrentDensity(results,querypoints)
Description
Jintrp = interpolateCurrentDensity(results,xq,yq) returns the interpolated current
density values at the 2-D points specified in xq and yq.
Examples
model = createpde("electromagnetic","conduction");
importGeometry(model,"PlateHolePlanar.stl");
figure
pdegplot(model,"EdgeLabels","on");
5-732
interpolateCurrentDensity
electromagneticProperties(model,"Conductivity",6e4);
Apply the voltage boundary conditions on the top and bottom edges of the plate.
electromagneticBC(model,"Voltage",100,"Edge",3);
electromagneticBC(model,"Voltage",200,"Edge",2);
Specify the surface current density on the edge representing the hole.
electromagneticBC(model,"SurfaceCurrentDensity",200000,"Edge",5);
generateMesh(model);
R = solve(model);
figure
pdeplot(model,"XYData",R.ElectricPotential,"ColorMap","jet", ...
"FlowData",[R.CurrentDensity.Jx R.CurrentDensity.Jy])
axis equal
5-733
5 Functions
Interpolate the resulting current density to a grid covering the central portion of the geometry.
[X,Y] = meshgrid(2:0.25:8,8:0.25:12);
Jintrp = interpolateCurrentDensity(R,X,Y)
Jintrp =
FEStruct with properties:
Reshape Jintrp.Jx and Jintrp.Jy, and plot the resulting current density.
JintrpX = reshape(Jintrp.Jx,size(X));
JintrpY = reshape(Jintrp.Jy,size(Y));
quiver(X,Y,JintrpX,JintrpY,"Color","red")
axis equal
5-734
interpolateCurrentDensity
Alternatively, you can specify the grid by using a matrix of query points.
querypoints = [X(:),Y(:)]';
Jintrp = interpolateCurrentDensity(R,querypoints);
model = createpde("electromagnetic","conduction");
g = importGeometry(model,"Plate10x10x1.stl");
pdegplot(model,"FaceLabels","on","FaceAlpha",0.3)
5-735
5 Functions
electromagneticProperties(model,"Conductivity",6e4);
Apply the voltage boundary conditions on the two faces of the plate.
electromagneticBC(model,"Voltage",0,"Face",[1 3]);
electromagneticBC(model,"SurfaceCurrentDensity",100,"Face",5);
generateMesh(model);
R = solve(model);
figure
pdeplot3D(model,"ColorMapData",R.ElectricPotential)
5-736
interpolateCurrentDensity
figure
pdeplot3D(model,"FlowData",[R.CurrentDensity.Jx, ...
R.CurrentDensity.Jy, ...
R.CurrentDensity.Jz])
5-737
5 Functions
[X,Y,Z] = meshgrid(0:10,0:10,0:0.5:1);
Jintrp = interpolateCurrentDensity(R,X,Y,Z)
Jintrp =
FEStruct with properties:
JintrpX = reshape(Jintrp.Jx,size(X));
JintrpY = reshape(Jintrp.Jy,size(Y));
JintrpZ = reshape(Jintrp.Jz,size(Z));
figure
quiver3(X,Y,Z,JintrpX,JintrpY,JintrpZ,"Color","red")
5-738
interpolateCurrentDensity
Input Arguments
results — Solution of DC conduction problem
ConductionResults object
interpolateCurrentDensity converts the query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns current density values as 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 Jintrp = reshape(Jintrp,size(xq)).
Example: xq = [0.5 0.5 0.75 0.75]
Data Types: double
5-739
5 Functions
interpolateCurrentDensity converts the query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns current density values as 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 Jintrp = reshape(Jintrp,size(yq)).
Example: yq = [1 2 0 0.5]
Data Types: double
interpolateCurrentDensity converts the query points to column vectors xq(:), yq(:), and
zq(:). It returns current density values as 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 Jintrp = reshape(Jintrp,size(zq)).
Example: zq = [1 1 0 1.5]
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. interpolateCurrentDensity evaluates the current density at the coordinate points
querypoints(:,i) for every i, so each column of querypoints contains exactly one 2-D or 3-D
query point.
Example: For a 2-D geometry, querypoints = [0.5 0.5 0.75 0.75; 1 2 0 0.5]
Data Types: double
Output Arguments
Jintrp — Current density at query points
FEStruct object
Current density at query points, returned as an FEStruct object with the properties representing
the spatial components of the current density at the query points. For query points that are outside
the geometry, Jintrp.Jx(i), Jintrp.Jy(i), and Jintrp.Jz(i) are NaN. Properties of an
FEStruct object are read-only.
5-740
interpolateCurrentDensity
Version History
Introduced in R2022b
See Also
solve | interpolateElectricPotential | interpolateElectricField |
ElectromagneticModel | ConductionResults
5-741
5 Functions
interpolateHarmonicField
Package: pde
Syntax
EHintrp = interpolateHarmonicField(harmonicresults,xq,yq)
EHintrp = interpolateHarmonicField(harmonicresults,xq,yq,zq)
EHintrp = interpolateHarmonicField(harmonicresults,querypoints)
Description
EHintrp = interpolateHarmonicField(harmonicresults,xq,yq) returns the interpolated
electric or magnetic field values at the 2-D points specified in xq and yq.
Examples
Solve a simple scattering problem and interpolate the x-component of the resulting electric field. A
scattering problem computes the waves reflected by a square object illuminated by incident waves.
emagmodel = createpde("electromagnetic","harmonic");
k = 4*pi;
Represent the square surface with a diamond-shaped hole. Define a diamond in a square, place them
in one matrix, and create a set formula that subtracts the diamond from the square.
g = decsg(gd,sf,ns);
geometryFromEdges(emagmodel,g);
5-742
interpolateHarmonicField
Include the geometry in the model and plot it with the edge labels.
figure;
pdegplot(emagmodel,"EdgeLabels","on");
xlim([-6,6])
ylim([-6,6])
emagmodel.VacuumPermittivity = 1;
emagmodel.VacuumPermeability = 1;
Specify the relative permittivity, relative permeability, and conductivity of the material.
electromagneticProperties(emagmodel,"RelativePermittivity",1, ...
"RelativePermeability",1, ...
"Conductivity",0);
Apply the absorbing boundary condition on the edges of the square. Specify the thickness and
attenuation rate for the absorbing region by using the Thickness, Exponent, and Scaling
arguments.
5-743
5 Functions
Generate a mesh.
generateMesh(emagmodel,"Hmax",0.1);
Plot the real part of the x-component of the resulting electric field.
u = result.ElectricField;
figure
pdeplot(emagmodel,"XYData",real(u.Ex),"Mesh","off");
colormap(jet)
Interpolate the resulting electric field to a grid covering the portion of the geometry, for x and y from
-1 to 4.
v = linspace(-1,4,101);
[X,Y] = meshgrid(v);
Eintrp = interpolateHarmonicField(result,X,Y);
5-744
interpolateHarmonicField
Reshape Eintrp.Ex and plot the x-component of the resulting electric field.
EintrpX = reshape(Eintrp.ElectricField.Ex,size(X));
figure
surf(X,Y,real(EintrpX),"LineStyle","none");
view(0,90)
colormap(jet)
Interpolate the x-component of the magnetic field in a harmonic analysis of a 3-D model.
By default, the field type is electric. Use the FieldType property of the model to change the field
type to magnetic.
emagmodel.FieldType = "magnetic";
5-745
5 Functions
Specify the vacuum permittivity and permeability values in the SI system of units.
emagmodel.VacuumPermittivity = 8.8541878128E-12;
emagmodel.VacuumPermeability = 1.2566370614E-6;
Specify the relative permittivity, relative permeability, and conductivity of the material.
electromagneticProperties(emagmodel,"RelativePermittivity",1, ...
"RelativePermeability",6, ...
"Conductivity",60);
Specify the current density for the entire geometry. For harmonic analysis with the magnetic field
type, the toolbox uses the curl of the specified current density.
electromagneticSource(emagmodel,"CurrentDensity",[1;1;1]);
Apply the absorbing boundary condition with a thickness of 0.1 on the side faces.
electromagneticBC(emagmodel,"Face",3:6, ...
"FarField","absorbing", ...
"Thickness",0.1);
Specify the magnetic field on the face bordering the round hole in the center of the geometry.
electromagneticBC(emagmodel,"Face",7,"MagneticField",[1000;0;0]);
Generate a mesh.
generateMesh(emagmodel);
5-746
interpolateHarmonicField
result = solve(emagmodel,"Frequency",50);
Plot the real part of the x-component of the resulting magnetic field.
u = result.MagneticField;
figure
pdeplot3D(emagmodel,"ColorMapData",real(u.Hx));
colormap jet
xlabel 'x'
ylabel 'y'
title("Real Part of x-Component of Magnetic Field")
Interpolate the resulting magnetic field to a grid covering the central portion of the geometry, for x, y,
and z.
x = linspace(3,7,51);
y = linspace(0,1,51);
z = linspace(8,12,51);
[X,Y,Z] = meshgrid(x,y,z);
Hintrp = interpolateHarmonicField(result,X,Y,Z)
5-747
5 Functions
Reshape Hintrp.Hx and plot the x-component of the resulting magnetic field as a slice plot for y =
0.
HintrpX = reshape(Hintrp.MagneticField.Hx,size(X));
figure
slice(X,Y,Z,real(HintrpX),[],0,[],'cubic')
axis equal
colorbar
colormap(jet)
Alternatively, you can specify the grid by using a matrix of query points.
querypoints = [X(:),Y(:),Z(:)]';
Hintrp = interpolateHarmonicField(result,querypoints)
Input Arguments
harmonicresults — Solution of harmonic electromagnetic problem
HarmonicResults object
5-748
interpolateHarmonicField
interpolateHarmonicField converts the query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns electric or magnetic field values as 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 EHintrpX = reshape(EHintrp.Ex,size(xq)).
Example: xq = [0.5 0.5 0.75 0.75]
Data Types: double
interpolateHarmonicField converts the query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns electric or magnetic field values as 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 EHintrpY = reshape(EHintrp.Ey,size(yq)).
Example: yq = [1 2 0 0.5]
Data Types: double
interpolateHarmonicField converts the query points to column vectors xq(:), yq(:), and
zq(:). It returns electric or magnetic field values as 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 EHintrpZ = reshape(EHintrp.Ez,size(zq)).
Example: zq = [1 1 0 1.5]
Data Types: double
5-749
5 Functions
Query points, specified as a real matrix with either two rows for a 2-D geometry or three rows for a 3-
D geometry. interpolateHarmonicField evaluates the electric or magnetic field at the coordinate
points querypoints(:,i) for every index i, so each column of querypoints contains exactly one
2-D or 3-D query point.
Example: For a 2-D geometry, querypoints = [0.5 0.5 0.75 0.75; 1 2 0 0.5]
Data Types: double
Output Arguments
EHintrp — Electric or magnetic field at query points
FEStruct object
Electric or magnetic field at query points, returned as an FEStruct object with the properties
representing the spatial components of the electric or magnetic field at the query points. For query
points that are outside the geometry, EHintrp.Ex(i), EHintrp.Ey(i), EHintrp.Ez(i),
EHintrp.Hx(i), EHintrp.Hy(i), and EHintrp.Hz(i) are NaN. Properties of an FEStruct object
are read-only.
Version History
Introduced in R2022a
See Also
solve | ElectromagneticModel | HarmonicResults
5-750
interpolateElectricPotential
interpolateElectricPotential
Package: pde
Syntax
Vintrp = interpolateElectricPotential(results,xq,yq)
Vintrp = interpolateElectricPotential(results,xq,yq,zq)
Vintrp = interpolateElectricPotential(results,querypoints)
Description
Vintrp = interpolateElectricPotential(results,xq,yq) returns the interpolated electric
potential values at the 2-D points specified in xq and yq.
Examples
emagmodel = createpde("electromagnetic","electrostatic");
Create a square geometry and include it in the model. Plot the geometry with the edge labels.
R1 = [3,4,-1,1,1,-1,1,1,-1,-1]';
g = decsg(R1, 'R1', ('R1')');
geometryFromEdges(emagmodel,g);
pdegplot(emagmodel,"EdgeLabels","on")
xlim([-1.5 1.5])
axis equal
5-751
5 Functions
emagmodel.VacuumPermittivity = 8.8541878128E-12;
electromagneticProperties(emagmodel,"RelativePermittivity",1);
electromagneticBC(emagmodel,"Voltage",0,"Edge",[1 3]);
electromagneticBC(emagmodel,"Voltage",1000,"Edge",[2 4]);
electromagneticSource(emagmodel,"ChargeDensity",5E-9);
generateMesh(emagmodel);
R = solve(emagmodel);
pdeplot(emagmodel,"XYData",R.ElectricPotential, ...
"Contour","on")
axis equal
5-752
interpolateElectricPotential
Interpolate the resulting electric potential 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,51);
[X,Y] = meshgrid(v);
Vintrp = interpolateElectricPotential(R,X,Y)
Vintrp = 2601×1
602.2959
616.0368
629.0799
641.4304
653.0883
664.0538
674.4221
684.1447
693.2593
701.7856
⋮
figure
5-753
5 Functions
contourf(X,Y,Vintrp)
colormap(cool)
colorbar
Alternatively, you can specify the grid by using a matrix of query points.
querypoints = [X(:),Y(:)]';
Vintrp = interpolateElectricPotential(R,querypoints);
emagmodel = createpde("electromagnetic","electrostatic");
importGeometry(emagmodel,"PlateHoleSolid.stl");
pdegplot(emagmodel,"FaceLabels","on","FaceAlpha",0.3)
5-754
interpolateElectricPotential
emagmodel.VacuumPermittivity = 8.8541878128E-12;
electromagneticProperties(emagmodel,"RelativePermittivity",1);
electromagneticSource(emagmodel,"ChargeDensity",5E-9);
Apply the voltage boundary conditions on the side faces and the face bordering the hole.
electromagneticBC(emagmodel,"Voltage",0,"Face",3:6);
electromagneticBC(emagmodel,"Voltage",1000,"Face",7);
generateMesh(emagmodel);
R = solve(emagmodel)
R =
ElectrostaticResults with properties:
5-755
5 Functions
pdeplot3D(emagmodel,"ColorMapData",R.ElectricPotential)
Interpolate the resulting electric potential to a grid covering the entire geometry, for x, y, and z.
x = linspace(0,10,11);
y = linspace(0,1,5);
z = linspace(0,20,11);
[X,Y,Z] = meshgrid(x,y,z);
Vintrp = interpolateElectricPotential(R,X,Y,Z);
Reshape Vintrp.
Vintrp = reshape(Vintrp,size(X));
Plot the resulting electric potential as a contour slice plot for two values of the y-coordinate.
figure
contourslice(X,Y,Z,Vintrp,[],[0 1],[])
view([10,10,-10])
5-756
interpolateElectricPotential
axis equal
colorbar
Input Arguments
results — Solution of electrostatic or DC conduction problem
ElectrostaticResults object | ConductionResults object
interpolateElectricPotential converts the query points to column vectors xq(:), yq(:), and
(if present) zq(:). It returns electric potential values as 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 Vintrp = reshape(Vintrp,size(xq)).
5-757
5 Functions
interpolateElectricPotential converts the query points to column vectors xq(:), yq(:), and
(if present) zq(:). It returns electric potential values as 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 Vintrp = reshape(Vintrp,size(yq)).
Example: yq = [1 2 0 0.5]
Data Types: double
interpolateElectricPotential converts the query points to column vectors xq(:), yq(:), and
zq(:). It returns electric potential values as 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 Vintrp = reshape(Vintrp,size(zq)).
Example: zq = [1 1 0 1.5]
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. interpolateElectricPotential evaluates the electric potential at the coordinate
points querypoints(:,i) for every i, so each column of querypoints contains exactly one 2-D or
3-D query point.
Example: For a 2-D geometry, querypoints = [0.5 0.5 0.75 0.75; 1 2 0 0.5]
Data Types: double
Output Arguments
Vintrp — Electric potential at query points
vector
Electric potential at query points, returned as a vector. For query points that are outside the
geometry, Vintrp(i) = NaN.
5-758
interpolateElectricPotential
Version History
Introduced in R2021a
The function now interpolates electric potential in DC conduction results in addition to electrostatic
results.
See Also
solve | interpolateElectricField | interpolateElectricFlux |
interpolateCurrentDensity | ElectromagneticModel | ElectrostaticResults |
ConductionResults
5-759
5 Functions
interpolateMagneticField
Package: pde
Syntax
Hintrp = interpolateMagneticField(magnetostaticresults,xq,yq)
Hintrp = interpolateMagneticField(magnetostaticresults,xq,yq,zq)
Hintrp = interpolateMagneticField(magnetostaticresults,querypoints)
Description
Hintrp = interpolateMagneticField(magnetostaticresults,xq,yq) returns the
interpolated magnetic field values at the 2-D points specified in xq and yq.
Examples
emagmodel = createpde("electromagnetic","magnetostatic");
Create a square geometry and include it in the model. Plot the geometry with the edge labels.
R1 = [3,4,-1,1,1,-1,1,1,-1,-1]';
g = decsg(R1,'R1',('R1')');
geometryFromEdges(emagmodel,g);
pdegplot(emagmodel,"EdgeLabels","on")
xlim([-1.5 1.5])
axis equal
5-760
interpolateMagneticField
emagmodel.VacuumPermeability = 1.2566370614E-6;
electromagneticProperties(emagmodel,"RelativePermeability",5000);
Apply the magnetic potential boundary conditions on the boundaries of the square.
electromagneticBC(emagmodel,"MagneticPotential",0,"Edge",[1 3]);
electromagneticBC(emagmodel,"MagneticPotential",0.01,"Edge",[2 4]);
electromagneticSource(emagmodel,"CurrentDensity",0.5);
generateMesh(emagmodel);
R = solve(emagmodel);
pdeplot(emagmodel,"FlowData",[R.MagneticField.Hx ...
R.MagneticField.Hy])
axis equal
5-761
5 Functions
Interpolate the resulting magnetic field 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,51);
[X,Y] = meshgrid(v);
Hintrp = interpolateMagneticField(R,X,Y)
Hintrp =
FEStruct with properties:
Reshape Hintrp.Hx and Hintrp.Hy and plot the resulting electric field.
HintrpX = reshape(Hintrp.Hx,size(X));
HintrpY = reshape(Hintrp.Hy,size(Y));
figure
quiver(X,Y,HintrpX,HintrpY,"Color","red")
5-762
interpolateMagneticField
Alternatively, you can specify the grid by using a matrix of query points.
querypoints = [X(:),Y(:)]';
Hintrp = interpolateMagneticField(R,querypoints);
emagmodel = createpde("electromagnetic","magnetostatic");
importGeometry(emagmodel,"PlateHoleSolid.stl");
pdegplot(emagmodel,"FaceLabels","on","FaceAlpha",0.3)
5-763
5 Functions
emagmodel.VacuumPermeability = 1.2566370614E-6;
electromagneticProperties(emagmodel,"RelativePermeability",5000);
electromagneticSource(emagmodel,"CurrentDensity",[0;0;0.5]);
Apply the magnetic potential boundary conditions on the side faces and the face bordering the hole.
electromagneticBC(emagmodel,"MagneticPotential",[0;0;0],"Face",3:6);
electromagneticBC(emagmodel,"MagneticPotential",[0;0;0.01],"Face",7);
generateMesh(emagmodel,"GeometricOrder","linear");
R = solve(emagmodel)
R =
MagnetostaticResults with properties:
5-764
interpolateMagneticField
Interpolate the resulting magnetic field to a grid covering the central portion of the geometry, for x,
y, and z.
x = linspace(3,7,5);
y = linspace(0,1,5);
z = linspace(8,12,5);
[X,Y,Z] = meshgrid(x,y,z);
Hintrp = interpolateMagneticField(R,X,Y,Z)
Hintrp =
FEStruct with properties:
5-765
5 Functions
HintrpX = reshape(Hintrp.Hx,size(X));
HintrpY = reshape(Hintrp.Hy,size(Y));
HintrpZ = reshape(Hintrp.Hz,size(Z));
figure
quiver3(X,Y,Z,HintrpX,HintrpY,HintrpZ,"Color","red")
view([30 10])
view([10 15])
Input Arguments
magnetostaticresults — Solution of magnetostatic problem
MagnetostaticResults object
5-766
interpolateMagneticField
interpolateMagneticField converts the query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns magnetic field values as 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 HintrpX = reshape(Hintrp.Hx,size(xq)).
Example: xq = [0.5 0.5 0.75 0.75]
Data Types: double
interpolateMagneticField converts the query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns magnetic field values as 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 HintrpY = reshape(Hintrp.Hy,size(yq)).
Example: yq = [1 2 0 0.5]
Data Types: double
interpolateMagneticField converts the query points to column vectors xq(:), yq(:), and
zq(:). It returns magnetic field values as 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 HintrpZ = reshape(Hintrp.Hz,size(zq)).
Example: zq = [1 1 0 1.5]
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. interpolateMagneticField evaluates magnetic field at the coordinate points
querypoints(:,i) for every i, so each column of querypoints contains exactly one 2-D or 3-D
query point.
Example: For a 2-D geometry, querypoints = [0.5 0.5 0.75 0.75; 1 2 0 0.5]
Data Types: double
5-767
5 Functions
Output Arguments
Hintrp — Magnetic field at query points
FEStruct
Magnetic field at query points, returned as an FEStruct object with the properties representing the
spatial components of the magnetic field at the query points. For query points that are outside the
geometry, Hintrp.Hx(i), Hintrp.Hy(i), and Hintrp.Hz(i) are NaN. Properties of an FEStruct
object are read-only.
Version History
Introduced in R2021a
See Also
solve | interpolateMagneticFlux | interpolateMagneticPotential |
ElectromagneticModel | MagnetostaticResults
5-768
interpolateMagneticFlux
interpolateMagneticFlux
Package: pde
Syntax
Bintrp = interpolateMagneticFlux(magnetostaticresults,xq,yq)
Bintrp = interpolateMagneticFlux(magnetostaticresults,xq,yq,zq)
Bintrp = interpolateMagneticFlux(magnetostaticresults,querypoints)
Description
Bintrp = interpolateMagneticFlux(magnetostaticresults,xq,yq) returns the
interpolated magnetic flux density at the 2-D points specified in xq and yq.
Examples
emagmodel = createpde("electromagnetic","magnetostatic");
Create a square geometry and include it in the model. Plot the geometry with the edge labels.
R1 = [3,4,-1,1,1,-1,1,1,-1,-1]';
g = decsg(R1,'R1',('R1')');
geometryFromEdges(emagmodel,g);
pdegplot(emagmodel,"EdgeLabels","on")
xlim([-1.5 1.5])
axis equal
5-769
5 Functions
emagmodel.VacuumPermeability = 1.2566370614E-6;
electromagneticProperties(emagmodel,"RelativePermeability",5000);
Apply the magnetic potential boundary conditions on the boundaries of the square.
electromagneticBC(emagmodel,"MagneticPotential",0,"Edge",[1 3]);
electromagneticBC(emagmodel,"MagneticPotential",0.01,"Edge",[2 4]);
electromagneticSource(emagmodel,"CurrentDensity",0.5);
generateMesh(emagmodel);
R = solve(emagmodel);
pdeplot(emagmodel,"FlowData",[R.MagneticFluxDensity.Bx ...
R.MagneticFluxDensity.By])
axis equal
5-770
interpolateMagneticFlux
Interpolate the resulting electric flux density 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,51);
[X,Y] = meshgrid(v);
Bintrp = interpolateMagneticFlux(R,X,Y)
Bintrp =
FEStruct with properties:
Reshape Bintrp.Bx and Bintrp.By and plot the resulting magnetic flux density.
BintrpX = reshape(Bintrp.Bx,size(X));
BintrpY = reshape(Bintrp.By,size(Y));
figure
quiver(X,Y,BintrpX,BintrpY,"Color","red")
5-771
5 Functions
Alternatively, you can specify the grid by using a matrix of query points.
querypoints = [X(:),Y(:)]';
Bintrp = interpolateMagneticFlux(R,querypoints);
emagmodel = createpde("electromagnetic","magnetostatic");
importGeometry(emagmodel,"PlateHoleSolid.stl");
pdegplot(emagmodel,"FaceLabels","on","FaceAlpha",0.3)
5-772
interpolateMagneticFlux
emagmodel.VacuumPermeability = 1.2566370614E-6;
electromagneticProperties(emagmodel,"RelativePermeability",5000);
electromagneticSource(emagmodel,"CurrentDensity",[0;0;0.5]);
Apply the magnetic potential boundary conditions on the side faces and the face bordering the hole.
electromagneticBC(emagmodel,"MagneticPotential",[0;0;0],"Face",3:6);
electromagneticBC(emagmodel,"MagneticPotential",[0;0;0.01],"Face",7);
Generate a mesh.
generateMesh(emagmodel);
R = solve(emagmodel)
R =
MagnetostaticResults with properties:
5-773
5 Functions
Interpolate the resulting magnetic flux density to a grid covering the central portion of the geometry,
for x, y, and z.
x = linspace(3,7,5);
y = linspace(0,1,5);
z = linspace(8,12,5);
[X,Y,Z] = meshgrid(x,y,z);
Bintrp = interpolateMagneticFlux(R,X,Y,Z)
Bintrp =
FEStruct with properties:
5-774
interpolateMagneticFlux
BintrpX = reshape(Bintrp.Bx,size(X));
BintrpY = reshape(Bintrp.By,size(Y));
BintrpZ = reshape(Bintrp.Bz,size(Z));
figure
quiver3(X,Y,Z,BintrpX,BintrpY,BintrpZ,"Color","red")
view([30 10])
view([10 15])
Input Arguments
magnetostaticresults — Solution of magnetostatic problem
MagnetostaticResults object
5-775
5 Functions
interpolateMagneticFlux converts the query points to column vectors xq(:) and yq(:). It
returns magnetic flux density as 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 BintrpX = reshape(Bintrp.Bx,size(xq)).
Example: xq = [0.5 0.5 0.75 0.75]
Data Types: double
interpolateMagneticFlux converts the query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns magnetic flux density as 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 BintrpY = reshape(Bintrp.By,size(yq)).
Example: yq = [1 2 0 0.5]
Data Types: double
interpolateMagneticFlux converts the query points to column vectors xq(:), yq(:), and
zq(:). It returns magnetic flux density values as 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 BintrpZ = reshape(Bintrp.Bz,size(zq)).
Example: zq = [1 1 0 1.5]
Data Types: double
Query points, specified as a real matrix with two rows for 2-D geometry or three rows for 3-D
geometry. interpolateMagneticFlux evaluates the magnetic flux density at the coordinate points
querypoints(:,i) for every i, so each column of querypoints contains exactly one 2-D or 3-D
query point.
Example: For a 2-D geometry, querypoints = [0.5 0.5 0.75 0.75; 1 2 0 0.5]
Data Types: double
5-776
interpolateMagneticFlux
Output Arguments
Bintrp — Magnetic flux density at query points
FEStruct
Magnetic flux density at query points, returned as an FEStruct object with the properties
representing the spatial components of the magnetic flux density at the query points. For query
points that are outside the geometry, Bintrp.Bx(i), Bintrp.By(i), and Bintrp.Bz(i) are NaN.
Properties of an FEStruct object are read-only.
Version History
Introduced in R2021a
See Also
solve | interpolateMagneticField | interpolateMagneticPotential |
ElectromagneticModel | MagnetostaticResults
5-777
5 Functions
interpolateMagneticPotential
Package: pde
Syntax
Aintrp = interpolateMagneticPotential(magnetostaticresults,xq,yq)
Aintrp = interpolateMagneticPotential(magnetostaticresults,xq,yq,zq)
Aintrp = interpolateMagneticPotential(magnetostaticresults,querypoints)
Description
Aintrp = interpolateMagneticPotential(magnetostaticresults,xq,yq) returns the
interpolated magnetic potential values at the 2-D points specified in xq and yq.
Examples
emagmodel = createpde("electromagnetic","magnetostatic");
Create a square geometry and include it in the model. Plot the geometry with the edge labels.
R1 = [3,4,-1,1,1,-1,1,1,-1,-1]';
g = decsg(R1,'R1',('R1')');
geometryFromEdges(emagmodel,g);
pdegplot(emagmodel,"EdgeLabels","on")
xlim([-1.5 1.5])
axis equal
5-778
interpolateMagneticPotential
emagmodel.VacuumPermeability = 1.2566370614E-6;
electromagneticProperties(emagmodel,"RelativePermeability",5000);
Apply the magnetic potential boundary conditions on the boundaries of the square.
electromagneticBC(emagmodel,"MagneticPotential",0,"Edge",[1 3]);
electromagneticBC(emagmodel,"MagneticPotential",0.01,"Edge",[2 4]);
electromagneticSource(emagmodel,"CurrentDensity",0.5);
generateMesh(emagmodel);
R = solve(emagmodel);
pdeplot(emagmodel,"XYData",R.MagneticPotential, ...
"Contour","on")
axis equal
5-779
5 Functions
Interpolate the resulting magnetic potential 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,51);
[X,Y] = meshgrid(v);
Aintrp = interpolateMagneticPotential(R,X,Y)
Aintrp = 2601×1
0.0056
0.0057
0.0058
0.0059
0.0060
0.0061
0.0062
0.0063
0.0064
0.0065
⋮
Aintrp = reshape(Aintrp,size(X));
figure
contourf(X,Y,Aintrp)
5-780
interpolateMagneticPotential
colormap(cool)
colorbar
Alternatively, you can specify the grid by using a matrix of query points.
querypoints = [X(:),Y(:)]';
Aintrp = interpolateMagneticPotential(R,querypoints);
emagmodel = createpde("electromagnetic","magnetostatic");
importGeometry(emagmodel,"PlateHoleSolid.stl");
pdegplot(emagmodel,"FaceLabels","on","FaceAlpha",0.3)
5-781
5 Functions
emagmodel.VacuumPermeability = 1.2566370614E-6;
electromagneticProperties(emagmodel,"RelativePermeability",5000);
electromagneticSource(emagmodel,"CurrentDensity",[0;0;0.5]);
Apply the magnetic potential boundary conditions on the side faces and the face bordering the hole.
electromagneticBC(emagmodel,"MagneticPotential",[0;0;0],"Face",3:6);
electromagneticBC(emagmodel,"MagneticPotential",[0;0;0.01],"Face",7);
generateMesh(emagmodel);
R = solve(emagmodel)
R =
MagnetostaticResults with properties:
5-782
interpolateMagneticPotential
Interpolate the resulting magnetic potential to a grid covering the entire geometry, for x, y, and z.
x = linspace(0,10,11);
y = linspace(0,1,5);
z = linspace(0,20,11);
[X,Y,Z] = meshgrid(x,y,z);
Aintrp = interpolateMagneticPotential(R,X,Y,Z)
Aintrp =
FEStruct with properties:
Reshape Aintrp.Ax, Aintrp.Ay, and Aintrp.Az to match the shape of the input grid.
5-783
5 Functions
AintrpX = reshape(Aintrp.Ax,size(X));
AintrpY = reshape(Aintrp.Ay,size(Y));
AintrpZ = reshape(Aintrp.Az,size(Z));
Input Arguments
magnetostaticresults — Solution of magnetostatic problem
MagnetostaticResults object
5-784
interpolateMagneticPotential
interpolateMagneticPotential converts query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns magnetic potential values as 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 Aintrp = reshape(Aintrp,size(xq)).
Example: xq = [0.5 0.5 0.75 0.75]
Data Types: double
interpolateMagneticPotential converts query points to column vectors xq(:), yq(:), and (if
present) zq(:). It returns magnetic potential values as 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 Aintrp = reshape(Aintrp,size(yq)).
Example: yq = [1 2 0 0.5]
Data Types: double
interpolateMagneticPotential converts the query points to column vectors xq(:), yq(:), and
zq(:). It returns magnetic potential values as 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 Aintrp = reshape(Aintrp,size(zq)).
Example: zq = [1 1 0 1.5]
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. interpolateMagneticPotential evaluates the magnetic potential at the coordinate
points querypoints(:,i) for every i, so each column of querypoints contains exactly one 2-D or
3-D query point.
Example: For a 2-D geometry, querypoints = [0.5 0.5 0.75 0.75; 1 2 0 0.5]
Data Types: double
Output Arguments
Aintrp — Magnetic potential at query points
vector | FEStruct object
5-785
5 Functions
Magnetic potential at query points, returned as a vector for a 2-D problem or an FEStruct object for
a 3-D problem. The properties of FEStruct contain the components of the magnetic potential at
query points. For query points i that are outside the geometry, Aintrp(i), Aintrp.Ax(i),
Aintrp.Ay(i), and Aintrp.Az(i) are NaN. Properties of an FEStruct object are read-only.
Version History
Introduced in R2021a
See Also
solve | interpolateMagneticField | interpolateMagneticFlux | ElectromagneticModel |
MagnetostaticResults
5-786
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.
uintrp = interpolateSolution( ___ ,iT) returns the interpolated values of the solution to the
time-dependent or eigenvalue equation or system of such equations at times or modal indices iT. For
a system of time-dependent or eigenvalue equations, specify both time/modal indices iT and equation
indices iU
Examples
Interpolate the solution to a scalar problem along a line and plot the result.
Create the solution to the problem −Δu = 1 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,...
5-787
5 Functions
"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)")
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.
5-788
interpolateSolution
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(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-789
5 Functions
Solve a scalar stationary problem and interpolate the solution to a dense grid.
Create the solution to the problem −Δu = 1 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);
v = linspace(-1,1,101);
[X,Y] = meshgrid(v);
querypoints = [X(:),Y(:)]';
uintrp = interpolateSolution(results,querypoints);
5-790
interpolateSolution
uintrp = reshape(uintrp,size(X));
mesh(X,Y,uintrp)
xlabel("x")
ylabel("y")
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-791
5 Functions
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]);
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]);
5-792
interpolateSolution
sol1 = reshape(uintrp(:,1),size(X));
sol2 = reshape(uintrp(:,2),size(X));
figure
surf(X,Z,sol1)
title("Component 1")
figure
surf(X,Z,sol2)
title("Component 2")
5-793
5 Functions
model = createpde(1);
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);
r = [0,100];
generateMesh(model,"Hmax",1/50);
results = solvepdeeig(model,r);
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);
5-794
interpolateSolution
uintrp = reshape(uintrp,size(xq));
surf(xq,yq,uintrp)
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-795
5 Functions
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 “Linear Elasticity Equations” on page 3-194.
E = 200e9;
nu = 0.3;
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);
5-796
interpolateSolution
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-797
5 Functions
Input Arguments
results — PDE solution
StationaryResults object (default) | TimeDependentResults object | EigenResults object
x-coordinate query points, specified as a real array. interpolateSolution evaluates the solution at
the 2-D coordinate points [xq(i),yq(i)] or at the 3-D coordinate points [xq(i),yq(i),zq(i)].
So xq, yq, and (if present) zq must have the same number of entries.
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
y-coordinate query points, specified as a real array. interpolateSolution evaluates the solution at
the 2-D coordinate points [xq(i),yq(i)] or at the 3-D coordinate points [xq(i),yq(i),zq(i)].
So xq, yq, and (if present) zq must have the same number of entries. Internally,
interpolateSolution converts query points to the column vector yq(:).
Data Types: double
z-coordinate query points, specified as a real array. interpolateSolution evaluates the solution at
the 3-D coordinate points [xq(i),yq(i),zq(i)]. So xq, yq, and zq must have the same number of
entries. Internally, interpolateSolution converts query points to the column vector 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. 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.
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
5-798
interpolateSolution
Equation indices, specified as a vector of positive integers. Each entry in iU specifies an equation
index.
Example: iU = [1,5] specifies the indices for the first and fifth equations.
Data Types: double
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-429.
Version History
Introduced in R2015b
See Also
PDEModel | StationaryResults | TimeDependentResults | evaluateGradient
Topics
“Solution and Gradient Plots with pdeplot and pdeplot3D” on page 3-376
“3-D Solution and Gradient Plots with MATLAB Functions” on page 3-391
“Dimensions of Solutions, Gradients, and Fluxes” on page 3-429
5-799
5 Functions
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 transient and frequency-response
structural models, interpolateStrain interpolates strain for all time- or frequency-steps,
respectively.
Examples
structuralmodel = createpde("structural","static-planestrain");
geometryFromEdges(structuralmodel,@squareg);
pdegplot(structuralmodel,"EdgeLabels","on")
axis equal
5-800
interpolateStrain
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);
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);
5-801
5 Functions
px.EdgeColor="none";
colorbar
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-802
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.
gm = multicylinder([0.01,0.015],0.05);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,"FaceLabels","on", ...
"CellLabels","on", ...
"FaceAlpha",0.5)
5-803
5 Functions
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]);
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel)
structuralresults =
StaticStructuralResults with properties:
5-804
interpolateStrain
[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)))
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-805
5 Functions
Interpolate the strain at the geometric center of a beam under a 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-806
interpolateStrain
Specify Young's modulus, Poisson's ratio, and the 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.
structuralBC(structuralmodel,"Face",3, ...
"YDisplacement",1E-4, ...
"Frequency",50);
Generate a mesh.
generateMesh(structuralmodel,"Hmax",0.01);
5-807
5 Functions
coordsMidSpan = [0;0;0.005];
intrpStrain = interpolateStrain(structuralresults,coordsMidSpan);
figure
plot(structuralresults.SolutionTimes,intrpStrain.exx)
title("X-Direction Normal Strain at Beam Center")
Input Arguments
structuralresults — Solution of structural analysis problem
StaticStructuralResults object | TransientStructuralResults object |
FrequencyStructuralResults object
5-808
interpolateStrain
x-coordinate query points, specified as a real array. interpolateStrain evaluates the strains at the
2-D coordinate points [xq(i),yq(i)] or at the 3-D coordinate points [xq(i),yq(i),zq(i)].
Therefore, xq, yq, and (if present) zq must have the same number of entries.
interpolateStrain converts query points to column vectors xq(:), yq(:), and (if present)
zq(:). The function returns strains as an FEStruct object with the properties containing vectors 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
y-coordinate query points, specified as a real array. interpolateStrain evaluates the strains at the
2-D coordinate points [xq(i),yq(i)] or at the 3-D coordinate points [xq(i),yq(i),zq(i)].
Therefore, xq, yq, and (if present) zq must have the same number of entries. Internally,
interpolateStrain converts the query points to the column vector yq(:).
Data Types: double
z-coordinate query points, specified as a real array. interpolateStrain evaluates the strains at the
3-D coordinate points [xq(i),yq(i),zq(i)]. Therefore, xq, yq, and zq must have the same
number of entries. Internally, interpolateStrain converts the query points to the column vector
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. 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.
Example: For 2-D geometry, querypoints = [0.5,0.5,0.75,0.75; 1,2,0,0.5]
Data Types: double
Output Arguments
intrpStrain — Strains at query points
FEStruct object
Strains at the query points, returned as an FEStruct object with the properties representing spatial
components of strain at the query points. For query points that are outside the geometry,
intrpStrain returns NaN. Properties of an FEStruct object are read-only.
Version History
Introduced in R2017b
5-809
5 Functions
For frequency response structural models, interpolateStrain interpolates strain for all
frequency-steps.
For transient structural models, interpolateStrain interpolates strain for all time-steps.
See Also
StructuralModel | StaticStructuralResults | interpolateDisplacement |
interpolateStress | interpolateVonMisesStress | evaluateReaction |
evaluatePrincipalStress | evaluatePrincipalStrain
5-810
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 transient and frequency-response
structural models, interpolateStress interpolates stress for all time- or frequency-steps,
respectively.
Examples
structuralmodel = createpde("structural","static-planestrain");
geometryFromEdges(structuralmodel,@squareg);
pdegplot(structuralmodel,"EdgeLabels","on")
axis equal
5-811
5 Functions
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);
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);
5-812
interpolateStress
px.EdgeColor="none";
colorbar
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-813
5 Functions
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.
gm = multicylinder([0.01,0.015],0.05);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,"FaceLabels","on", ...
"CellLabels","on", ...
"FaceAlpha",0.5)
5-814
interpolateStress
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]);
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel)
structuralresults =
StaticStructuralResults with properties:
5-815
5 Functions
[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)))
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-816
interpolateStress
Interpolate the stress at the geometric center of a beam under a 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-817
5 Functions
Specify Young's modulus, Poisson's ratio, and the 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.
structuralBC(structuralmodel,"Face",3, ...
"YDisplacement",1E-4, ...
"Frequency",50);
Generate a mesh.
generateMesh(structuralmodel,"Hmax",0.01);
5-818
interpolateStress
coordsMidSpan = [0;0;0.005];
intrpStress = interpolateStress(structuralresults,coordsMidSpan);
figure
plot(structuralresults.SolutionTimes,intrpStress.sxx)
title("X-Direction Normal Stress at Beam Center")
Input Arguments
structuralresults — Solution of structural analysis problem
StaticStructuralResults object | TransientStructuralResults object |
FrequencyStructuralResults object
5-819
5 Functions
x-coordinate query points, specified as a real array. interpolateStress evaluates the stresses at
the 2-D coordinate points [xq(i),yq(i)] or at the 3-D coordinate points [xq(i),yq(i),zq(i)].
Therefore, xq, yq, and (if present) zq must have the same number of entries.
interpolateStress converts the query points to column vectors xq(:), yq(:), and (if present)
zq(:). It returns stresses as an FEStruct object with the properties containing vectors 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
y-coordinate query points, specified as a real array. interpolateStress evaluates the stresses at
the 2-D coordinate points [xq(i),yq(i)] or at the 3-D coordinate points [xq(i),yq(i),zq(i)].
Therefore, xq, yq, and (if present) zq must have the same number of entries. Internally,
interpolateStress converts the query points to the column vector yq(:).
Data Types: double
z-coordinate query points, specified as a real array. interpolateStress evaluates the stresses at
the 3-D coordinate points [xq(i),yq(i),zq(i)]. Therefore, xq, yq, and zq must have the same
number of entries. Internally, interpolateStress converts the query points to the column vector
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. interpolateStress evaluates stresses 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
intrpStress — Stresses at query points
FEStruct object
Stresses at the query points, returned as an FEStruct object with the properties representing
spatial components of stress at the query points. For query points that are outside the geometry,
intrpStress returns NaN. Properties of an FEStruct object are read-only.
Version History
Introduced in R2017b
5-820
interpolateStress
For frequency response structural models, interpolateStress interpolates stress for all
frequency-steps.
For transient structural models, interpolateStress interpolates stress for all time-steps.
See Also
StructuralModel | StaticStructuralResults | interpolateDisplacement |
interpolateStrain | interpolateVonMisesStress | evaluateReaction |
evaluatePrincipalStress | evaluatePrincipalStrain
5-821
5 Functions
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 for a steady-state thermal model.
Tintrp = interpolateTemperature( ___ ,iT) returns the interpolated temperature values for
the transient thermal model at times iT.
Examples
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-822
interpolateTemperature
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.
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);
results =
SteadyStateThermalResults with properties:
5-823
5 Functions
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");
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)
colormap(hot)
colorbar
5-824
interpolateTemperature
Alternatively, you can specify the grid by using a matrix of query points.
querypoints = [X(:),Y(:)]';
Tintrp = interpolateTemperature(results,querypoints);
thermalmodel = createpde("thermal");
importGeometry(thermalmodel,"Block.stl");
pdegplot(thermalmodel,"FaceLabels","on","FaceAlpha",0.5)
title("Copper block, cm")
axis equal
5-825
5 Functions
Assuming that this is a copper block, the thermal conductivity of the block is approximately 4 W/
(cm*K).
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 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:
5-826
interpolateTemperature
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)
Create a grid specified by x, y, and z coordinates and interpolate temperatures to the grid.
[X,Y,Z] = meshgrid(1:16:100,1:6:20,1:7:50);
Tintrp = interpolateTemperature(thermalresults,X,Y,Z);
Tintrp = reshape(Tintrp,size(X));
contourslice(X,Y,Z,Tintrp,[],1:6:20,[])
xlabel("x")
ylabel("y")
zlabel("z")
xlim([1,100])
ylim([1,20])
5-827
5 Functions
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);
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-828
interpolateTemperature
Solve a 2-D transient heat transfer problem on a square domain and compute temperatures at the
convective boundary.
thermalmodel = createpde("thermal","transient");
g = @squareg;
geometryFromEdges(thermalmodel,g);
pdegplot(thermalmodel,"EdgeLabels","on")
xlim([-1.2,1.2])
ylim([-1.2,1.2])
axis equal
5-829
5 Functions
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.
5-830
interpolateTemperature
generateMesh(thermalmodel);
tlist = 0:1000:200000;
thermalresults = solve(thermalmodel,tlist);
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.
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-831
5 Functions
Input Arguments
thermalresults — Solution of thermal problem
SteadyStateThermalResults object | TransientThermalResults object
interpolateTemperature converts query points to column vectors xq(:), yq(:), and (if present)
zq(:). It returns temperatures in the 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 Tintrp = reshape(Tintrp,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. 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.
5-832
interpolateTemperature
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.
Version History
Introduced in R2017a
See Also
ThermalModel | SteadyStateThermalResults | TransientThermalResults |
evaluateHeatFlux | evaluateHeatRate | evaluateTemperatureGradient
Topics
“Dimensions of Solutions, Gradients, and Fluxes” on page 3-429
5-833
5 Functions
interpolateVelocity
Package: pde
Interpolate velocity at arbitrary spatial locations for all time or frequency steps for dynamic
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 or frequency 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-834
interpolateVelocity
Specify Young's modulus, Poisson's ratio, and the 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.
structuralBC(structuralmodel,"Face",3, ...
"YDisplacement",1E-4, ...
"Frequency",50);
Generate a mesh.
generateMesh(structuralmodel,"Hmax",0.01);
5-835
5 Functions
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")
Input Arguments
structuralresults — Solution of dynamic structural analysis problem
TransientStructuralResults object | FrequencyStructuralResults object
5-836
interpolateVelocity
interpolateVelocity converts query points to column vectors xq(:), yq(:), and (if present)
zq(:). It returns velocities as an FEStruct object with the properties containing vectors 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.
Example: For 2-D geometry, querypoints = [0.5,0.5,0.75,0.75; 1,2,0,0.5]
Data Types: double
Output Arguments
intrpVel — Velocities at query points
FEStruct object
Velocities at the query points, returned as an FEStruct object with the properties representing
spatial components of velocity at the query points. For query points that are outside the geometry,
intrpVel returns NaN. Properties of an FEStruct object are read-only.
Version History
Introduced in R2018a
5-837
5 Functions
See Also
StructuralModel | TransientStructuralResults | interpolateDisplacement |
interpolateAcceleration | interpolateStress | interpolateStrain |
interpolateVonMisesStress | evaluateStress | evaluateStrain |
evaluateVonMisesStress | evaluateReaction | evaluatePrincipalStress |
evaluatePrincipalStrain
5-838
interpolateVonMisesStress
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 transient and
frequency-response structural models, interpolateVonMisesStress interpolates von Mises stress
for all time- or frequency-steps, respectively.
Examples
structuralmodel = createpde("structural","static-planestrain");
geometryFromEdges(structuralmodel,@squareg);
pdegplot(structuralmodel,"EdgeLabels","on")
axis equal
5-839
5 Functions
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);
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);
5-840
interpolateVonMisesStress
p.EdgeColor="none";
colorbar
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.
gm = multicylinder([0.01,0.015],0.05);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,"FaceLabels","on", ...
"CellLabels","on", ...
"FaceAlpha",0.5)
5-841
5 Functions
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]);
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel)
structuralresults =
StaticStructuralResults with properties:
5-842
interpolateVonMisesStress
[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)))
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-843
5 Functions
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.
gm = multicuboid(0.06,0.005,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,"FaceLabels","on","FaceAlpha",0.5)
view(50,20)
5-844
interpolateVonMisesStress
Specify Young's modulus, Poisson's ratio, and the 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.
structuralBC(structuralmodel,"Face",3, ...
"YDisplacement",1E-4, ...
"Frequency",50);
Generate a mesh.
generateMesh(structuralmodel,"Hmax",0.01);
5-845
5 Functions
Interpolate the von Mises stress at the geometric center of the beam.
coordsMidSpan = [0;0;0.005];
VMStress = interpolateVonMisesStress(structuralresults,coordsMidSpan);
Plot the von Mises stress at the geometric center of the beam.
figure
plot(structuralresults.SolutionTimes,VMStress)
title("von Mises Stress at Beam Center")
Input Arguments
structuralresults — Solution of structural analysis problem
StaticStructuralResults object | TransientStructuralResults object |
FrequencyStructuralResults object
5-846
interpolateVonMisesStress
interpolateVonMisesStress converts query points to column vectors xq(:), yq(:), and (if
present) zq(:). The function returns von Mises stress as a column vector of the same size as the
query point 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
intrpVMStress = reshape(intrpVMStress,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. interpolateVonMisesStress evaluates the von Mises stress 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
intrpVMStress — von Mises stress at query points
column vector
For query points that are outside the geometry, intrpVMStress = NaN.
5-847
5 Functions
Version History
Introduced in R2017b
For transient structural models, interpolateVonMisesStress interpolates von Mises stress for all
time-steps.
See Also
StructuralModel | StaticStructuralResults | interpolateDisplacement |
interpolateStress | interpolateStrain | evaluateReaction | evaluatePrincipalStress
| evaluatePrincipalStrain
5-848
jigglemesh
jigglemesh
Package: 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 generateMesh.
Syntax
p1 = jigglemesh(p,e,t)
p1 = jigglemesh(p,e,t,Name,Value)
Description
p1 = jigglemesh(p,e,t) jiggles the triangular mesh by adjusting the node point positions.
Typically, the quality of the mesh increases after jiggling.
Examples
Jiggle Mesh
Create a triangular mesh of the square geometry by using initmesh. To avoid jiggling, call
initimesh with the Jiggle value set to off.
[p,e,t] = initmesh("lshapeg","Jiggle","off");
q = pdetriq(p,t);
pdeplot(p,e,t,"XYData",q,"ColorBar","on","XYStyle","flat")
5-849
5 Functions
Jiggle the mesh using the default parameter values. Plot the result.
p1 = jigglemesh(p,e,t);
q = pdetriq(p1,t);
pdeplot(p1,e,t,"XYData",q,"ColorBar","on","XYStyle","flat")
5-850
jigglemesh
Now jiggle the original mesh again, this time using 50000 iterations.
p2 = jigglemesh(p,e,t,"Opt","off","Iter",5e4);
q = pdetriq(p2,t);
pdeplot(p2,e,t,"XYData",q,"ColorBar","on","XYStyle","flat")
5-851
5 Functions
Input Arguments
p — Mesh points
2-by-Np matrix
Mesh points, specified as a 2-by-Np matrix. 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) and the y-coordinate of point k in p(2,k). For
details, see “Mesh Data as [p,e,t] Triples” on page 2-181.
e — Mesh edges
7-by-Ne matrix
Mesh edges, specified as a 7-by-Ne matrix, where 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 as [p,e,t] Triples” on page 2-181.
t — Mesh elements
4-by-Nt matrix
Mesh elements, specified as a 4-by-Nt matrix. Nt is the number of triangles in the mesh.
The t(i,k), with i ranging from 1 through end - 1, contain indices to the corner points of element
k. For details, see “Mesh Data as [p,e,t] Triples” on page 2-181. The last row, t(end,k), contains the
subdomain number of the element.
5-852
jigglemesh
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: p1 = jigglemesh(p,e,t,"Iter",Inf)
Optimization method, specified as the comma-separated pair consisting of "Opt" and "mean",
"minimum", or "off".
Jiggling a mesh moves each mesh point not located on an edge segment towards the center of mass of
the polygon formed by the adjacent triangles. The optimization method controls how many times
jigglemesh repeats this process:
• If Opt is "off", jigglemesh repeats this process Iter times. The default value of Iter in this
case is 1.
• If Opt is "mean", jigglemesh repeats this process until the mean triangle quality stops
increasing significantly or until the maximum number of iterations is reached. The default value of
Iter in this case is 20.
• If Opt is "minimum", jigglemesh repeats this process until the minimum triangle quality stops
increasing significantly or until the maximum number of iterations is reached. The default value of
Iter in this case is 20.
Example: p1 = jigglemesh(p,e,t,"Opt","off","Iter",1000);
Data Types: char | string
Maximum number of iterations, specified as the comma-separated pair consisting of "Iter" and a
positive number. The default value depends on the Opt argument value. If Opt is set to "mean"
(default) or "minimum", the default maximum number of iterations is 20. If Opt is set to "off", the
default maximum number of iterations is 1.
Example: p1 = jigglemesh(p,e,t,"Opt","off","Iter",1000);
Data Types: double
Output Arguments
p1 — Modified mesh points
2-by-Np matrix
Modified mesh points, returned as a 2-by-Np matrix. 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) and the y-coordinate of point k in
p(2,k). For details, see “Mesh Data as [p,e,t] Triples” on page 2-181.
5-853
5 Functions
Version History
Introduced before R2006a
See Also
initmesh | pdetriq
Topics
“Mesh Data as [p,e,t] Triples” on page 2-181
5-854
linearize
linearize
Package: pde
Syntax
sys = linearize(model)
mx = linearize(model,"OutputType","matrices")
Description
sys = linearize(model) extracts a sparse linear model for use with Control System Toolbox. For
a structural analysis model, linearize extracts a mechss model. For a thermal analysis model, it
extracts a sparss model. For transient models, linearize uses time 0.
Use linearizeInput to specify the inputs of the linear model that correspond to external forcing,
such as loads or internal heat sources. The toolbox treats the value of each selected constraint, load,
or source as a constant, and the value becomes one input channel in the linearized model. The
remaining boundary conditions are set to zero for linearization purposes, regardless of their value in
the structural or thermal model. Ensure that you label all nonzero boundary conditions and pass them
as inputs using linearizeInput.
Use linearizeOutput to specify the outputs of the linear model in terms of regions of the
geometry, such as cells (for 3-D geometries only), faces, edges, or vertices. This includes all degrees
of freedom (DoFs) in the specified region as output values. For structural models, you can also specify
which of the x, y, and z degrees of freedom to include as outputs.
Use sys.InputName and sys.OutputGroup to locate the inputs and outputs of sys that
correspond to a particular boundary condition or to a selected region.
Examples
Linearize a model for thermal analysis and return finite element matrices.
Add the block geometry to the thermal model by using the geometryFromEdges function. The
geometry description file for this problem is called crackg.m.
geometryFromEdges(thermalmodel,@crackg);
5-855
5 Functions
pdegplot(thermalmodel,"EdgeLabels","on")
ylim([-1,1])
axis equal
Generate a mesh.
generateMesh(thermalmodel);
Specify the thermal conductivity, mass density, and specific heat of the material.
thermalProperties(thermalmodel,"ThermalConductivity",1, ...
"MassDensity",1, ...
"SpecificHeat",1);
Specify the temperature on the left edge as 100, and constant heat flow to the exterior through the
right edge as -10. Add a unique label to each boundary condition.
thermalBC(thermalmodel,"Edge",6,"Temperature",100,"Label","TempBC");
thermalBC(thermalmodel,"Edge",1,"HeatFlux",-10,"Label","FluxBC");
Specify that the entire geometry generates heat and add a unique label to this assignment.
internalHeatSource(thermalmodel,25,"Label","HeatSource");
thermalIC(thermalmodel,0);
5-856
linearize
Specify the inputs of the linearized model by calling the linearizeInput function with the
previously defined labels for the boundary conditions and the internal heat source. Add one label per
function call.
linearizeInput(thermalmodel,"HeatSource");
linearizeInput(thermalmodel,"TempBC");
linearizeInput(thermalmodel,"FluxBC");
Specify the outputs of the linearized model by calling the linearizeOutput function to set the
regions of interest for measuring temperature. Specify one region per function call. For example,
specify that the output is the temperature value at all nodes on edge 2.
linearizeOutput(thermalmodel,"Edge",2);
sys = linearize(thermalmodel)
Sparse continuous-time state-space model with 27 outputs, 3 inputs, and 1351 states.
In the linearized model, use sys.InputName to check that the inputs to sys are the heat source, the
temperature on edge 6, and the heat flux on edge 1.
sys.InputName
In the linearized model, use sys.OutputGroup to locate the sections associated with each
coordinate.
sys.OutputGroup
If you do not have Control System Toolbox™, you can access the finite element matrices A, B, C, and E
as follows.
mx = linearize(thermalmodel,"OutputType","matrices")
5-857
5 Functions
Generate a mesh.
generateMesh(structuralmodel,"Hmax",0.005);
Specify Young's modulus, Poisson's ratio, and the mass density to model linear elastic material
behavior. Specify all physical properties in consistent units.
structuralProperties(structuralmodel,"YoungsModulus",210E9, ...
"PoissonsRatio",0.3, ...
"MassDensity",8000);
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(structuralmodel,"FaceLabels","on")
5-858
linearize
view(-50,15)
title("Geometry with Face Labels")
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(structuralmodel,"Face",[21,22],"Constraint","fixed");
structuralBoundaryLoad(structuralmodel,"Face",11,"Pressure",5E6, ...
"EndTime",1e-3,"Label","Pressure");
5-859
5 Functions
Create inputs for gravity and the pressure pulse on tuning fork.
linearizeInput(structuralmodel,"Gravity");
linearizeInput(structuralmodel,"Pressure");
Sparse continuous-time second-order model with 28 outputs, 4 inputs, and 4926 degrees of freedom.
In the linearized model, use sys.InputName to check that the inputs to sys are the gravity body
load and the pressure pulse on a tine. The gravity body load produces three inputs because it has x-,
y-, and z-components.
sys.InputName
In the linearized model, use sys.OutputGroup to locate the sections associated with each
coordinate.
sys.OutputGroup
If you do not have Control System Toolbox™, you can access the finite element matrices M, K, B, and F
as follows.
mx = linearize(structuralmodel,"OutputType","matrices")
Input Arguments
model — Structural or thermal model
StructuralModel object | ThermalModel object
5-860
linearize
Output Arguments
sys — Sparse linear models for use with Control System Toolbox
mechss model object | sparss model object
Sparse linear models for use with Control System Toolbox, returned as a mechss or sparss model
object.
Version History
Introduced in R2021b
See Also
linearizeInput | linearizeOutput
5-861
5 Functions
linearizeInput
Package: pde
Syntax
linearizeInput(model,labeltext)
input = linearizeInput(model,labeltext)
Description
linearizeInput(model,labeltext) adds inputs for the boundary condition, constraint, load, or
source with the label labeltext. In the linearized model, the input value u = 1 corresponds to a unit
boundary condition acting on the entire region specified by labeltext. In other words, simulating
the linearized model with the input value u(t) = 25 is equivalent to setting the boundary condition
value to 25 in the thermal or structural model in Partial Differential Equation Toolbox. For more
information, see “Algorithms” on page 5-868.
For a structural analysis model, the following boundary conditions, constraints, and loads can become
inputs of the linearized model:
• A structural boundary constraint. Use the structuralBC function with the Constraint
argument.
• A displacement or a displacement component on the boundary. Use the structuralBC function
with the Displacement, XDisplacement, YDisplacement, or ZDisplacement argument.
• A structural boundary load. Use the structuralBoundaryLoad function with the Pressure,
Force, or SurfaceTraction argument.
• A structural body load. Use the structuralBodyLoad function with the
GravitationalAcceleration argument.
The boundary conditions, loads, or constraints with x-, y-, and z- components produce one input
channel per component.
For a thermal analysis model, the following boundary conditions and sources can become inputs of
the linearized model:
• A temperature or heat flux on the boundary. Use the thermalBC function with the Temperature
or HeatFlux argument.
• An internal heat source. Use the internalHeatSource function.
Each selected condition or source produces a single scalar input in the linearized model.
To make a condition, constraint, load, or source available as a linearization input, always label it upon
creation. For example, specify an internal heat source for a thermal model as follows:
internalHeatSource(thermalmodel,25,"Label","HeatSource");
5-862
linearizeInput
The remaining boundary conditions are set to zero for linearization purposes, regardless of their
value in the structural or thermal model. Ensure that you label all nonzero boundary conditions and
pass them as inputs using linearizeInput.
Use linearizeInput and linearizeOutput together with the linearize function to extract
sparse linear models from structural and thermal models.
Examples
Thermal Boundary Conditions and Internal Heat Source as Inputs for linearize Function
Use labels to pass the parameters of a 2-D thermal analysis model to the linearize function. This
function extracts sparse linear models for use with Control System Toolbox™.
thermalmodel = createpde("thermal","transient");
Add the block geometry to the thermal model by using the geometryFromEdges function. The
geometry description file for this problem is called crackg.m.
geometryFromEdges(thermalmodel,@crackg);
pdegplot(thermalmodel,"EdgeLabels","on")
ylim([-1,1])
axis equal
5-863
5 Functions
Generate a mesh.
generateMesh(thermalmodel);
Specify the thermal conductivity, mass density, and specific heat of the material.
thermalProperties(thermalmodel,"ThermalConductivity",1, ...
"MassDensity",1, ...
"SpecificHeat",1);
Specify the temperature on the left edge as 100, and constant heat flow to the exterior through the
right edge as -10. Add a unique label to each boundary condition.
thermalBC(thermalmodel,"Edge",6,"Temperature",100,"Label","TempBC");
thermalBC(thermalmodel,"Edge",1,"HeatFlux",-10,"Label","FluxBC");
Specify that the entire geometry generates heat and add a unique label to this assignment.
internalHeatSource(thermalmodel,25,"Label","HeatSource");
thermalIC(thermalmodel,0);
Call the linearizeInput function with the previously defined labels for the boundary conditions
and the internal heat source to set the inputs for the linearize function. Add one label per function
call.
5-864
linearizeInput
linearizeInput(thermalmodel,"HeatSource");
linearizeInput(thermalmodel,"TempBC");
linearizeInput(thermalmodel,"FluxBC");
Create inputs for gravity and a short pressure pulse on tuning fork.
5-865
5 Functions
Generate a mesh.
generateMesh(structuralmodel,"Hmax",0.005);
Specify Young's modulus, Poisson's ratio, and the mass density to model linear elastic material
behavior. Specify all physical properties in consistent units.
structuralProperties(structuralmodel,"YoungsModulus",210E9, ...
"PoissonsRatio",0.3, ...
"MassDensity",8000);
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(structuralmodel,"FaceLabels","on")
view(-50,15)
title("Geometry with Face Labels")
5-866
linearizeInput
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. As a simplified approximation of this boundary
condition, fix a region near the intersection of the tines and the handle (faces 21 and 22).
structuralBC(structuralmodel,"Face",[21,22],"Constraint","fixed");
structuralBoundaryLoad(structuralmodel,"Face",11, ...
"Pressure",5E6, ...
"EndTime",1e-3, ...
"Label","Pressure");
structuralBodyLoad(structuralmodel, ...
"GravitationalAcceleration",[0 0 -1], ...
"Label","Gravity");
Create inputs for gravity and the pressure pulse on the tuning fork.
linearizeInput(structuralmodel,"Gravity");
linearizeInput(structuralmodel,"Pressure");
structuralmodel.LinearizeInputs
Input Arguments
model — Structural or linear thermal model
StructuralModel object | ThermalModel object
Output Arguments
input — Linearization input description
structure array
5-867
5 Functions
Algorithms
The linearize function constructs a linear model whose inputs are a subset of the boundary
conditions, loads, or sources applied to the thermal or structural model in Partial Differential
Equation Toolbox and whose outputs are the resulting values at the selected DoFs. For example, if
you designate the heat source
internalHeatSource(model,25,"Face",2,"Label","heatSource")
as a linearization input
linearizeInput(model,"heatSource")
linearizeOutput(model,"Face",X)
then the response of the linearized model to the constant input u(t) = 25 (the heat source value in the
thermal model) matches the Partial Differential Equation Toolbox simulation results for face X.
tlist = 1:10;
u = repmat(25,size(tlist));
ysp = lsim(linsys,uLoad,tlist);
Note that loads and boundary conditions not included as linearization inputs are assumed to be zero
in the linearized model regardless of their values in the structural or thermal model in Partial
Differential Equation Toolbox. Simulation results can differ in this case.
Version History
Introduced in R2021b
See Also
linearize | linearizeOutput | structuralBodyLoad | structuralBoundaryLoad |
structuralBC | internalHeatSource | thermalBC
5-868
linearizeOutput
linearizeOutput
Package: pde
Syntax
linearizeOutput(model,RegionType,RegionID)
linearizeOutput(model,RegionType,RegionID,"Component",xyz)
output = linearizeOutput( ___ )
Description
linearizeOutput(model,RegionType,RegionID) adds all degrees of freedom (DoFs) associated
with the region defined by RegionType and RegionID to the output vector of the linearized model.
For 3-D structural models, linearizeOutput adds all x-coordinates first, then all y-coordinates,
then all z-coordinates. In the linearized model sys, use sys.OutputGroup to locate the sections
associated with each coordinate.
Use linearizeInput and linearizeOutput together with the linearize function to extract
sparse linear models from structural and thermal models.
output = linearizeOutput( ___ ) returns a structure array output with the linearization
output description. Use this syntax with any of the previous arguments.
Examples
Specify the regions of a 2-D thermal model for which linearize extracts sparse linear models used
in Control System Toolbox™.
thermalmodel = createpde("thermal","transient");
Add the block geometry to the thermal model by using the geometryFromEdges function. The
geometry description file for this problem is called crackg.m.
geometryFromEdges(thermalmodel,@crackg);
pdegplot(thermalmodel,"EdgeLabels","on")
ylim([-1,1])
axis equal
5-869
5 Functions
Generate a mesh.
generateMesh(thermalmodel);
Specify the thermal conductivity, mass density, and specific heat of the material.
thermalProperties(thermalmodel,"ThermalConductivity",1, ...
"MassDensity",1, ...
"SpecificHeat",1);
Specify the temperature on the left edge as 100, and constant heat flow to the exterior through the
right edge as -10. Add a unique label to each boundary condition.
thermalBC(thermalmodel,"Edge",6,"Temperature",100,"Label","TempBC");
thermalBC(thermalmodel,"Edge",1,"HeatFlux",-10,"Label","FluxBC");
Specify that the entire geometry generates heat and add a unique label to this assignment.
internalHeatSource(thermalmodel,25,"Label","HeatSource");
thermalIC(thermalmodel,0);
Call the linearizeInput function with the previously defined labels for the boundary conditions
and the internal heat source to set the inputs for the linearize function. Add one label per function
call.
5-870
linearizeOutput
linearizeInput(thermalmodel,"HeatSource");
linearizeInput(thermalmodel,"TempBC");
linearizeInput(thermalmodel,"FluxBC");
Call the linearizeOutput function to specify the regions for which you want linearize to extract
sparse linear models. Specify one region per function call.
linearizeOutput(thermalmodel,"Edge",2)
Specify which of the x-, y-, and z- coordinates to include in a linearized model.
5-871
5 Functions
Generate a mesh.
generateMesh(structuralmodel,"Hmax",0.005);
Specify Young's modulus, Poisson's ratio, and the mass density to model linear elastic material
behavior. Specify all physical properties in consistent units.
structuralProperties(structuralmodel,"YoungsModulus",210E9, ...
"PoissonsRatio",0.3, ...
"MassDensity",8000);
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(structuralmodel,"FaceLabels","on")
view(-50,15)
title("Geometry with Face Labels")
5-872
linearizeOutput
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. As a simplified approximation of this boundary
condition, fix a region near the intersection of the tines and the handle (faces 21 and 22).
structuralBC(structuralmodel,"Face",[21,22],"Constraint","fixed");
structuralBoundaryLoad(structuralmodel,"Face",11,...
"Pressure",5E6, ...
"EndTime",1e-3, ...
"Label","Pressure");
structuralBodyLoad(structuralmodel, ...
"GravitationalAcceleration",[0 0 -1], ...
"Label","Gravity");
Create inputs for gravity and the pressure pulse on tuning fork.
linearizeInput(structuralmodel,"Gravity");
linearizeInput(structuralmodel,"Pressure");
linearizeOutput(structuralmodel,"Face",12,"Component","y")
linearizeOutput(structuralmodel,"Face",6,"Component","x")
Input Arguments
model — Structural or linear thermal model
StructuralModel object | ThermalModel object
Geometric region type, specified as "Cell" (for a 3-D model only), "Face", "Edge", or "Vertex".
Data Types: char
5-873
5 Functions
Geometric region ID, specified as a positive integer. Find the region IDs by using pdegplot with the
"CellLabels", "FaceLabels", "EdgeLabels", or "VertexLabels" value set to "on".
Data Types: double
Coordinates to include, specified as a character vector or a string of x-, y-, and z-coordinates to
include.
Example: linearizeOutput(pdemodel,"Face",10,"Component","xz") selects the x and z
DoFs for face 10
Data Types: char | string
Output Arguments
output — Linearization output description
structure array
Version History
Introduced in R2021b
See Also
linearize | linearizeInput
5-874
mergeCells
mergeCells
Package:
Syntax
h = mergeCells(g,cellIDs)
Description
h = mergeCells(g,cellIDs) merges two cells of the 3-D geometry g by removing their shared
faces. cellIDs must be a vector of two cell IDs. The specified cells must share at least one face.
mergeCells renumbers cells, faces, edges, and vertices in the resulting geometry. The merged cell
gets the first of the specified cell IDs. The function decreases all cell IDs following the second of the
specified cell IDs by 1. Because mergeCells removes shared faces, it also removes edges and
vertices belonging only to these faces and decreases IDs of all subsequent faces, edges, and vertices.
Examples
gm = multicylinder([1 2 3],3);
pdegplot(gm,CellLabels="on",FaceAlpha=0.5);
5-875
5 Functions
Plot the resulting geometry. While mergeCells removes shared faces, it does not merge faces of the
merged cells. So, cell 1 has two top and two bottom faces.
pdegplot(newgm,CellLabels="on",FaceAlpha=0.5);
5-876
mergeCells
Input Arguments
g — Original multicell geometry
fegeometry object | DiscreteGeometry object
Output Arguments
h — Modified geometry
fegeometry object | handle to DiscreteGeometry object
5-877
5 Functions
Tips
• While mergeCells removes shared faces of the merged cells, it does not merge faces of the
merged cell. So, the resulting geometry can have extraneous faces. For example, if you merge two
stacked cubes, mergeCells removes the face between the cubes,but each side of the merged cell
consists of two faces, not one face, for a total of 10 faces in the merged geometry.
• Merging modifies a geometry, but it does not modify the mesh. After merging cells, call
generateMesh for a proper mesh association with the new geometry.
Version History
Introduced in R2023b
See Also
Functions
addCell | addFace | addVertex | addVoid | rotate | scale | translate | extrude |
generateMesh
5-878
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.
Q = meshQuality( ___ ,"aspect-ratio") determines the shape quality by using the ratio of
minimal to maximal dimensions of an element. The quality values are numbers from 0 through 1,
where 1 corresponds to the optimal shape of the element. Specify "aspect-ratio" after any of the
previous syntaxes.
Examples
model = createpde;
importGeometry(model,"PlateSquareHoleSolid.stl");
pdegplot(model)
5-879
5 Functions
mesh = generateMesh(model,"Hmax",35)
mesh =
FEMesh with properties:
pdemesh(model)
5-880
meshQuality
Evaluate the shape quality of all mesh elements. Display the first five values.
Q = meshQuality(mesh);
Q(1:5)
ans = 1×5
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-881
5 Functions
figure
hist(Q)
xlabel("Element Shape Quality","fontweight","b")
ylabel("Number of Elements","fontweight","b")
5-882
meshQuality
Qworst = min(Q)
Qworst = 0.1867
elemIDs = find(Q==Qworst)
elemIDs = 377
model = createpde;
importGeometry(model,"PlateSquareHolePlanar.stl");
pdegplot(model)
5-883
5 Functions
mesh = generateMesh(model,"Hmax",20)
mesh =
FEMesh with properties:
pdemesh(model)
5-884
meshQuality
Find the IDs of the elements within a box enclosing the center of the plate.
elemIDs = findElements(mesh,"box",[25,75],[80,120]);
Evaluate the shape quality of these elements. Display the result as a column vector.
Q = meshQuality(mesh,elemIDs);
Q.'
ans = 16×1
0.3623
0.9973
0.6361
0.3497
0.7660
0.7858
0.9843
0.7858
0.3439
0.3623
⋮
Find the elements with the quality values less than 0.4.
5-885
5 Functions
elemIDs04 = 1×4
5 26 47 51
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)
Determine the shape quality of mesh elements by using the ratios of minimal to maximal dimensions.
5-886
meshQuality
pdeplot(model)
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 = 1×5
Evaluate the shape quality of mesh elements by using the default setting. Display the first five values.
Q = meshQuality(mesh);
Q(1:5)
ans = 1×5
Input Arguments
mesh — Mesh object
Mesh property of a PDEModel object | output of generateMesh
5-887
5 Functions
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
Version History
Introduced in R2018a
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
findElements | findNodes | area | volume | FEMesh Properties
Topics
“Finite Element Method Basics” on page 1-11
5-888
meshToPet
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';
gd = decsg(geom,sf,ns);
geometryFromEdges(model,gd);
pdegplot(model,"EdgeLabels","on")
xlim([-1.1 1.1])
axis equal
5-889
5 Functions
generateMesh(model);
pdemesh(model)
axis equal
5-890
meshToPet
[p,e,t] = meshToPet(model.Mesh);
size(p)
ans = 1×2
2 948
size(e)
ans = 1×2
7 160
size(t)
ans = 1×2
7 434
5-891
5 Functions
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-184.
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-184.
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-184. 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.
Version History
Introduced in R2015a
See Also
FEMesh | generateMesh
Topics
“Mesh Data” on page 2-184
5-892
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.
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.
5-893
5 Functions
gm =
DiscreteGeometry with properties:
NumCells: 3
NumFaces: 18
NumEdges: 36
NumVertices: 24
Vertices: [24x3 double]
model = createpde
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
pdegplot(model,"CellLabels","on","FaceAlpha",0.5)
5-894
multicuboid
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 =
DiscreteGeometry with properties:
NumCells: 4
NumFaces: 21
NumEdges: 36
NumVertices: 20
Vertices: [20x3 double]
model = createpde
model =
PDEModel with properties:
5-895
5 Functions
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
pdegplot(model,"CellLabels","on","FaceAlpha",0.5)
5-896
multicuboid
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:
NumCells: 1
NumFaces: 6
NumEdges: 12
NumVertices: 8
Vertices: [8x3 double]
model = createpde
model =
PDEModel with properties:
5-897
5 Functions
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
pdegplot(model,"CellLabels","on")
5-898
multicuboid
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:
NumCells: 1
NumFaces: 10
NumEdges: 24
NumVertices: 16
Vertices: [16x3 double]
model = createpde
model =
PDEModel with properties:
5-899
5 Functions
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
pdegplot(model,"CellLabels","on","FaceAlpha",0.5)
5-900
multicuboid
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.
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.
5-901
5 Functions
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.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: gm = multicuboid([1 2],[1 2],[3 3],"Void",[true,false])
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.
5-902
multicuboid
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
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.
Version History
Introduced in R2017a
See Also
Functions
multicylinder | multisphere
Objects
DiscreteGeometry
5-903
5 Functions
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.
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:
5-904
multicylinder
NumCells: 3
NumFaces: 9
NumEdges: 6
NumVertices: 6
Vertices: [6x3 double]
model = createpde
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
pdegplot(model,"CellLabels","on","FaceAlpha",0.5)
5-905
5 Functions
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
Vertices: [5x3 double]
model = createpde
model =
PDEModel with properties:
5-906
multicylinder
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
pdegplot(model,"CellLabels","on","FaceAlpha",0.5)
5-907
5 Functions
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
Vertices: [2x3 double]
model = createpde
model =
PDEModel with properties:
5-908
multicylinder
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
pdegplot(model,"CellLabels","on")
5-909
5 Functions
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
Vertices: [4x3 double]
model = createpde
model =
PDEModel with properties:
5-910
multicylinder
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
pdegplot(model,"CellLabels","on","FaceAlpha",0.5)
5-911
5 Functions
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.
5-912
multicylinder
Note Either radius or height must be the same for all cells in the geometry.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: gm = multicylinder([1 2],1,"Void",[true,false])
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-913
5 Functions
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.
Version History
Introduced in R2017a
See Also
Functions
multicuboid | multisphere
Objects
DiscreteGeometry
5-914
multisphere
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.
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
5-915
5 Functions
NumFaces: 3
NumEdges: 0
NumVertices: 0
Vertices: []
model = createpde
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
pdegplot(model,"CellLabels","on","FaceAlpha",0.2)
5-916
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
Vertices: []
model = createpde
model =
PDEModel with properties:
5-917
5 Functions
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
pdegplot(model,"CellLabels","on")
5-918
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
Vertices: []
model = createpde
model =
PDEModel with properties:
5-919
5 Functions
PDESystemSize: 1
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
model.Geometry = gm
model =
PDEModel with properties:
PDESystemSize: 1
IsTimeDependent: 0
Geometry: [1x1 DiscreteGeometry]
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.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
5-920
multisphere
Version History
Introduced in R2017a
See Also
Functions
multicuboid | multicylinder
Objects
DiscreteGeometry
Topics
“Heat Conduction in Multidomain Geometry with Nonuniform Heat Flux” on page 3-318
5-921
5 Functions
nearestEdge
Find edges nearest to specified point
Syntax
EdgeID = nearestEdge(g,Coords)
Description
EdgeID = nearestEdge(g,Coords) finds edges nearest to the point with the coordinates Coords.
Examples
gm = multicuboid(3,2,1)
gm =
DiscreteGeometry with properties:
NumCells: 1
NumFaces: 6
NumEdges: 12
NumVertices: 8
Vertices: [8x3 double]
Plot the geometry with the edge labels. Add the points with the coordinates (0 0 0), (1 0.9 1), and (1.5
-1 0) to the plot.
pdegplot(gm,"EdgeLabels","on","FaceAlpha",0.2)
hold on
scatter3([0 1 1.5],[0 0.9 -1],[0 1 0],"filled","MarkerFaceColor","g")
5-922
nearestEdge
Find edges closest to the points with the coordinates (0 0 0), (1 0.9 1), and (1.5 -1 0). If several edges
are equally close (within the tolerance) to the point, nearestEdge returns the ID of one of the edges.
edgeIDs = 1×3
1 7 1
Create a model and include this geometry. The geometry of the L-shaped membrane is described in
the file lshapeg.
model = createpde();
gm = geometryFromEdges(model,@lshapeg)
gm =
AnalyticGeometry with properties:
NumCells: 0
NumFaces: 3
5-923
5 Functions
NumEdges: 10
NumVertices: 8
Vertices: [8x2 double]
Plot the geometry with the edge labels. Add the points with the coordinates (0 0), (0.1 0.2), and (-0.5
0.5) to the plot.
pdegplot(gm,"EdgeLabels","on")
hold on
scatter([0 0.1 -0.5],[0 0.2 0.5],"filled")
Find edges closest to the points with the coordinates (0 0), (0.1 0.2), and (-0.5 0.5). If several edges
are equally close (within the tolerance) to the point, nearestEdge returns the ID of one of the edges.
edgeIDs = 1×3
7 10 10
Input Arguments
g — Geometry
fegeometry object | DiscreteGeometry object | AnalyticGeometry object
5-924
nearestEdge
Coords — Coordinates
N-by-2 numeric matrix | N-by-3 numeric matrix
Coordinates of the points, specified as an N-by-2 or N-by-3 numeric matrix for a 2-D or 3-D geometry,
respectively. Here, N is the number of points.
Data Types: double
Output Arguments
EdgeID — IDs of edges nearest to specified point
positive number | vector of positive numbers
IDs of edges nearest to the specified point, returned as a positive number or a vector of positive
numbers.
Version History
Introduced in R2021a
See Also
Functions
cellEdges | cellFaces | faceEdges | facesAttachedToEdges | nearestFace
Objects
fegeometry | DiscreteGeometry | AnalyticGeometry
5-925
5 Functions
nearestFace
Find faces nearest to specified point
Syntax
FaceID = nearestFace(g,Coords)
Description
FaceID = nearestFace(g,Coords) finds faces nearest to the point with the coordinates Coords.
Examples
gm = multicuboid(3,2,1)
gm =
DiscreteGeometry with properties:
NumCells: 1
NumFaces: 6
NumEdges: 12
NumVertices: 8
Vertices: [8x3 double]
Plot the geometry with the face labels. Add the points with the coordinates (0 0 0.1), (2 0.9 1), and
(1.5 -1 1) to the plot.
pdegplot(gm,"FaceLabels","on","FaceAlpha",0.2)
hold on
scatter3([0 2 1.5],[0 0.9 -1],[0.1 1 1],"filled","MarkerFaceColor","g")
5-926
nearestFace
Find faces closest to the points with the coordinates (0 0 0.1), (2 0.9 1), and (1.5 -1 1). If several faces
are equally close (within the tolerance) to the point, nearestFace returns the ID of one of the faces.
faceIDs = 1×3
1 3 2
Create a model and include this geometry. The geometry of the L-shaped membrane is described in
the file lshapeg.
model = createpde();
gm = geometryFromEdges(model,@lshapeg)
gm =
AnalyticGeometry with properties:
NumCells: 0
NumFaces: 3
5-927
5 Functions
NumEdges: 10
NumVertices: 8
Vertices: [8x2 double]
Plot the geometry with the face labels. Add the points with the coordinates (0 0), (1.1 -0.2), and (-0.5
0.5) to the plot.
pdegplot(gm,"FaceLabels","on")
hold on
scatter([0 1.1 -0.5],[0 -0.2 0.5],"filled")
Find faces closest to the points with the coordinates (0 0), (1.1 -0.2), and (-0.5 0.5). If several faces
are equally close (within the tolerance) to the point, nearestFace returns the ID of one of the faces.
faceIDs = 1×3
3 3 1
Input Arguments
g — Geometry
fegeometry object | DiscreteGeometry object | AnalyticGeometry object
5-928
nearestFace
Coords — Coordinates
N-by-2 numeric matrix | N-by-3 numeric matrix
Coordinates of the points, specified as an N-by-2 or N-by-3 numeric matrix for a 2-D or 3-D geometry,
respectively. Here, N is the number of points.
Data Types: double
Output Arguments
FaceID — IDs of faces nearest to specified point
positive number | vector of positive numbers
IDs of faces nearest to the specified point, returned as a positive number or a vector of positive
numbers.
Version History
Introduced in R2021a
See Also
Functions
cellEdges | cellFaces | faceEdges | facesAttachedToEdges | nearestEdge
Objects
fegeometry | DiscreteGeometry | AnalyticGeometry
5-929
5 Functions
parabolic
(Not recommended) Solve parabolic PDE problem
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
Parabolic equation solver
∂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.
∂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.
5-930
parabolic
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.
u = parabolic( ___ ,'Stats','off'), for any of the previous input arguments, turns off the
display of internal ODE solver statistics during the solution process.
Examples
Parabolic Equation
∂u
= Δu
∂t
model = createpde;
geometryFromEdges(model,@squareg);
pdegplot(model,'EdgeLabels','on')
ylim([-1.1,1.1])
axis equal
5-931
5 Functions
applyBoundaryCondition(model,'dirichlet',...
'Edge',1:model.Geometry.NumEdges, ...
'u',0);
generateMesh(model,'Hmax',0.02,'GeometricOrder','linear');
2
Set the initial condition to have u(0) = 1 on the disk x2 + y2 ≤ 0 . 4 and u(0) = 0 elsewhere.
p = model.Mesh.Nodes;
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,model,c,a,f,d);
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')
subplot(2,2,4)
pdeplot(model,'XYData',u(:,end))
axis equal
title('t = 0.1')
5-932
parabolic
∂u
= Δu
∂t
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-933
5 Functions
Set Dirichlet boundary conditions u = 0 on all edges. The squareb1 function specifies these
boundary conditions.
b = @squareb1;
[p,e,t] = initmesh(g,'Hmax',0.02);
2
Set the initial condition to have u(0) = 1 on the disk x2 + y2 ≤ 0 . 4 and u(0) = 0 elsewhere.
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;
5-934
parabolic
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
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-935
5 Functions
Create finite element matrices that encode a parabolic problem, and solve the problem.
The problem is the evolution of temperature in a conducting block. The block is a rectangular slab.
model = createpde(1);
importGeometry(model,'Block.stl');
handl = pdegplot(model,'FaceLabels','on');
view(-42,24)
handl(1).FaceAlpha = 0.5;
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);
−3
u0 = 10 xyz .
generateMesh(model);
p = model.Mesh.Nodes;
5-936
parabolic
x = p(1,:);
y = p(2,:);
z = p(3,:);
u0 = x.*y.*z*1e-3;
∂u
d − ∇ ⋅ (c ∇u) + au = f .
∂t
Suppose the thermal conductivity of the block leads to a c coefficient value of 1. The values of the
other coefficients in this problem are d = 1, a = 0, and f = 0.
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
72 function evaluations
1 partial derivatives
10 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'
clim([umin umax]);
subplot(2,2,2)
pdeplot3D(model,'ColorMapData',u(:,11))
colorbar off
view(125,22)
title 't = 10'
clim([umin umax]);
subplot(2,2,3)
pdeplot3D(model,'ColorMapData',u(:,26))
colorbar off
view(125,22)
title 't = 25'
clim([umin umax]);
5-937
5 Functions
subplot(2,2,4)
pdeplot3D(model,'ColorMapData',u(:,41))
colorbar off
view(125,22)
title 't = 40'
clim([umin umax]);
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.
5-938
parabolic
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
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
∂u
d − ∇ ⋅ c ⊗ ∇u + au = f
∂t
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
Example: 2*eye(3)
5-939
5 Functions
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
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
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.
Example: b = 'circleb1', b = "circleb1", or b = @circleb1
Data Types: double | char | string | function_handle
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 as [p,e,t] Triples” on page 2-181.
5-940
parabolic
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 as [p,e,t] Triples” on page 2-181.
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
Mesh triangles, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For a description of the (p,e,t) matrices, see “Mesh Data as [p,e,t] Triples” on page 2-181.
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-
210. Typically, Kc is the output of assempde.
Fc — Load vector
vector
Load vector, specified as a vector. See “Elliptic Equations” on page 5-210. Typically, Fc is the output
of assempde.
B — Dirichlet nullspace
sparse matrix
Dirichlet nullspace, returned as a sparse matrix. See “Algorithms” on page 5-210. Typically, B is the
output of assempde.
ud — Dirichlet vector
vector
Dirichlet vector, returned as a vector. See “Algorithms” on page 5-210. Typically, ud is the output of
assempde.
5-941
5 Functions
M — Mass matrix
sparse matrix | full matrix
Mass matrix. specified as a sparse matrix or a full matrix. See “Elliptic Equations” on page 5-210.
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 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 “3-D Solution and Gradient Plots with
MATLAB Functions” on page 3-391.
5-942
parabolic
Algorithms
Reducing Parabolic Equations to Elliptic Equations
parabolic 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.
∂2 u ∂u
m +d − ∇ · c ∇u + au = f
∂t2 ∂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 Ω
∂t
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
ρC − ∇ · 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.
Assuming a mesh on Ω and t ≥ 0, expand the solution to the PDE (as a function of x) in the Finite
Element Method basis:
u(x, t) = ∑ Ui(t)ϕi(x)
i
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
∑ ∫ dϕ jϕi dt
dx + ∑ ∫ ∇ϕ ⋅ c ∇ϕ
j i + aϕ jϕi dx + ∫ qϕ ϕ ds U (t)
j i i
i Ω i Ω ∂Ω
=
Ω
∫ f ϕ dx + ∫ gϕ ds
j
∂Ω
j ∀j
5-943
5 Functions
In matrix notation, we have to solve the linear, large and sparse ODE system
dU
M + KU = F
dt
Ui(0) = u0(xi)
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 Ω
with the original boundary conditions, while M is just the mass matrix of the problem
–∇ · (0∇u) + du = 0 in Ω.
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.
Version History
Introduced before R2006a
parabolic is not recommended. Use solvepde instead. There are no plans to remove parabolic.
R2012b: Coefficients of parabolic PDEs as functions of the solution and its gradient
You can now solve parabolic equations whose coefficients depend on the solution u or on the gradient
of u.
5-944
parabolic
See Also
solvepde
5-945
5 Functions
pdearcl
Represent arc lengths as parametrized curve
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.
The arc length values s,s0, and s1 can be an affine transformation of the arc length.
Examples
Polygonal Approximation
Create a cardioid geometry by using the pdearcl function with a polygonal approximation to the
geometry. 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 this 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
5-946
pdearcl
yt = r.*sin(th);
% Compute parameters corresponding to the arc length values in s
th = pdearcl(th,[xt;yt],s,0,2*pi); % th contains the parameters
% Now compute x and y for the parameters th
r = 2*(1 + cos(th));
x(:) = r.*cos(th);
y(:) = r.*sin(th);
end
pdegplot("cardioid1","EdgeLabels","on")
axis equal
Input Arguments
p — Parameter values corresponding to points on curve
row vector
Parameter values corresponding to the points xy on the curve, specified as a monotone row vector.
Data Types: double
xy — Points on curve
2-row matrix
5-947
5 Functions
Points on the curve, specified as a 2-row matrix. Each column specifies the coordinates of a point on
the curve.
Data Types: double
Arc length value for the first point, specified as a real number.
Data Types: double
Arc length value for the last point, specified as a real number.
Data Types: double
Output Arguments
pp — Parameter values corresponding to arc length values
vector
Version History
Introduced before R2006a
See Also
pdegplot
5-948
pdecgrad
pdecgrad
(Not recommended) Flux of PDE solution
Syntax
[cgxu,cgyu] = pdecgrad(p,t,u,c)
[cgxu,cgyu] = pdecgrad(p,t,u,c,time)
[cgxu,cgyu] = pdecgrad( ___ ,FaceID)
Description
[cgxu,cgyu] = pdecgrad(p,t,u,c) computes the flux of the solution c ⊗ ∇u evaluated at the
center of each mesh triangle.
The gradient is the same everywhere in the triangle interior because pdecgrad uses only linear basis
functions. However, the flux can vary inside a triangle because the coefficient c can vary.
[cgxu,cgyu] = pdecgrad( ___ ,FaceID) uses the arguments from the previous syntaxes and
restricts the computation to the faces listed in FaceID.
Examples
[p,e,t] = initmesh('lshapeg');
c = 1;
a = 0;
f = 1;
u = assempde('lshapeb',p,e,t,c,a,f);
[cgradx,cgrady] = pdecgrad(p,t,c,u);
pdeplot(p,e,t,'XYData',u,'FlowData',[cgradx;cgrady])
5-949
5 Functions
Input Arguments
p — Mesh nodes
matrix
Mesh nodes, specified as a 2-by-Np matrix of nodes (points), where Np is the number of nodes in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
t — Mesh elements
matrix
Mesh elements, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
u — Data at nodes
column vector
For a PDE system of N equations and a mesh with Np node points, the first Np values of u describe
the first component, the following Np values of u describe the second component, and so on.
5-950
pdecgrad
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
Example: 'cosh(x+y.^2)'
Data Types: double | char | string | function_handle
Complex Number Support: Yes
Time for parabolic and hyperbolic problems with a time-dependent coefficient c, specified as a
nonnegative number.
Data Types: double
Output Arguments
cgxu — x-component of flux of u evaluated at the center of each triangle
row vector | matrix
x-component of the flux of u evaluated at the center of each triangle, returned as a row vector for a
scalar PDE or a matrix for a system of PDEs. The number of elements in a row vector or columns in a
matrix corresponds to the number Nt of mesh triangles. For a PDE system of N equations, each row i
N ∂u j ∂u j
from 1 to N contains ∑ ci j11 + ci j12 .
j=1
∂x ∂y
y-component of the flux of u evaluated at the center of each triangle, returned as a row vector for a
scalar PDE or a matrix for a system of PDEs. The number of elements in a row vector or columns in a
matrix corresponds to the number Nt of mesh triangles. For a PDE system of N equations, each row i
N ∂u j ∂u j
from 1 to N contains ∑ ci j21 + ci j22 .
j=1
∂x ∂y
5-951
5 Functions
Version History
Introduced before R2006a
pdecgrad is not recommended. Use evaluateCGradient instead. There are no plans to remove
pdecgrad.
See Also
evaluateCGradient | pdegrad
5-952
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.
pdecirc(xc,yc,R,label) assigns a name to the circle. Otherwise, pdecirc uses a default name,
such as C1, C2, and so on.
Examples
Open the PDE Modeler app window containing a circle with the center at (0,0) and the radius 1.
pdecirc(0,0,1)
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-953
5 Functions
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-954
pdecirc
Input Arguments
xc — x-coordinate of center
real number
yc — y-coordinate of center
real number
5-955
5 Functions
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.
Version History
Introduced before R2006a
See Also
pdeellip | pdepoly | pderect | PDE Modeler
5-956
pdecont
pdecont
(To be removed) Contour plot of PDE node or triangle data
Note pdecont will be removed in a future release. Use pdeplot instead. For more information, see
“Compatibility Considerations”.
Syntax
pdecont(p,t,u)
pdecont(p,t,u,n)
pdecont(p,t,u,v)
h = pdecont( ___ )
Description
pdecont(p,t,u) creates a contour plot of node data or triangle data. By default, pdecont uses 10
levels for a contour plot. The p and t arguments specify the geometry of the PDE problem.
If u is a column vector, pdecont treats it as a node data. If u is a row vector, pdesurf treats it as a
triangle data.
h = pdecont( ___ ) uses any of the previous syntaxes and returns handles to the drawn axes
objects.
Examples
Plot contours of the solution to the equation −Δu = 1 on the L-shaped membrane using the pdecont
function.
[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-957
5 Functions
Plot contours of the solution using the pdecont function. By default, there are 10 levels.
pdecont(p,t,u)
5-958
pdecont
pdecont(p,t,u,3)
5-959
5 Functions
Plot the contours of the solution at the heights 0, 0.05, 0.1, and 0.14.
5-960
pdecont
Input Arguments
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 details on the mesh data representation, see initmesh.
Data Types: double
t — Mesh triangles
matrix
Mesh triangles, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
u — PDE solution
vector
The pdesurf function treats a column vector as node data and uses continuous style and
interpolated shading. The function treats a row vector as triangle data and uses discontinuous style
and flat shading.
5-961
5 Functions
n — Number of levels
positive integer
v — Levels to plot
vector of heights
Output Arguments
h — Handles to graphics objects
vector
Tips
• For more control over a contour plot, use the pdeplot function.
Version History
Introduced before R2006a
R2023a: Warns
Warns starting in R2023a
The pdecont function issues a warning that it will be removed in a future release.
To update your code for plotting the default 10 levels u, change instances of the function call
pdecont(p,t,u) to the function call:
pdeplot(p,[],t,'XYData',u,'XStyle','off', ...
'Contour','on','ColorBar','off')
To update your code for plotting the first n levels, change instances of the function call
pdecont(p,t,u,n) to the function call:
pdeplot(p,[],t,'XYData',u,'XStyle','off', ...
'Contour','on','Levels',n, ...
'ColorBar','off')
To update your code for plotting levels specified as a vector v, change instances of the function call
pdecont(p,t,u,v) to the function call:
pdeplot(p,[],t,'XYData',u,'XStyle','off', ...
'Contour','on','Levels',v, ...
'ColorBar','off')
5-962
pdecont
Note that the legacy workflow that uses the [p,e,t] mesh is not recommended. New features might
not be compatible with this legacy workflow. For description of the mesh data in the recommended
workflow, see “Mesh Data” on page 2-184.
R2022a: To be removed
Not recommended starting in R2022a
The pdecont function runs without a warning, but will be removed in a future release. Use pdeplot
instead.
See Also
pdemesh | pdeplot
5-963
5 Functions
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 = λdu on Ω
− ∇ ⋅ (c ⊗ ∇u) + au = λdu on Ω
with geometry, boundary conditions, and mesh specified in model, a PDEModel object.
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.
[v,l] = pdeeig(b,p,e,t,c,a,d,r) solves for boundary conditions described in b, and the finite
element mesh in [p,e,t].
[v,l] = pdeeig(Kc,B,M,r) produces the solution to the generalized sparse matrix eigenvalue
problem
Kc ui = λB´MBui
u = Bui
Examples
Compute the eigenvalues that are less than 100, and compute the corresponding eigenmodes for
− ∇u = λu 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);
5-964
pdeeig
c = 1;
a = 0;
d = 1;
r = [-Inf 100];
[v,l] = pdeeig(model,c,a,d,r);
l(1) % first eigenvalue
ans = 9.6505
Display the first eigenmode, and compare it to the built-in membrane plot.
pdeplot(model,'XYData',v(:,1),'ZData',v(:,1))
figure
membrane(1,20,9,9) % the MATLAB function
5-965
5 Functions
ans = 92.5224
figure
pdeplot(model,'XYData',v(:,16),'ZData',v(:,16)) % sixteenth eigenmode
5-966
pdeeig
Compute the eigenvalues that are less than 100, and compute the corresponding eigenmodes for
− ∇u = λu 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-23.
g = @lshapeg;
pdegplot(g,'EdgeLabels','on')
axis equal
ylim([-1.1,1.1])
5-967
5 Functions
ans = 9.6481
Import a simple 3-D geometry and find eigenvalues and eigenvectors from the associated finite
element matrices.
5-968
pdeeig
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-969
5 Functions
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];
ans = 2×1
-0.0000
42.8014
5-970
pdeeig
pdeplot3D(model,'ColorMapData',v(:,2))
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 = λdu on Ω
− ∇ ⋅ (c ⊗ ∇u) + au = λdu on Ω
Example: 'cosh(x+y.^2)'
5-971
5 Functions
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 = λdu on Ω
− ∇ ⋅ (c ⊗ ∇u) + au = λdu on Ω
Example: 2*eye(3)
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
− ∇ ⋅ (c ∇u) + au = λdu on Ω
− ∇ ⋅ (c ⊗ ∇u) + au = λdu on Ω
Example: 2*eye(3)
Data Types: double | char | string | function_handle
Complex Number Support: Yes
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. A boundary matrix is generally an export from the PDE Modeler
app.
Example: b = 'circleb1', b = "circleb1", or b = @circleb1
Data Types: double | char | string | function_handle
5-972
pdeeig
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 as [p,e,t] Triples” on page 2-181.
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 as [p,e,t] Triples” on page 2-181.
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
Mesh triangles, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For a description of the (p,e,t) matrices, see “Mesh Data as [p,e,t] Triples” on page 2-181.
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-
210. Typically, Kc is the output of assempde.
B — Dirichlet nullspace
sparse matrix
Dirichlet nullspace, returned as a sparse matrix. See “Algorithms” on page 5-210. 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-210.
To obtain the input matrices for pdeeig, hyperbolic or parabolic, run both assema and
assempde:
5-973
5 Functions
[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
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.
Note Eigenvectors are determined only up to multiple by a scalar, including a negative scalar.
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.
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.
5-974
pdeeig
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 = λdu
where λ is an unknown complex number. In solid mechanics, this is a problem associated with wave
phenomena describing, e.g., the natural modes of a vibrating membrane. In quantum mechanics λ is
the energy level of a bound state in the potential well a(x), where x represents a 2-D or 3-D point.
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
The matrices K and M are produced by calling assema for the equations
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 L-Shaped Membrane” on page 3-353 or “Eigenvalues and Eigenmodes of Square”
on page 3-364, 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 MU
λ−μ
5-975
5 Functions
This is a standard eigenvalue problem AU = θU, with the matrix A = (K – µM)-1M and eigenvalues
1
θi =
λi − μ
where i = 1, . . ., n. The largest eigenvalues θi of the transformed matrix A now correspond to the
eigenvalues λi = µ + 1/θi of the original pencil (K,M) closest to the shift µ.
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.)
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 jH j, j + v j + 1h j + 1, jeTj
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,
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, js 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-976
pdeeig
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,
P(K – µM)Q = LU
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
with one sparse matrix vector multiplication, a permutation, sparse forward- and back-substitutions,
and a final renumbering.
Version History
Introduced before R2006a
pdeeig is not recommended. Use solvepdeeig instead. There are no plans to remove pdeeig.
See Also
solvepdeeig
5-977
5 Functions
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 π/4 counterclockwise.
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 π/2 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-978
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 π/4 counterclockwise. Assign the name ellipse1 to this ellipse.
pdeellip(0,0,1,0.3,pi/4,"ellipse1")
5-979
5 Functions
Input Arguments
xc — x-coordinate of center
real number
yc — y-coordinate of center
real number
5-980
pdeellip
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
Version History
Introduced before R2006a
See Also
pdecirc | pdepoly | pderect | PDE Modeler
5-981
5 Functions
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;
0 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 1 1;
0 0 0 0 0 0 0 0 0 0.75 0.75;
0 0 0 0 0 0 0 0 0 0 0];
pdegplot(g)
5-982
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-983
5 Functions
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-984
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-985
5 Functions
Create and plot a 3-D geometry consisting of three nested cuboids of the same height. By default,
pdegplot uses lighting effects to display geometric features, like different cells, with more contrast.
5-986
pdegplot
To obtain the same plot appearance as in R2023a or earlier, turn off the lighting effects.
figure
pdegplot(gm,CellLabels="on",FaceAlpha=0.3,Lighting="off")
5-987
5 Functions
Input Arguments
g — Geometry description
femodel object | fegeometry object | PDEModel object | DiscreteGeometry object |
AnalyticGeometry object | output of decsg | decomposed geometry matrix | name of geometry file
| function handle to geometry file
• femodel object
• fegeometry object
• PDEModel object
• DiscreteGeometry object
• AnalyticGeometry object
• Output of decsg
• Decomposed geometry matrix (see “Decomposed Geometry Data Structure” on page 2-21)
• Name of geometry file (see “Parametrized Function for 2-D Geometry Creation” on page 2-23)
• Function handle to geometry file (see “Parametrized Function for 2-D Geometry Creation” on page
2-23)
5-988
pdegplot
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: pdegplot(g,FaceLabels="on")
Boundary edge labels for 2-D or 3-D geometry, specified as "off" or "on".
Data Types: char | string
Boundary face labels for 2-D or 3-D geometry, specified as "off" or "on".
Data Types: char | string
Surface transparency for 3-D geometry, specified as 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
5-989
5 Functions
Alternative Functionality
App
If you create a 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.
Version History
Introduced before R2006a
pdegplot now uses lighting effects by default to display geometric features with more contrast. To
obtain the same plot appearance as in the previous releases, you can turn off lighting effects by
setting the Lighting name-value argument to "off".
pdegplot shows faster rendering and better responsiveness for plots that display many text labels.
Code containing findobj(fig,'Type','Text') no longer returns labels on figures produced by
pdegplot.
You can now set plot transparency by using FaceAlpha, and display vertex and cell labels by using
VertexLabels and CellLabels, respectively.
The argument SubdomainLabels is no longer recommended. Use FaceLabels for 2-D geometries
instead.
See Also
Functions
pdeplot | pdeplot3D | pdemesh | decsg | importGeometry
Apps
PDE Modeler
5-990
pdegplot
Topics
“STL File Import” on page 2-43
“Solve Problems Using PDEModel Objects” on page 2-3
5-991
5 Functions
pdegrad
(Not recommended) Gradient of PDE solution
Syntax
[ux,uy] = pdegrad(p,t,u)
[ux,uy] = pdegrad(p,t,u,FaceID)
Description
[ux,uy] = pdegrad(p,t,u) returns the gradient of u evaluated at the center of each mesh
triangle.
The gradient is the same everywhere in the triangle interior because pdegrad uses only linear basis
functions. The derivatives at the boundaries of the triangles can be discontinuous.
Examples
[p,e,t] = initmesh('lshapeg');
c = 1;
a = 0;
f = 1;
u = assempde('lshapeb',p,e,t,c,a,f);
[gradx,grady] = pdegrad(p,t,u);
pdeplot(p,e,t,'XYData',u,'FlowData',[gradx;grady])
5-992
pdegrad
Input Arguments
p — Mesh nodes
matrix
Mesh nodes, specified as a 2-by-Np matrix of nodes (points), where Np is the number of nodes in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
t — Mesh elements
matrix
Mesh elements, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
u — Data at nodes
column vector
For a PDE system of N equations and a mesh with Np node points, the first Np values of u describe
the first component, the following Np values of u describe the second component, and so on.
5-993
5 Functions
Output Arguments
ux — x-component of the gradient of u evaluated at the center of each triangle
row vector | matrix
x-component of the gradient of u evaluated at the center of each triangle, returned as a row vector
for a scalar PDE or a matrix for a system of PDEs. The number of elements in a row vector or columns
in a matrix corresponds to the number Nt of mesh triangles. For a PDE system of N equations, each
∂ui
row i from 1 to N contains .
∂x
y-component of the gradient of u evaluated at the center of each triangle, returned as a row vector
for a scalar PDE or a matrix for a system of PDEs. The number of elements in a row vector or columns
in a matrix corresponds to the number Nt of mesh triangles. For a PDE system of N equations, each
∂ui
row i from 1 to N contains .
∂y
Version History
Introduced before R2006a
pdegrad is not recommended. Use evaluateGradient instead. There are no plans to remove
pdegrad.
See Also
evaluateGradient | pdecgrad
5-994
pdeInterpolant
pdeInterpolant
Interpolant for nodal data to selected locations
Note pdeInterpolant and [p,e,t] representation of FEMesh data are 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.
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
Use meshToPet to obtain the p and t data for interpolation using pdeInterpolant.
Input Arguments
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-184.
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-184.
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
5-995
5 Functions
Data values to interpolate, specified as a vector or matrix. Typically, u is the solution of a PDE
problem returned by assempde, parabolic, hyperbolic, or another solver. For example, u =
assempde(b,p,e,t,c,a,f). You can also export u from the Solve menu of the PDE Modeler app.
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
Create Interpolant
This example shows how to create a pdeInterpolant from the solution to a scalar PDE.
Solve the equation −Δu = 1 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
5-996
pdeInterpolant
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.
Version History
Introduced in R2014b
See Also
evaluate | tri2grid
Topics
“Mesh Data” on page 2-184
5-997
5 Functions
pdeintrp
(Not recommended) Interpolate mesh nodal data to triangle midpoints
Syntax
ut = pdeintrp(p,t,un)
Description
ut = pdeintrp(p,t,un) uses the data un at mesh nodes to linearly interpolate data at mesh
triangle midpoints.
pdeintrp and pdeprtni are not inverse functions because the interpolation introduces some
averaging.
Examples
Solve the equation −Δu = 1 on the L-shaped membrane and interpolate the solution from nodes to
triangle midpoints.
[p,e,t] = initmesh('lshapeg');
Solve the equation using the Dirichlet boundary condition u = 0 on ∂Ω. The result is the solution at
the mesh nodes.
un = assempde('lshapeb',p,e,t,1,0,1);
Interpolate the solution from the mesh nodes to the triangle midpoints.
ut = pdeintrp(p,t,un);
Interpolate the solution back to nodes by using the pdeprtni function. Compare the result and the
original solution at the mesh nodes. The pdeprtni and pdeintrp functions are not inverse.
un2 = pdeprtni(p,t,ut);
isequal(un,un2)
ans = logical
0
5-998
pdeintrp
Input Arguments
p — Mesh nodes
matrix
Mesh nodes, specified as a 2-by-Np matrix of nodes (points), where Np is the number of nodes in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
t — Mesh elements
matrix
Mesh elements, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
un — Data at nodes
column vector
For a PDE system of N equations and a mesh with Np node points, the first Np values of un describe
the first component, the following Np values of un describe the second component, and so on.
Data Types: double
Output Arguments
ut — Data at triangle midpoints
row vector
For a PDE system of N equations and a mesh with Nt elements, the first Nt values of ut describe the
first component, the following Nt values of ut describe the second component, and so on.
Version History
Introduced before R2006a
See Also
pdeprtni | evaluate | pdeInterpolant
Topics
“Mesh Data as [p,e,t] Triples” on page 2-181
5-999
5 Functions
pdejmps
(Not recommended) Error estimates for adaptation
Note pdejmps is not recommended. Use meshes represented as FEMesh objects instead of [p,e,t]
meshes. For more information, see “Compatibility Considerations”.
Syntax
errf = pdejmps(p,t,c,a,f,u,alpha,beta,m)
Description
errf = pdejmps(p,t,c,a,f,u,alpha,beta,m) calculates the error indication function used for
mesh adaptation. The columns of errf correspond to triangles, and the rows correspond to the
equations in the PDE system.
The function computes the error indicator E(K) for each triangle K as
1/2
m 1 2m 2
2 τ ∈∑∂K τ
E K =α h f − au K+β h [nτ ⋅ (c ∇uh)]
where nτ is the unit normal of edge τ and the braced term is the jump in flux across the element edge.
Here, α and β are weight indices, and m is an order parameter. The norm is an L2 norm computed
over the element K.
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. Use the original coarser mesh and
the refined mesh, and calculate the error indication function in both cases.
[p,e,t] = initmesh('cirsg');
pdemesh(p,e,t)
5-1000
pdejmps
u = assempde('cirsb',p,e,t,1,0,0);
Calculate the error indication function for each mesh triangle. Use the weight indices α = 0 . 15,
β = 0 . 15, and the order parameter m = 1.
alpha = 0.15;
beta = 0.15;
m = 1;
errf = pdejmps(p,t,1,0,0,u,alpha,beta,m);
max(abs(errf))
ans = 0.0306
[p,e,t] = refinemesh('cirsg',p,e,t);
pdemesh(p,e,t)
5-1001
5 Functions
Solve the same equation on the refined mesh, and calculate the error indication function for each
mesh triangle. Use the same values for the weight indices and the order parameter.
u = assempde('cirsb',p,e,t,1,0,0);
errf = pdejmps(p,t,1,0,0,u,alpha,beta,m);
ans = 0.0194
5-1002
pdejmps
pdemesh(p,e,t)
errf = pdejmps(p,t,1,0,0,u,alpha,beta,m);
max(abs(errf))
ans = 0.0024
Input Arguments
p — Mesh node points
matrix
Mesh node points, specified as a 2-by-Np matrix of points (nodes), where Np is the number of nodes in
the mesh. For details on mesh data representation, see initmesh.
Data Types: double
t — Mesh elements
4-by-Nt matrix
5-1003
5 Functions
Mesh elements, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For details on mesh data representation, see initmesh.
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
− ∇ ⋅ c ∇u + au = f
− ∇ ⋅ c ⊗ ∇u + au = f
The coefficients c, a, and f can depend on the solution u if you use the nonlinear solver by setting the
value of 'Nonlin' to 'on'. The coefficients cannot be functions of the time t.
Example: 'cosh(x+y.^2)'
Data Types: double | char | string | function_handle
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
The coefficients c, a, and f can depend on the solution u if you use the nonlinear solver by setting the
value of 'Nonlin' to 'on'. The coefficients cannot be functions of the time t.
Example: 2*eye(3)
Data Types: double | char | string | function_handle
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
The coefficients c, a, and f can depend on the solution u if you use the nonlinear solver by setting the
value of 'Nonlin' to 'on'. The coefficients cannot be functions of the time t.
Example: char('sin(x)';'cos(y)';'tan(z)')
5-1004
pdejmps
u — PDE solution
vector
• If the PDE is scalar, meaning that it 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 represent the solution of
equation 1, the next Np elements represent the solution of equation 2, and so on.
m — Order parameter
number
Output Arguments
errf — Error indicator
matrix
Error indicator, returned as a matrix with the number of columns equal to the number of triangles t
and the number of rows equal to the number of PDEs in the system.
Version History
Introduced before R2006a
pdejmps and [p,e,t] meshes are not recommended. Use meshes represented as FEMesh objects
instead. There are no plans to remove pdejmps and [p,e,t] meshes.
5-1005
5 Functions
Starting in R2016a, use the generateMesh function to create meshes as FEMesh objects. For details
about these meshes, see “Mesh Data” on page 2-184.
See Also
adaptmesh | initmesh | refinemesh
5-1006
pdemesh
pdemesh
Plot PDE mesh
Syntax
pdemesh(model)
pdemesh(fegeometry)
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.
pdemesh(fegeometry) plots the mesh represented by the Mesh property of an fegeometry object.
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.
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.
5-1007
5 Functions
model = createpde;
geometryFromEdges(model,@lshapeg);
mesh = generateMesh(model);
pdemesh(model)
pdemesh(mesh)
5-1008
pdemesh
Another approach is to use the nodes and elements of the mesh as input arguments for pdemesh.
pdemesh(mesh.Nodes,mesh.Elements)
5-1009
5 Functions
pdemesh(model,NodeLabels="on")
5-1010
pdemesh
xlim([-0.4,0.4])
ylim([-0.4,0.4])
5-1011
5 Functions
pdemesh(model,ElementLabels="on")
xlim([-0.4,0.4])
ylim([-0.4,0.4])
5-1012
pdemesh
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:
u = results.NodalSolution;
pdemesh(model,u)
5-1013
5 Functions
The pdemesh function ignores NodeLabels and ElementLabels when you plot solution data as a 3-
D plot.
model = createpde;
importGeometry(model,"Plate10x10x1.stl");
generateMesh(model,Hmax=5);
pdemesh(model,FaceAlpha=0.5)
5-1014
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-1015
5 Functions
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-1016
pdemesh
[p,e,t] = initmesh("lshapeg");
[p,e,t] = refinemesh("lshapeg",p,e,t);
pdemesh(p,e,t)
5-1017
5 Functions
Now solve Poisson's equation −Δu = 1 over the geometry defined by the L-shaped membrane. Use
Dirichlet boundary conditions u = 0 on δΩ, and plot the result.
u = assempde("lshapeb",p,e,t,1,0,1);
pdemesh(p,e,t,u)
5-1018
pdemesh
Input Arguments
model — Model container
femodel object | PDEModel object | ThermalModel object | StructuralModel object |
ElectromagneticModel object
u — PDE solution
vector | matrix
Geometry object for finite element analysis, specified as an fegeometry object. The pdemesh
function plots the mesh from the Mesh property of the fegeometry object.
5-1019
5 Functions
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-1020
pdemesh
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 as [p,e,t] Triples” on page 2-181.
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 as [p,e,t] Triples” on page 2-181.
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
Mesh triangles, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For a description of the (p,e,t) matrices, see “Mesh Data as [p,e,t] Triples” on page 2-181.
5-1021
5 Functions
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
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: pdemesh(model,NodeLabels="on")
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 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 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.
5-1022
pdemesh
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
Version History
Introduced before R2006a
pdemesh shows faster rendering and better responsiveness for plots that display many text labels.
Code containing findobj(fig,'Type','Text') no longer returns labels on figures produced by
pdemesh.
5-1023
5 Functions
pdemesh accepts node and element IDs as input arguments, letting you highlight particular nodes
and elements on mesh plots.
You can now set plot transparency by using FaceAlpha, and display node and element labels by
using NodeLabels and ElementLabels, respectively.
See Also
Functions
pdeplot | pdeplot3D | pdegplot
Topics
“Mesh Data” on page 2-184
5-1024
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, specified as a positive integer. See “Equations You Can Solve Using PDE
Toolbox” on page 1-3.
Example: 1
Data Types: double
PDE boundary conditions, specified as a vector of BoundaryCondition objects. You create boundary
conditions using the applyBoundaryCondition function
Mesh for solution, specified as an FEMesh object. You create the mesh using the generateMesh
function.
Indicator if model is time-dependent, specified as 1 (true) or 0 (false). The property is true when
the m or d coefficient is nonzero, and is false otherwise.
5-1025
5 Functions
In case of GeometricInitialConditions, for time-dependent problems, you must give one or two
initial conditions: one if the m coefficient is zero, and two if the m coefficient is nonzero. For nonlinear
stationary problems, you can optionally give an initial solution that solvepde uses to start its
iterations. See setInitialConditions.
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.
Algorithm options for the PDE solvers, specified 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 from decomposed geometry matrix
geometryFromMesh Create 2-D or 3-D geometry from mesh
importGeometry Import geometry from STL or STEP file
setInitialConditions Give initial conditions or initial solution
specifyCoefficients Specify coefficients in PDE model
solvepde Solve PDE specified in a PDEModel
solvepdeeig Solve PDE eigenvalue problem specified in a PDEModel
Examples
model =
PDEModel with properties:
PDESystemSize: 1
5-1026
PDEModel
IsTimeDependent: 0
Geometry: []
EquationCoefficients: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
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:
Version History
Introduced in R2015a
See Also
createpde | applyBoundaryCondition | generateMesh | geometryFromEdges |
geometryFromMesh | importGeometry | pdegplot | pdeplot | pdeplot3D |
setInitialConditions | specifyCoefficients
Topics
“Solve Problems Using PDEModel Objects” on page 2-3
5-1027
5 Functions
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(b,p,e,t,c,a,f) solves the PDE with boundary conditions b, and finite element
mesh (p,e,t).
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.
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);
5-1028
pdenonlin
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)
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.
5-1029
5 Functions
g = @circleg;
pdegplot(g,'EdgeLabels','on')
axis equal
Create Dirichlet boundary conditions with value x2.Create the following file and save it on your
MATLAB path.
function [qmatrix,gmatrix,hmatrix,rmatrix] = pdex2bound(p,e,u,time)
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}
hmatrix(k) = 1;
hmatrix(k+ne) = 1;
rmatrix(k) = x1^2;
rmatrix(k+ne) = x2^2;
5-1030
pdenonlin
end
end
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)
Import the geometry from the BracketWithHole.stl file. Plot the geometry and face labels.
model = createpde();
importGeometry(model,'BracketWithHole.stl');
figure
5-1031
5 Functions
pdegplot(model,'FaceLabels','on','FaceAlpha',0.5)
view(30,30)
title('Bracket with Face Labels')
figure
pdegplot(model,'FaceLabels','on','FaceAlpha',0.5)
view(-134,-32)
title('Bracket with Face Labels, Rear View')
5-1032
pdenonlin
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';
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');
5-1033
5 Functions
pdeplot3D(model,'ColorMapData',u)
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
Example: 'cosh(x+y.^2)'
5-1034
pdenonlin
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
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
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.
Example: b = 'circleb1', b = "circleb1", or b = @circleb1
Data Types: double | char | string | function_handle
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 as [p,e,t] Triples” on page 2-181.
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)
5-1035
5 Functions
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 as [p,e,t] Triples” on page 2-181.
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
Mesh triangles, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For a description of the (p,e,t) matrices, see “Mesh Data as [p,e,t] Triples” on page 2-181.
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
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: 'Jacobian','full'
• '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-
1038. This approximation is based on the numerical differentiation of the coefficients.
Example: u = pdenonlin(model,c,a,f,'Jacobian','full')
Data Types: char | string
5-1036
pdenonlin
Initial solution guess, specified as a scalar, a vector of characters, or a vector of numbers. A scalar
specifies a constant initial condition for either a scalar or PDE system.
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 as [p,e,t] Triples” on page 2-181.
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')
Data Types: double | char | string
Complex Number Support: Yes
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-1037
5 Functions
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 “3-D Solution and Gradient Plots with
MATLAB Functions” on page 3-391.
Norm of Newton step residuals, returned as a scalar. For information about the algorithm, see
“Nonlinear Equations” on page 5-1038.
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 obtain better results
by scaling the coefficients or geometry dimensions to be of order one.
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 jϕ j
5-1038
pdenonlin
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
0=ρU = ∑
j Ω
∫ c x, U ∇ϕ j(x) ⋅ ∇ϕ j(x) + a x, U ϕ j(x)ϕi(x) dx
+ ∫ q x, U ϕ (x)ϕ (x) ds U
∂Ω
j i j
− ∫ f x, U ϕ (x) dx − ∫ g x, U ϕ (x) ds
Ω
i
∂Ω
i
ρ(U) = (K + M + Q)U – (F + G)
where the matrices K, M, Q and the vectors F and G are produced by assembling the problem
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
∂ρ U(n)
U(n + 1) − U(n) = − αρ U(n)
∂U
where α 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 residual, i.e., the solution of
minU ρ(U) .
and
−1
∂ρ U(n)
pn = ρ U(n)
∂U
is called a descent direction for ρ(U) , where ⋅ is the L2-norm. The iteration is
where α ≤ 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:
5-1039
5 Functions
α
ρ U(n) − ρ U(n) + αpn ≥ ρ U(n)
2
which guarantees a reduction of the residual norm by at least 1 – α/2. Each step of the line-search
algorithm requires an evaluation of the residual ρ U(n) + αpn .
An important point of this strategy is that when U(n) approaches the solution, then α→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
U(1) = K–1F
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.
∂ρ U(n)
Jn =
∂U
is not available. Approximation of Jn by finite differences in the following way is expensive but
feasible. The ith column of Jn can be approximated by
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.
This is equivalent to approximating the Jacobian with the stiffness matrix. Indeed, since ρ(U(n)) =
KU(n) – F, putting Jn = K yields
In many cases the convergence rate is slow, but the cost of each iteration is cheap.
5-1040
pdenonlin
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
∂U j
1
= lim ∑
ε 0ε l
∫c U + εϕ
Ω
j ∇ϕl ∇ϕi dx Ul + εδl, j
− ∫c U ∇ϕ ∇ϕ dxU
Ω
l i l
= ∫c U ∇ϕ ∇ϕ dx + ∑ ∫ϕ ∂u
Ω
j
∂c
i ∇ϕ ∇ϕ dxU
l Ω
j l i l
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
δi, j ∑
l Ω
∫ ∂u
∂c
∇ϕ ∇ϕ dxU
l i l
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
− ∫ ∂u
Ω
∂f
ϕ ϕ dx i j
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 μ 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
5-1041
5 Functions
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.
Version History
Introduced before R2006a
pdenonlin is not recommended. Use solvepde instead. There are no plans to remove pdenonlin.
See Also
solvepde
5-1042
pdeplot
pdeplot
Plot solution or mesh for 2-D problem
Syntax
pdeplot(results.Mesh,XYData=results.NodalSolution)
pdeplot(results.Mesh,XYData=results.Temperature,ColorMap="hot")
pdeplot(results.Mesh,XYData=results.VonMisesStress,Deformation=results.Displa
cement)
pdeplot(results.Mesh,XYData=results.ModeShapes.ux)
pdeplot(results.Mesh,XYData=results.ElectricPotential)
pdeplot(mesh)
pdeplot(nodes,elements)
pdeplot(model)
pdeplot(p,e,t)
Description
pdeplot(results.Mesh,XYData=results.NodalSolution) plots the solution at nodal locations
as a colored surface plot using the default "cool" colormap.
pdeplot(results.Mesh,XYData=results.VonMisesStress,Deformation=results.Displa
cement) plots the von Mises stress and shows the deformed shape for a 2-D structural analysis
problem.
pdeplot(model) plots the mesh specified in model. This syntax does not work with an femodel
object.
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.
5-1043
5 Functions
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 the mesh.
model = createpde;
geometryFromEdges(model,@lshapeg);
mesh = generateMesh(model);
pdeplot(mesh)
5-1044
pdeplot
pdeplot(model)
Another approach is to use the nodes and elements of the mesh as input arguments for pdeplot.
pdeplot(mesh.Nodes,mesh.Elements)
5-1045
5 Functions
Display the node labels. Use xlim and ylim to zoom in on particular nodes.
pdeplot(mesh,NodeLabels="on")
xlim([-0.2,0.2])
ylim([-0.2,0.2])
5-1046
pdeplot
pdeplot(mesh,ElementLabels="on")
xlim([-0.2,0.2])
ylim([-0.2,0.2])
5-1047
5 Functions
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);
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)
5-1048
pdeplot
results =
StationaryResults with properties:
u = results.NodalSolution;
msh = results.Mesh;
pdeplot(msh,XYData=u)
pdeplot(msh,XYData=u,ZData=u)
5-1049
5 Functions
Create a PDE model. Include the geometry of the built-in function lshapeg. Mesh the geometry.
model = createpde;
geometryFromEdges(model,@lshapeg);
generateMesh(model);
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)
5-1050
pdeplot
results =
StationaryResults with properties:
Plot the gradient of the solution at the nodal locations as a quiver plot.
ux = results.XGradients;
uy = results.YGradients;
msh = results.Mesh;
pdeplot(msh,FlowData=[ux,uy])
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.
5-1051
5 Functions
model = createpde;
geometryFromEdges(model,@lshapeg);
generateMesh(model);
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:
Plot the solution in 3-D with the "jet" coloring and a mesh, and include the gradient as a quiver
plot.
u = results.NodalSolution;
ux = results.XGradients;
uy = results.YGradients;
msh = results.Mesh;
h = pdeplot(msh,XYData=u,ZData=u, ...
FaceAlpha=0.5, ...
FlowData=[ux,uy], ...
ColorMap="jet", ...
Mesh="on");
5-1052
pdeplot
thermalmodel = createpde(thermal="transient");
5-1053
5 Functions
• Thermal conductivity is 10 W/ m ⋅∘ C
• Mass density is 2 kg/m3
• Specific heat is 0 . 1 J/ kg ⋅ ∘C
thermalProperties(thermalmodel,ThermalConductivity=10, ...
MassDensity=2, ...
SpecificHeat=0.1, ...
Face=1);
• Thermal conductivity is 2 W/ m ⋅∘ C
• Mass density is 1 kg/m3
• Specific heat is 0 . 1 J/ kg ⋅ ∘C
thermalProperties(thermalmodel,ThermalConductivity=2, ...
MassDensity=1, ...
SpecificHeat=0.1, ...
Face=2);
Assume that the diamond-shaped region is a heat source with a density of 4 W/m2.
internalHeatSource(thermalmodel,4,Face=2);
5-1054
pdeplot
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 most active 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);
T = thermalresults.Temperature;
msh = thermalresults.Mesh;
pdeplot(msh,XYData=T(:,10),Contour="on",ColorMap="hot")
5-1055
5 Functions
Create the geometry and include it in the model. Plot the geometry.
geometryFromEdges(structuralmodel,@squareg);
pdegplot(structuralmodel,EdgeLabels="on")
axis equal
5-1056
pdeplot
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(structuralresults.Mesh, ...
XYData=structuralresults.VonMisesStress, ...
Deformation=structuralresults.Displacement, ...
ColorMap="jet")
pdeplot(structuralresults.Mesh, ...
XYData=structuralresults.VonMisesStress, ...
Deformation=structuralresults.Displacement, ...
DeformationScaleFactor=500,...
ColorMap="jet")
5-1057
5 Functions
pdeplot(structuralresults.Mesh, ...
XYData=structuralresults.VonMisesStress, ...
ColorMap="jet")
5-1058
pdeplot
Find the fundamental (lowest) mode of a 2-D cantilevered beam, assuming prevalence of the plane-
stress condition.
Specify 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);
5-1059
5 Functions
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.
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
ans =
FEStruct with properties:
5-1060
pdeplot
pdeplot(modalresults.Mesh,XYData=modalresults.ModeShapes.uy(:,1))
title(['First Mode with Frequency ', ...
num2str(modalresults.NaturalFrequencies(1)/(2*pi)),' Hz'])
axis equal
Solve an electromagnetic problem and find the electric potential and field distribution for a 2-D
geometry representing a plate with a hole.
emagmodel = createpde(electromagnetic="electrostatic");
importGeometry(emagmodel,"PlateHolePlanar.stl");
pdegplot(emagmodel,EdgeLabels="on")
5-1061
5 Functions
emagmodel.VacuumPermittivity = 8.8541878128E-12;
electromagneticProperties(emagmodel,RelativePermittivity=1);
Apply the voltage boundary conditions on the edges framing the rectangle and the circle.
electromagneticBC(emagmodel,Voltage=0,Edge=1:4);
electromagneticBC(emagmodel,Voltage=1000,Edge=5);
electromagneticSource(emagmodel,ChargeDensity=5E-9);
generateMesh(emagmodel);
R = solve(emagmodel)
R =
ElectrostaticResults with properties:
5-1062
pdeplot
pdeplot(R.Mesh,XYData=R.ElectricPotential, ...
FlowData=[R.ElectricField.Ex ...
R.ElectricField.Ey])
axis equal
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);
pdeplot(p,e,t)
5-1063
5 Functions
pdeplot(p,e,t,XYData=u)
5-1064
pdeplot
pdeplot(p,e,t,XYData=u,ZData=u)
5-1065
5 Functions
Input Arguments
mesh — Mesh description
FEMesh object
Element connectivity matrix in terms of the node IDs, specified as a 3-by-NumElements or 6-by-
NumElements matrix. Linear meshes contain only corner nodes. For linear meshes, the connectivity
matrix has three nodes per 2-D element. Quadratic meshes contain corner nodes and nodes in the
middle of each edge of an element. For quadratic meshes, the connectivity matrix has six nodes per 2-
D element.
5-1066
pdeplot
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 as [p,e,t] Triples” on page 2-181.
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 as [p,e,t] Triples” on page 2-181.
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
Mesh triangles, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For a description of the (p,e,t) matrices, see “Mesh Data as [p,e,t] Triples” on page 2-181.
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)
5-1067
5 Functions
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: pdeplot(results.Mesh,XYData=u,ZData=u)
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 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 an FEMesh object, specify:
results = solvepde(model);
u = results.NodalSolution; % each column of u has one component of u
pdeplot(results.Mesh,XYData=u(:,k)) % data for column k
Example: XYData=u
Data Types: double
5-1068
pdeplot
Data for the 3-D plot heights, specified as 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 an FEMesh object, specify:
results = solvepde(model);
u = results.NodalSolution; % each column of u has one component of u
pdeplot(results.Mesh,XYData=u(:,k),ZData=u(:,k)) % data for column k
Example: ZData=u
Data Types: double
If you use ZStyle without specifying the ZData name-value pair, then pdeplot ignores ZStyle.
Example: ZStyle="discontinuous"
5-1069
5 Functions
Data for the quiver plot on page 5-1073, specified as 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;
msh = results.Mesh;
pdeplot(msh,FlowData=[gradx grady])
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 "arrow" or "off". Here, "arrow" displays the quiver
plot on page 5-1073 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 "off" or "on".
Note This conversion can change the geometry and lessen the quality of the plot.
5-1070
pdeplot
[~,tn,a2,a3] = tri2grid(p,t,u,x,y);
pdeplot(p,e,t,XYGrid="on",GridParam=[tn;a2;a3],XYData=u)
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 Displacement
property of the StaticStructuralResults object.
In an undeformed shape, center nodes in quadratic meshes are always added at half-distance
between corners. When you plot a deformed shape, the center nodes might move away from the edge
centers.
Example: Deformation = structuralresults.Displacement
Scaling factor for plotting the deformed shape, specified as 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
5-1071
5 Functions
Indicator to include a color bar, specified as "on" or "off". Specify "on" to display a bar giving the
numeric values of colors in the plot. For details, see colorbar. The pdeplot function uses the
colormap specified in the ColorMap name-value pair.
Example: ColorBar="off"
Data Types: char | string
ColorMap — Colormap
"cool" (default) | ColorMap value or matrix of such values
Colormap, specified as a value representing a built-in colormap, or a colormap matrix. For details, see
colormap.
Indicator to show the mesh, specified as "on" or "off". Specify "on" to show the mesh in the plot.
Example: Mesh="on"
Data Types: char | string
Surface transparency for 3-D geometry, specified as 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
Indicator to plot level curves, specified as "off" or "on". Specify "on" to plot level curves for the
XYData data. Specify the levels with the Levels name-value pair.
Example: Contour="on"
5-1072
pdeplot
Levels for contour plot, specified as a positive integer or a vector of level values.
Output Arguments
h — Handles to graphics objects
vector
More About
Quiver 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.
Version History
Introduced before R2006a
You can now plot electromagnetic results, such as electric and magnetic potentials, fields, and fluxes.
pdeplot shows faster rendering and better responsiveness for plots that display many text labels.
Code containing findobj(fig,'Type','Text') no longer returns labels on figures produced by
pdeplot.
pdeplot accepts node and element IDs as input arguments, letting you highlight particular nodes
and elements on mesh plots.
5-1073
5 Functions
You can now plot structural results, such as displacements, stresses, and strains.
You can now plot thermal results, such as temperatures and temperature gradients.
You can now set plot transparency by using FaceAlpha, and display node and element labels by
using NodeLabels and ElementLabels, respectively.
See Also
Functions
pdegplot | pdemesh | pdeplot3D | pdeviz
Topics
“Solution and Gradient Plots with pdeplot and pdeplot3D” on page 3-376
“Deflection of Piezoelectric Actuator” on page 3-10
“Mesh Data” on page 2-184
“Solve Problems Using PDEModel Objects” on page 2-3
5-1074
pdeplot3D
pdeplot3D
Plot solution or surface mesh for 3-D problem
Syntax
pdeplot3D(results.Mesh,ColorMapData=results.NodalSolution)
pdeplot3D(results.Mesh,ColorMapData=results.Temperature)
pdeplot3D(results.Mesh,ColorMapData=results.VonMisesStress,Deformation=result
s.Displacement)
pdeplot3D(results.Mesh,ColorMapData=results.ElectricPotential)
pdeplot3D(mesh)
pdeplot3D(nodes,elements)
pdeplot3D(model)
Description
pdeplot3D(results.Mesh,ColorMapData=results.NodalSolution) plots the solution at
nodal locations.
pdeplot3D(results.Mesh,ColorMapData=results.VonMisesStress,Deformation=result
s.Displacement) plots the von Mises stress and shows the deformed shape for a 3-D structural
analysis problem.
pdeplot3D(model) plots the surface mesh specified in model. This syntax does not work with an
femodel object.
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
5-1075
5 Functions
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;
msh = results.Mesh;
pdeplot3D(model,ColorMapData=u)
5-1076
pdeplot3D
thermalmodel = createpde(thermal="steadystate");
importGeometry(thermalmodel,"Block.stl");
pdegplot(thermalmodel,FaceLabels="on",FaceAlpha=0.5)
axis equal
thermalProperties(thermalmodel,ThermalConductivity=80);
Apply a constant temperature of 100 °C to the left side of the block (face 1) and a constant
temperature of 300 °C 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-1077
5 Functions
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 the nodal locations.
pdeplot3D(thermalresults.Mesh,ColorMapData=thermalresults.Temperature)
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.
5-1078
pdeplot3D
thermalmodel = createpde(thermal="steadystate");
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 /(cmK).
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).
thermalBC(thermalmodel,Face=1,Temperature=373);
thermalBC(thermalmodel,Face=3,Temperature=573);
thermalBC(thermalmodel,Face=4,HeatFlux=-20);
generateMesh(thermalmodel);
thermalresults = solve(thermalmodel)
5-1079
5 Functions
thermalresults =
SteadyStateThermalResults with properties:
[qx,qy,qz] = evaluateHeatFlux(thermalresults);
figure
pdeplot3D(thermalresults.Mesh,FlowData=[qx qy qz])
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));
5-1080
pdeplot3D
figure
quiver3(X,Y,Z,qx,qy,qz)
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-1081
5 Functions
structuralmodel = createpde(structural="static-solid");
importGeometry(structuralmodel,"SquareBeam.stl");
pdegplot(structuralmodel,FaceLabels="on",FaceAlpha=0.5)
5-1082
pdeplot3D
structuralProperties(structuralmodel,PoissonsRatio=0.3, ...
YoungsModulus=210E3);
structuralBC(structuralmodel,Face=6,Constraint="fixed");
structuralBoundaryLoad(structuralmodel,Face=5, ...
SurfaceTraction=[0;0;-2]);
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(structuralresults.Mesh, ...
ColorMapData=structuralresults.VonMisesStress, ...
Deformation=structuralresults.Displacement)
5-1083
5 Functions
figure
pdeplot3D(structuralresults.Mesh, ...
ColorMapData=structuralresults.VonMisesStress, ...
Deformation=structuralresults.Displacement, ...
DeformationScaleFactor=500)
5-1084
pdeplot3D
figure
pdeplot3D(structuralresults.Mesh, ...
ColorMapData=structuralresults.VonMisesStress)
5-1085
5 Functions
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-1086
pdeplot3D
Specify Young's modulus, Poisson's ratio, and the 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);
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);
5-1087
5 Functions
vmStress = evaluateVonMisesStress(structuralresults);
figure
pdeplot3D(structuralresults.Mesh,ColorMapData = vmStress(:,end))
title("von Mises Stress in the Beam for the Last Time-Step")
Solve an electromagnetic problem and find the electric potential and field distribution for a 3-D
geometry representing a plate with a hole.
emagmodel = createpde(electromagnetic="electrostatic");
gm = importGeometry(emagmodel,"PlateHoleSolid.stl");
pdegplot(gm,FaceLabels="on",FaceAlpha=0.3)
5-1088
pdeplot3D
emagmodel.VacuumPermittivity = 8.8541878128E-12;
electromagneticProperties(emagmodel,RelativePermittivity=1);
electromagneticSource(emagmodel,ChargeDensity=5E-9);
Apply the voltage boundary conditions on the side faces and the face bordering the hole.
electromagneticBC(emagmodel,Voltage=0,Face=3:6);
electromagneticBC(emagmodel,Voltage=1000,Face=7);
generateMesh(emagmodel);
R = solve(emagmodel)
R =
ElectrostaticResults with properties:
5-1089
5 Functions
figure
pdeplot3D(R.Mesh,ColorMapData=R.ElectricPotential)
pdeplot3D(R.Mesh,FlowData=[R.ElectricField.Ex ...
R.ElectricField.Ey ...
R.ElectricField.Ez])
5-1090
pdeplot3D
model = createpde;
importGeometry(model,"Tetrahedron.stl");
mesh = generateMesh(model,Hmax=20,GeometricOrder="linear");
pdeplot3D(mesh)
5-1091
5 Functions
pdeplot3D(model)
5-1092
pdeplot3D
Another approach is to use the nodes and elements of the mesh as input arguments for pdeplot3D.
pdeplot3D(mesh.Nodes,mesh.Elements)
5-1093
5 Functions
pdeplot3D(mesh,NodeLabels="on")
view(101,12)
5-1094
pdeplot3D
pdeplot3D(mesh,ElementLabels="on")
view(101,12)
5-1095
5 Functions
Input Arguments
model — Model container
PDEModel object | ThermalModel object | StructuralModel object | ElectromagneticModel
object
Element connectivity matrix in terms of the node IDs, specified as a 4-by-NumElements or 10-by-
NumElements matrix. Linear meshes contain only corner nodes. For linear meshes, the connectivity
matrix has four nodes per 3-D element. Quadratic meshes contain corner nodes and nodes in the
5-1096
pdeplot3D
middle of each edge of an element. For quadratic meshes, the connectivity matrix has 10 nodes per 3-
D element.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: pdeplot3D(model,NodeLabels="on")
Data for the quiver plot on page 5-1073, 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:
5-1097
5 Functions
results = solvepde(model);
[cgradx,cgrady,cgradz] = evaluateCGradient(results);
pdeplot3D(results.Mesh,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
Node labels, specified as the comma-separated pair consisting of "NodeLabels" and "off" or "on".
Example: NodeLabels="on"
Data Types: char | string
Element labels, specified as the comma-separated pair consisting of "ElementLabels" and "off"
or "on".
Example: ElementLabels="on"
Data Types: char | string
Surface transparency for 3-D geometry, specified as 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
Deformed shape for structural analysis models, specified as the comma-separated pair consisting of
Deformation and the FEStruct object representing displacement values at nodes. The
displacement FEStruct object is a property of StaticStructuralResults,
TransientStructuralResults, and FrequencyStructuralResults.
In an undeformed shape, center nodes in quadratic meshes are always added at half-distance
between corners. When you plot a deformed shape, the center nodes might move away from the edge
centers.
5-1098
pdeplot3D
Example: Deformation=results.Displacement
Scaling factor for plotting the deformed shape, specified as the comma-separated pair consisting of
DeformationScaleFactor and a positive number. Use this argument together with the
Deformation name-value pair argument. The pdeplot3D function chooses the default value based
on the geometry itself and on the magnitude of deformation.
Example: DeformationScaleFactor=1000
Data Types: double
Output Arguments
h — Handles to graphics objects
vector
Version History
Introduced in R2015a
pdeplot3d accepts the femodel object that defines structural mechanics, thermal, and
electromagnetic problems.
You can now plot electromagnetic results, such as electric and magnetic potentials, fields, and fluxes.
pdeplot3d shows faster rendering and better responsiveness for plots that display many text labels.
Code containing findobj(fig,'Type','Text') no longer returns labels on figures produced by
pdeplot3d.
pdeplot3d accepts node and element IDs as input arguments, letting you highlight particular nodes
and elements on mesh plots.
You can now plot structural results, such as displacements, stresses, and strains.
5-1099
5 Functions
You can now plot thermal results, such as temperatures and temperature gradients.
You can now set plot transparency by using FaceAlpha, and display node and element labels by
using NodeLabels and ElementLabels, respectively.
See Also
PDEModel | pdeplot | pdegplot | pdemesh
Topics
“3-D Solution and Gradient Plots with MATLAB Functions” on page 3-391
“Solve Problems Using PDEModel Objects” on page 2-3
5-1100
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.
pdepoly(X,Y,label) assigns a name to the polygon. Otherwise, pdepoly uses a default name,
such as P1, P2, and so on.
Examples
Open the PDE Modeler app window containing a polygon representing the L-shaped membrane
geometry.
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-1101
5 Functions
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-1102
pdepoly
Input Arguments
X — x-coordinates of vertices
vector of real numbers
Y — y-coordinates of vertices
vector of real numbers
5-1103
5 Functions
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,'.-')
Version History
Introduced before R2006a
See Also
pdecirc | pdeellip | pderect | PDE Modeler
5-1104
pdeprtni
pdeprtni
(Not recommended) Interpolate triangle midpoint data to mesh nodes
Syntax
un = pdeprtni(p,t,ut)
Description
un = pdeprtni(p,t,ut) uses the data ut at mesh triangle midpoints to linearly interpolate data at
mesh nodes.
pdeprtni and pdeintrp are not inverse functions because the interpolation introduces some
averaging.
Examples
Solve the equation −Δu = 1 on the L-shaped membrane and interpolate the solution from nodes to
triangle midpoints.
[p,e,t] = initmesh('lshapeg');
Solve the equation using the Dirichlet boundary condition u = 0 on ∂Ω. The result is the solution at
the mesh nodes.
un = assempde('lshapeb',p,e,t,1,0,1);
Interpolate the solution from the mesh nodes to the triangle midpoints.
ut = pdeintrp(p,t,un);
Interpolate the solution back to nodes by using the pdeprtni function. Compare the result and the
original solution at the mesh nodes. The pdeprtni and pdeintrp functions are not inverse.
un2 = pdeprtni(p,t,ut);
isequal(un,un2)
ans = logical
0
5-1105
5 Functions
Input Arguments
p — Mesh nodes
matrix
Mesh nodes, specified as a 2-by-Np matrix of nodes (points), where Np is the number of nodes in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
t — Mesh elements
matrix
Mesh elements, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
For a PDE system of N equations and a mesh with Nt elements, the first Nt values of ut describe the
first component, the following Nt values of ut describe the second component, and so on.
Output Arguments
un — Data at nodes
column vector
For a PDE system of N equations and a mesh with Np node points, the first Np values of un describe
the first component, the following Np values of un describe the second component, and so on.
Data Types: double
Version History
Introduced before R2006a
See Also
pdeintrp | evaluate | pdeInterpolant
Topics
“Mesh Data as [p,e,t] Triples” on page 2-181
5-1106
pderect
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.
pderect([xmin xmax ymin ymax], label) assigns a name to the rectangle. Otherwise,
pderect uses a default name, such as R1, R2, and so on. For squares, pderect uses the default
names SQ1, SQ2, and so on.
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).
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-1107
5 Functions
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-1108
pderect
Input Arguments
[xmin xmax ymin ymax] — Corner coordinates
vector of real numbers
label — Name
character vector | string scalar
5-1109
5 Functions
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]).
Version History
Introduced before R2006a
See Also
pdecirc | pdeellip | pdepoly | PDE Modeler
5-1110
pdesdp
pdesdp
(Not recommended) Indices of subset of mesh nodes belonging to specified faces of 2-D geometry
Syntax
s = pdesdp(p,e,t,FaceID)
[i,c] = pdesdp(p,e,t,FaceID)
___ = pdesdp(p,e,t)
Description
s = pdesdp(p,e,t,FaceID) returns the indices of the nodes of the [p,e,t] mesh shared
between two or more faces listed in FaceID.
[i,c] = pdesdp(p,e,t,FaceID) returns the indices of the nodes of the [p,e,t] mesh belonging
strictly to faces FaceID as i. It also returns the indices of the nodes shared between FaceID and
faces not listed in FaceID as c.
___ = pdesdp(p,e,t) uses any of the previous syntaxes, assuming that FaceID is a list of all
faces of a 2-D geometry.
Examples
Find the indices of the mesh nodes belonging strictly to the specified faces and the indices of the
nodes shared between faces.
Define two circles and a rectangle and place these in one matrix.
R1 = [3,4,-1,1,1,-1,0.5,0.5,-0.75,-0.75]';
C1 = [1,-0.5,-0.25,0.25]';
C2 = [1,0.5,-0.25,0.25]';
C1 = [C1;zeros(length(R1) - length(C1),1)];
C2 = [C2;zeros(length(R1) - length(C2),1)];
gd = [R1,C1,C2];
sf = 'R1+C1+C2';
ns = char('R1','C1','C2');
ns = ns';
gd = decsg(gd,sf,ns);
pdegplot(gd,'FaceLabels','on')
5-1111
5 Functions
Create a mesh.
[p,e,t] = initmesh(gd);
pdemesh(p,e,t,'NodeLabels','on')
5-1112
pdesdp
Find the indices of the mesh nodes shared between faces 1 and 2.
s1 = pdesdp(p,e,t,[1 2])
s1 = 1×8
5 6 7 8 13 14 15 16
Find the indices of the mesh nodes shared between faces 2 and 3. Since these faces do not share any
nodes, pdesdp returns an empty vector.
s2 = pdesdp(p,e,t,[2 3])
s2 =
Find the nodes belonging strictly to face 2 and also the nodes shared between face 2 and other faces.
Face 2 shares nodes only with face 1, therefore, vectors c and s1 consist of the same face IDs.
[i,c] = pdesdp(p,e,t,2)
i = 1×5
56 88 90 91 92
5-1113
5 Functions
c = 1×8
5 6 7 8 13 14 15 16
Input Arguments
p — Mesh nodes
matrix
Mesh nodes, specified as a 2-by-Np matrix of nodes (points), where Np is the number of nodes in the
mesh. For details on the mesh data representation, see initmesh.
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
details on the mesh data representation, see initmesh.
Data Types: double
t — Mesh elements
matrix
Mesh elements, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
Output Arguments
s — Mesh nodes shared between two or more specified faces
row vector of positive integers
Mesh nodes shared between two or more specified faces, returned as a row vector of positive
integers representing the indices of the nodes.
Mesh nodes belonging only to specified faces, returned as a row vector of positive integers
representing the indices of the nodes.
5-1114
pdesdp
Mesh nodes shared between specified and other faces, returned as a row vector of positive integers
representing the indices of the nodes.
Version History
Introduced before R2006a
pdesdp is not recommended. Use findNodes instead. There are no plans to remove pdesdp.
See Also
pdesde | pdesdt
Topics
“Mesh Data as [p,e,t] Triples” on page 2-181
5-1115
5 Functions
pdesde
(Not recommended) Indices of edges of mesh elements belonging to the specified faces of 2-D
geometry
Syntax
i = pdesde(e,FaceID)
i = pdesde(e)
Description
i = pdesde(e,FaceID) returns the indices of the [p,e,t] mesh edges that belong to outer
boundaries of the geometry for a set of faces listed in FaceID.
Examples
Find the indices of the mesh elements' edges located on the outer boundaries of the geometry and
belonging to the specified faces.
Define two circles and a rectangle and place these in one matrix.
R1 = [3,4,-1,1,1,-1,0.5,0.5,-0.75,-0.75]';
C1 = [1,-0.5,-0.25,0.25]';
C2 = [1,0.5,-0.25,0.25]';
C1 = [C1;zeros(length(R1) - length(C1),1)];
C2 = [C2;zeros(length(R1) - length(C2),1)];
gd = [R1,C1,C2];
Create a set formula that subtracts one circle from the rectangle and adds the other circle to the
rectangle.
sf = 'R1-C1+C2';
ns = char('R1','C1','C2');
ns = ns';
gd = decsg(gd,sf,ns);
pdegplot(gd,'FaceLabels','on')
5-1116
pdesde
[p,e,t] = initmesh(gd);
pdemesh(p,e,t)
5-1117
5 Functions
Find the indices of the mesh elements' edges located on the outer boundaries and belonging to face
1. Display the result as a column vector.
i1 = pdesde(e,1);
i1.'
ans = 42×1
1
2
3
4
5
6
7
8
9
10
⋮
The resulting vector contains indices of all mesh edges in this geometry, except the eight internal
edges surrounding face 2.
length(e) - length(i1)
ans = 8
5-1118
pdesde
Use the pdesde function to find the mesh edges surrounding face 2. The result is an empty vector
because none of these mesh edges belong to the outer boundary of the geometry.
i2 = pdesde(e,2)
i2 =
Input Arguments
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
details on the mesh data representation, see initmesh.
Data Types: double
Output Arguments
i — Indices of mesh edges on outer boundaries
vector of integers
Indices of the mesh edges on the outer boundaries, returned as a vector of integers.
Version History
Introduced before R2006a
pdesde is not recommended. Use faceEdges instead. There are no plans to remove pdesde.
See Also
pdesdp | pdesdt
Topics
“Mesh Data as [p,e,t] Triples” on page 2-181
5-1119
5 Functions
pdesdt
(Not recommended) Indices of subset of mesh elements belonging to specified faces of 2-D geometry
Syntax
i = pdesdt(t,FaceID)
i = pdesdt(t)
Description
i = pdesdt(t,FaceID) returns the indices of the mesh elements of the [p,e,t] mesh that belong
to the set of faces listed in FaceID.
Examples
Find the indices of the mesh elements belonging to the specified faces.
Define two circles and a rectangle and place these in one matrix.
R1 = [3,4,-1,1,1,-1,0.5,0.5,-0.75,-0.75]';
C1 = [1,-0.5,-0.25,0.25]';
C2 = [1,0.5,-0.25,0.25]';
C1 = [C1;zeros(length(R1) - length(C1),1)];
C2 = [C2;zeros(length(R1) - length(C2),1)];
gd = [R1,C1,C2];
sf = 'R1+C1+C2';
ns = char('R1','C1','C2');
ns = ns';
gd = decsg(gd,sf,ns);
pdegplot(gd,'FaceLabels','on')
5-1120
pdesdt
Create a mesh.
[p,e,t] = initmesh(gd);
pdemesh(p,e,t,'ElementLabels','on')
5-1121
5 Functions
Find the indices of the mesh elements that belong to face 2. Display the result as a column vector.
i = pdesdt(t,2);
i.'
ans = 16×1
5
8
19
20
21
22
75
76
139
140
⋮
Input Arguments
t — Mesh elements
matrix
5-1122
pdesdt
Mesh elements, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
Output Arguments
i — Mesh elements belonging to specified faces
vector of integers
Version History
Introduced before R2006a
pdesdt is not recommended. Use findElements instead. There are no plans to remove pdesdt.
See Also
pdesdp | pdesde
Topics
“Mesh Data as [p,e,t] Triples” on page 2-181
5-1123
5 Functions
pdesmech
(Not recommended) Calculate structural mechanics tensor
Note pdesmech is not recommended. Use the PDE Modeler app or the “Structural Mechanics”
workflow instead. For more information, see “Compatibility Considerations”.
Syntax
structMechT = pdesmech(p,t,c,u,Name,Value)
Description
structMechT = pdesmech(p,t,c,u,Name,Value) returns a tensor evaluated at the center of
each triangle in t. The tensors are stresses and strains for structural mechanics applications with
plane stress or plane strain conditions. If you do not specify Name,Value, the function returns the
von Mises effective stress for plane stress conditions.
Export the solution, the mesh, and the PDE coefficients to the MATLAB workspace. Then use
pdesmech for postprocessing of a solution computed in one of the structural mechanics application
modes of the PDE Modeler app.
When calculating shear stresses and strains and the von Mises effective stress in plane strain mode,
specify Poisson's ratio.
Examples
Solve a structural mechanics problem in the PDE Modeler app, and export the solution to the
MATLAB workspace. Then use pdesmech to compute the x-component of the stress and the von
Mises effective stress.
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 these
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.
5-1124
pdesmech
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.
pdepoly([0 2/3 1 1 1/3 1/3 0],[1 1 2/3 0 0 1/3 1/3])
pdecirc(2/3,2/3,1/3)
Set the x-axis limit to [-0.5 1.5] and y-axis limit to [0 1.2]. To do this, select Options > Axes
Limits and set the corresponding ranges.
Remove all subdomain borders. To do this, switch to the boundary mode by selecting Boundary >
Boundary Mode. Then select Boundary > Remove All Subdomain Borders.
Display the edge labels by selecting Boundary > Show Edge Labels.
Specify the boundary conditions. To do this, select Boundary > Specify Boundary Conditions.
5-1125
5 Functions
• For convenience, first specify the Neumann boundary condition: g1 = g2 = 0, q11 = q12 =
q21 = q22 = 0 (no normal stress) for all boundaries. Use Edit > Select All to select all
boundaries.
• For the two clamped boundaries at the inset in the lower left (edges 4 and 5), specify the Dirichlet
boundary condition with zero displacements: h11 = 1, h12 = 0, h21 = 0, h22 = 1, r1 = 0,
r2 = 0. Use Shift+click to select several boundaries.
• For the rounded cut (edge 7), specify the Neumann boundary condition: g1 = 0.5*nx, g2 =
0.5*ny, q11 = q12 = q21 = q22 = 0.
Specify the coefficients by selecting PDE > PDE Specification or clicking the PDE button on the
toolbar. Specify E = 196E3 and nu = 0.31. The material is homogeneous, so the same values E and
nu apply to the entire 2-D domain. Because there are no volume forces, specify Kx = Ky = 0. The
elliptic type of PDE for plane stress does not use density, so you can specify any value. For example,
specify rho = 0.
Initialize the mesh by selecting Mesh > Initialize Mesh. Refine the mesh by selecting Mesh >
Refine Mesh.
Further refine the mesh in areas where the gradient of the solution (the stress) is large. To do this,
select Solve > Parameters. In the resulting dialog box, select Adaptive mode. Use the default
adaptation options: the Worst triangles triangle selection method with the Worst triangle fraction
set to 0.5.
Solve the PDE by selecting Solve > Solve PDE or by clicking the = button on the toolbar.
Export the PDE coefficients, mesh, and solution to the MATLAB workspace.
• To export the PDE coefficients, select PDE > Export PDE Coefficients.
• To export the mesh, select Mesh > Export Mesh.
• To export the solution, select Solve > Export Solution.
sx = pdesmech(p,t,c,u,'tensor','sxx');
pdeplot(p,e,t,'XYData',sx,'Mesh','on')
5-1126
pdesmech
vM = pdesmech(p,t,c,u,'tensor','vonmises');
pdeplot(p,e,t,'XYData',vM,'Mesh','on')
5-1127
5 Functions
Input Arguments
p — Mesh nodes
matrix
Mesh nodes, specified as a 2-by-Np matrix of nodes (points), where Np is the number of nodes in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
t — Mesh elements
matrix
Mesh elements, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For details on the mesh data representation, see initmesh.
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.
Data Types: double | char | string | function_handle
u — PDE solution
vector
5-1128
pdesmech
PDE solution, specified as a column vector of 2Np elements, where Np is the number of nodes in the
mesh. The first Np elements of u represent the x-displacement, and the next Np elements represent y-
displacement.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: vM = pdesmech(p,t,c,u,'tensor','ux');
5-1129
5 Functions
nu — Poisson's ratio
0.3 (default) | number | vector | character vector | string scalar
Poisson's ratio, specified as a number, vector, character vector, or string scalar. The pdesmech
function uses the value of Poisson's ratio to calculate shear stresses and strains, and the von Mises
effective stress in the plane strain mode. Specify a scalar if the value is constant over the entire
geometry. Otherwise, specify a row vector whose length is equal to the number of elements, a
character vector, or a string scalar in coefficient form.
Output Arguments
structMechT — Resulting tensor
vector
Resulting tensor, returned as a vector. Depending on the value of the tensor input argument, the
result is one of these values:
Version History
Introduced before R2006a
pdesmech is not recommended. Use the PDE Modeler app instead. There are no plans to remove
pdesmech.
Starting in R2016a, use the PDE Modeler app to calculate stresses and strains for structural
mechanics applications with plane stress or plane strain conditions. For example, see “von Mises
Effective Stress and Displacements: PDE Modeler App” on page 3-3. Alternatively, starting in R2017b,
you can use the recommended structural mechanics workflow. For details, see “Structural
Mechanics”.
See Also
PDE Modeler
Topics
“Structural Mechanics”
5-1130
PDESolverOptions Properties
PDESolverOptions Properties
Algorithm options for solvers
Description
A PDESolverOptions object contains options used by the solvers when solving a structural,
thermal, or general PDE problem specified as a StructuralModel, ThermalModel, or PDEModel
object, respectively. StructuralModel, ThermalModel, and PDEModel objects contain a
PDESolverOptions object in their SolverOptions property.
Solvers for structural modal analysis problems and reduced-order modeling use the Lanczos
algorithm.
Properties
Statistics and Convergence Report
Flag to display the internal solver statistics and the convergence report during the solution process
for transient and eigenvalue problems, specified as "on" or "off". For linear stationary problems,
there is no statistics and convergence report to display.
Example: model.SolverOptions.ReportStatistics = "on"
Data Types: char
ODE Solver
Absolute tolerance for the internal ODE solver, specified as a positive 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 the internal ODE solver, specified as a positive 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-1131
5 Functions
Nonlinear Solver
Acceptable residual tolerance for the internal nonlinear solver, specified as a positive 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 for the internal nonlinear solver, specified as a positive
integer.
Example: model.SolverOptions.MaxIterations = 30
Data Types: double
Minimum damping of the search direction for the internal nonlinear solver, specified as a positive
number. For details, see “Nonlinear Solver Algorithm” on page 5-1133.
Example: model.SolverOptions.MinStep = 1.5259e-7
Data Types: double
ResidualNorm — Type of norm for computing residual for internal nonlinear solver
Inf | -Inf | positive number | "energy"
Type of norm for computing the residual for the internal nonlinear solver, specified as Inf, -Inf, a
positive number, or "energy". The default value for ElectromagneticModel is 2, and for all other
models it is Inf.
ρ ∞
= maxi ρ i
ρ −∞
= mini ρ i
ρ = ρT Kρ
Here, K is the combined stiffness matrix defined in “Nonlinear Solver Algorithm” on page 5-1133.
5-1132
PDESolverOptions Properties
Lanczos Solver
Maximum number of Lanczos shifts, specified as a positive integer. Increase this value when
computing a large number of eigenpairs.
Example: model.SolverOptions.MaxShift = 500
Data Types: double
Block size for block Lanczos recurrence, specified as a positive integer. The default number ranges
from 7 to 25, depending on the size of the stiffness matrix K.
Example: model.SolverOptions.BlockSize = 20
Data Types: double
Algorithms
Nonlinear Solver Algorithm
r u = − ∇⋅ c u ∇ u +a u u−f u =0
To obtain a discretized residual equation, apply the finite element method (FEM) to a partial
differential equation as described in “Finite Element Method Basics” on page 1-11:
ρ U =K U U−F U =0
The nonlinear solver uses a Gauss-Newton iteration scheme applied to the finite element matrices.
Use a Taylor series expansion to obtain the linearized system for the residual:
∂ρ Un
ρ Un + 1 ≅ ρ Un + Un + 1 − Un + … = 0
∂U
∂ρ Un
Un + 1 − Un = − ρ Un
∂U
−1
∂ρ Un
pn = − ρ Un
∂U
5-1133
5 Functions
The Gauss-Newton iteration minimizes the residual, that is, the solution of minU ρ U , using the
equation
Un + 1 = Un + αpn
Here, ɑ ≤ 1 is a positive number, that must be set as large as possible so that the step has a
reasonable descent. For a sufficiently small ɑ,
ρ Un + αpn < ρ Un
For the Gauss-Newton algorithm to converge, U0 must be close enough to the solution. The first
guess is often outside the region of convergence. The Armijo-Goldstein line search (a damping
strategy for choosing ɑ) helps to improve convergence from bad initial guesses. This method chooses
the largest damping coefficient ɑ out of the sequence 1, 1/2, 1/4, . . . such that the following
inequality holds:
α
ρ Un − ρ Un + αpn ≥ ρ Un
2
Using the Armijo-Goldstein line search guarantees a reduction of the residual norm by at least
1 − α/2. Each step of the line-search algorithm must evaluate the residual ρ Un + αpn .
With this strategy, when Un approaches the solution, α→1, thus, the convergence rate increases.
Version History
Introduced in R2016a
See Also
PDEModel | solvepde | solvepdeeig
5-1134
pdesurf
pdesurf
(To be removed) Surface plot of PDE node or triangle data
Note pdesurf will be removed in a future release. Use pdeplot instead. For more information, see
“Compatibility Considerations”.
Syntax
pdesurf(p,t,u)
h = pdesurf(p,t,u)
Description
pdesurf(p,t,u) plots a 3-D surface using PDE node or triangle data as a height for a 2-D problem.
The p and t arguments specify the geometry of the PDE problem.
If u is a column vector, pdesurf treats it as node data and uses continuous style and interpolated
shading. If u is a row vector, pdesurf treats it as triangle data and uses discontinuous style and flat
shading.
Examples
Plot the solution of the equation −Δu = 1 on the L-shaped membrane using the pdesurf function.
[p,e,t] = initmesh('lshapeg');
u = assempde('lshapeb',p,e,t,1,0,1);
Plot the solution at the mesh nodes. When plotting the solution at the nodes, the function uses
continuous style and interpolated shading.
pdesurf(p,t,u)
5-1135
5 Functions
Interpolate the solution from the mesh nodes to the triangle midpoints.
ut = pdeintrp(p,t,u);
Plot the interpolated solution. When plotting the solution as a triangle data, the function uses
discontinuous style and flat shading.
pdesurf(p,t,ut)
5-1136
pdesurf
Input Arguments
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 details on the mesh data representation, see initmesh.
Data Types: double
t — Mesh triangles
matrix
Mesh triangles, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
u — PDE solution
vector
The pdesurf function treats a column vector as node data and uses continuous style and
interpolated shading. The function treats a row vector as triangle data and uses discontinuous style
and flat shading.
5-1137
5 Functions
Output Arguments
h — Handles to graphics objects
vector
Tips
• For more control over a surface plot, use the pdeplot function.
Version History
Introduced before R2006a
R2023a: Warns
Warns starting in R2023a
The pdesurf function issues a warning that it will be removed in a future release.
To update your code for plotting a solution u at nodes, change instances of the function call
pdesurf(p,t,u) to the function call:
pdeplot(p,[],t,'XYData',u,'ZData',u,'ColorBar','off')
To update your code for plotting a solution ut at midpoints of mesh triangles, change instances of the
function call pdecont(p,t,ut) to the function call:
pdeplot(p,[],t,'XYData',ut,'XStyle','flat', ...
'ZData',ut,'ZStyle','discontinuos', ...
'ColorBar','off')
Note that the legacy workflow that uses the [p,e,t] mesh is not recommended. New features might
not be compatible with this legacy workflow. For description of the mesh data in the recommended
workflow, see “Mesh Data” on page 2-184.
R2022a: To be removed
Not recommended starting in R2022a
The pdesurf function runs without a warning, but will be removed in a future release. Use pdeplot
instead.
See Also
pdemesh | pdeplot
5-1138
PDE Modeler
PDE Modeler
Create complex 2-D geometries by drawing, overlapping, and rotating basic shapes
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-1139
5 Functions
Examples
• “Solve 2-D PDEs Using the PDE Modeler App” on page 1-5
• “Open the PDE Modeler App” on page 4-2
• “2-D Geometry Creation in PDE Modeler App” on page 4-3
• “Specify Boundary Conditions in the PDE Modeler App” on page 4-12
• “Specify Coefficients in PDE Modeler App” on page 4-14
5-1140
PDE Modeler
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].
Version History
Introduced before R2006a
5-1141
5 Functions
R2017b: Calling pdetool or opening the app via the Apps tab does not overwrite existing
information in the app
Behavior change in future release
In previous releases, starting the PDE Modeler app and then reopening the app by calling pdetool
or by using the Apps tab overwrites any existing information in the app. Now, reopening the PDE
Modeler app brings focus to the app window. To overwrite the existing information in the PDE
Modeler app, select File > New.
The mesher provides an enhancement option for increased meshing speed and robustness. Choose
the enhanced algorithm by selecting Mesh > Parameters and setting Mesher version to R2013a.
You can now save the current figure in a variety of image formats by using the File > Export Image
menu.
See Also
Functions
pdecirc | pdeellip | pdepoly | pderect
Topics
“Solve 2-D PDEs Using the PDE Modeler App” on page 1-5
“Open the PDE Modeler App” on page 4-2
“2-D Geometry Creation in PDE Modeler App” on page 4-3
“Specify Boundary Conditions in the PDE Modeler App” on page 4-12
“Specify Coefficients in PDE Modeler App” on page 4-14
“Specify Mesh Parameters in the PDE Modeler App” on page 4-24
“Adjust Solve Parameters in the PDE Modeler App” on page 4-26
“Plot the Solution in the PDE Modeler App” on page 4-31
“von Mises Effective Stress and Displacements: PDE Modeler App” on page 3-3
“Heat Transfer in Block with Cavity: PDE Modeler App” on page 3-299
“Heat Distribution in Circular Cylindrical Rod: PDE Modeler App” on page 3-343
“Heat Transfer Between Two Squares Made of Different Materials: PDE Modeler App” on page 3-234
“Poisson's Equation on Unit Disk: PDE Modeler App” on page 3-257
“Poisson’s Equation with Complex 2-D Geometry: PDE Modeler App” on page 1-7
“Electrostatic Potential in Air-Filled Frame: PDE Modeler App” on page 3-171
“Magnetic Field in Two-Pole Electric Motor: PDE Modeler App” on page 3-205
“Wave Equation on Square Domain: PDE Modeler App” on page 3-350
“Scattering Problem: PDE Modeler App” on page 3-276
“Skin Effect in Copper Wire with Circular Cross Section: PDE Modeler App” on page 3-223
“Poisson's Equation on Unit Disk: PDE Modeler App” on page 3-257
“Minimal Surface Problem: PDE Modeler App” on page 3-292
“Current Density Between Two Metallic Conductors: PDE Modeler App” on page 3-231
“L-Shaped Membrane with Rounded Corner: PDE Modeler App” on page 3-361
“Eigenvalues and Eigenmodes of Square: PDE Modeler App” on page 3-369
5-1142
PDE Modeler
“Eigenvalues and Eigenmodes of L-Shaped Membrane: PDE Modeler App” on page 3-358
5-1143
5 Functions
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 areas of individual mesh triangles as a vector ar and
half of the negative cotangent of each angle as vectors a1,a2,a3.
Examples
Find the area of each element of a 2-D mesh. In addition, return half of the negative cotangent of
each angle and the gradient components of the triangle base functions for each element.
[p,e,t] = initmesh(@squareg);
pdemesh(p,e,t)
5-1144
pdetrg
Compute the area of each individual element of the mesh and half of the negative cotangent of each
angle. Display the first 5 elements for each result.
[ar,a1,a2,a3] = pdetrg(p,t);
ar(1:5)
ans = 1×5
a1(1:5)
ans = 1×5
a2(1:5)
ans = 1×5
a3(1:5)
ans = 1×5
5-1145
5 Functions
Find the area of the smallest and the largest element of the mesh.
min(ar)
ans = 0.0061
max(ar)
ans = 0.0216
Use the syntax with seven output arguments to compute the gradient components of the triangle base
functions for each element.
[ar,g1x,g1y,g2x,g2y,g3x,g3y] = pdetrg(p,t);
Input Arguments
p — Mesh nodes
matrix
Mesh nodes, specified as a 2-by-Np matrix of nodes (points), where Np is the number of nodes in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
t — Mesh elements
matrix
Mesh elements, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
Output Arguments
ar — Areas of individual elements
row vector of positive numbers
Half of the negative cotangent of each angle, returned as three row vectors of numbers.
Gradient components of the triangle base functions, returned as six row vectors of numbers.
5-1146
pdetrg
Version History
Introduced before R2006a
pdetrg is not recommended. Use area instead. There are no plans to remove pdetrg.
See Also
area | pdetriq
Topics
“Mesh Data as [p,e,t] Triples” on page 2-181
5-1147
5 Functions
pdetriq
(Not recommended) Triangle quality measure
Syntax
q = pdetriq(p,t)
Description
q = pdetriq(p,t) returns a row vector of numbers from 0 through 1 representing the triangle
quality of all the elements of the [p,e,t] mesh.
4a 3
q= 2 2 2
h1 + h2 + h3
where a is the area and h1, h2, and h3 are the lengths of the edges of the triangle.
The value 0 corresponds to a degenerate triangle with zero area. The value 1 corresponds to a
triangle with h1 = h2 = h3.
Examples
Generate and plot a mesh for the geometry consisting of a circle with a diamond hole.
[p,e,t] = initmesh(@scatterg);
pdemesh(p,e,t)
axis equal
5-1148
pdetriq
Evaluate the triangle quality for each mesh triangle. Plot the resulting quality values.
q = pdetriq(p,t);
figure
pdeplot(p,e,t,'XYData',q);
axis equal
5-1149
5 Functions
Input Arguments
p — Mesh nodes
matrix
Mesh nodes, specified as a 2-by-Np matrix of nodes (points), where Np is the number of nodes in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
t — Mesh elements
matrix
Mesh elements, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
Output Arguments
q — Triangle quality
row vector
5-1150
pdetriq
Version History
Introduced before R2006a
pdetriq is not recommended. Use meshQuality instead. There are no plans to remove pdetriq.
References
[1] Bank, Randolph E. PLTMG: A Software Package for Solving Elliptic Partial Differential Equations,
User's Guide 6.0. Philadelphia, PA: Society for Industrial and Applied Mathematics, 1990.
See Also
pdetrg | meshQuality
Topics
“Mesh Data as [p,e,t] Triples” on page 2-181
5-1151
5 Functions
pdeviz
Create and plot PDE visualization object
Syntax
pdeviz(MeshData,NodalData)
pdeviz(MeshData)
pdeviz( ___ ,Name,Value)
pdeviz(figure, ___ )
V = pdeviz( ___ )
Description
pdeviz(MeshData,NodalData) creates a PDEVisualization object and plots the data at the
mesh nodes as a surface plot. For details, see PDEVisualization Properties.
pdeviz( ___ ,Name,Value) customizes the plot appearance using one or more Name,Value
arguments. Use name-value arguments with any combination of arguments from the previous
syntaxes.
pdeviz(figure, ___ ) specifies the graphics container for the PDEVisualization object. For
example, you can plot the object in Figure 3 by specifying pdeviz(figure(3), ___).
V = pdeviz( ___ ) returns a handle to the PDEVisualization object, using any of the previous
syntaxes.
Examples
Use the pdeviz function to create a PDE visualization object and plot it. Change the properties of
this object to interact with the resulting plot.
structuralmodel = createpde("structural","static-solid");
importGeometry(structuralmodel,"SquareBeam.stl");
pdegplot(structuralmodel,"FaceLabels","on","FaceAlpha",0.5)
5-1152
pdeviz
structuralProperties(structuralmodel,"PoissonsRatio",0.3, ...
"YoungsModulus",210E3);
structuralBC(structuralmodel,"Face",6,"Constraint","fixed");
structuralBoundaryLoad(structuralmodel,"Face",5, ...
"SurfaceTraction",[0;0;-2]);
msh = generateMesh(structuralmodel);
structuralresults = solve(structuralmodel);
Call pdeviz with only the mesh data. This call creates a PDEVisualization object and plots the
mesh.
figure
v = pdeviz(msh)
5-1153
5 Functions
v =
PDEVisualization with properties:
Update the plot by adding the von Mises stress as the NodalData property of the
PDEVisualization object v. The plot now shows the von Mises stress and the mesh.
figure
v.NodalData = structuralresults.VonMisesStress;
Update the plot by adding the displacement as the DeformationData property of the
PDEVisualization object v. The plot shows the deformed shape with the von Mises stress.
figure
v.DeformationData = structuralresults.Displacement;
5-1154
pdeviz
figure
v.MeshVisible = "off";
5-1155
5 Functions
figure
v.AxesVisible = "off";
5-1156
pdeviz
Input Arguments
MeshData — Finite element mesh
FEMesh object
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example:
pdeviz(model.Mesh,results.NodalSolution,"MeshVisible","on","DeformationData",
results.Displacement)
5-1157
5 Functions
Surface transparency, specified as a real number from 0 through 1. The default value 1 indicates no
transparency. The value 0 indicates complete transparency.
Data Types: double
Toggle to show mesh, specified as "on" or "off", or as numeric or logical 1 (true) or 0 (false). A
value of "on" is equivalent to true, and "off" is equivalent to false. Thus, you can use the value
of this argument as a logical value.
When plotting only the mesh, the default is "on". Otherwise, the default is "off".
Data Types: char | string
• An FEStruct object with the properties ux, uy, and, for a 3-D geometry, uz
• A structure array with the fields ux, uy, and, for a 3-D geometry, uz
• A matrix with either two columns for a 2-D geometry or three columns for a 3-D geometry
Level of mesh deformation, specified as a nonnegative number. Use this name-value argument
together with DeformationData.
pdeviz computes the default value of DeformationScaleFactor based on the mesh and the value
of DeformationData.
Data Types: double
Toggle to hide or show axes, specified as "on" or "off", or as numeric or logical 1 (true) or 0
(false). A value of "on" is equivalent to true, and "off" is equivalent to false. Thus, you can use
the value of this argument as a logical value.
Background color, specified as an RGB triplet, a hexadecimal color code, a color name, or a short
name.
5-1158
pdeviz
of this property as a logical value. The value is stored as an on/off logical value of type
matlab.lang.OnOffSwitchState.
Color limits, specified as a two-element vector of the form [min max]. The color limits indicate the
color data values that map to the first and last colors in the colormap.
Chart title, specified as a character vector, cell array of character vectors, string array, or categorical
array.
Example: "My Title Text"
To create a multi-line title, specify a cell array of character vectors or a string array. Each element in
the array corresponds to a line of text.
Example: {"My","Title"};
If you specify the title as a categorical array, MATLAB uses the values in the array, not the categories.
If you create the chart using tabular data, the default chart has an autogenerated title. If you do not
want a title, specify "".
Azimuth and elevation of view, specified as a two-element vector of the form [azimuth elevation]
defined in degree units. Alternatively, use the view function to set the view.
Output Arguments
V — Visualization container
handle
Visualization container, returned as a handle to the PDEVisualization object. For details, see
PDEVisualization Properties.
Version History
Introduced in R2021a
See Also
pdeplot | pdeplot3D | pdemesh | PDEVisualization Properties
5-1159
5 Functions
PDEVisualization Properties
PDE visualization of mesh and nodal results
Description
PDEVisualization properties control the appearance and behavior of a PDEVisualization
object. By changing property values, you can modify certain aspects of the visualization.
Properties
Displayed Data
• An FEStruct object with the properties ux, uy, and, for a 3-D geometry, uz
• A structure array with the fields ux, uy, and, for a 3-D geometry, uz
• A matrix with either two columns for a 2-D geometry or three columns for a 3-D geometry
The toolbox computes the default value of DeformationScaleFactor based on the mesh and the
value of DeformationData.
Example: v.DeformationScaleFactor = 1000;
Data Types: double
5-1160
PDEVisualization Properties
Axis limits, specified as a two-element vector of the form [min max], where max is greater than min.
You can specify the limits as numeric, categorical, datetime, or duration values. The type of values
that you specify must match the type of values along the axis.
You can specify both limits or you can specify one limit and let the axes automatically calculate the
other. For an automatically calculated minimum or maximum limit, use -Inf or Inf, respectively.
Example: ax.XLim = [0 10]
Example: ax.YLim = [-Inf 10]
Example: ax.ZLim = [0 Inf]
Color limits, specified as a two-element vector of the form [min max]. The color limits indicate the
color data values that map to the first and last colors in the colormap.
Example: v.ColorLimits = [0 10];
Mesh visibility, specified as 'on' or 'off', or as numeric or logical 1 (true) or 0 (false). A value of
'on' is equivalent to true, and 'off' is equivalent to false. Thus, you can use the value of this
property as a logical value. The value is stored as an on/off logical value of type
matlab.lang.OnOffSwitchState.
Example: v.MeshVisible = 'on';
Data Types: char | string
Surface transparency, specified as a real number from 0 through 1. The default value 1 indicates no
transparency. The value 0 indicates complete transparency.
When you use the Transparency argument for solution plots, the plot colors might not match the
color bar values. Always use a fully opaque plot to estimate the solution values.
Data Types: double
5-1161
5 Functions
Toggle to hide or show axes, specified as 'on' or 'off', or as numeric or logical 1 (true) or 0
(false). A value of 'on' is equivalent to true, and 'off' is equivalent to false. Thus, you can use
the value of this argument as a logical value.
Background color, specified as an RGB triplet, a hexadecimal color code, a color name, or a short
name.
Labels
Axis labels, specified as character vectors, cell arrays of character vectors, string arrays, or
categorical arrays.
Example: v.XLabel = 'time';
Chart title, specified as a character vector, cell array of character vectors, string array, or categorical
array.
Example: v.Title = 'My Title Text';
To create a multi-line title, specify a cell array of character vectors or a string array. Each element in
the array corresponds to a line of text.
Example: v.Title = {'My','Title'};
If you specify the title as a categorical array, MATLAB uses the values in the array, not the categories.
If you create the chart using tabular data, the default chart has an autogenerated title. If you do not
want a title, specify ''.
Interactivity
State of visibility, specified as 'on' or 'off', or as numeric or logical 1 (true) or 0 (false). A value
of 'on' is equivalent to true, and 'off' is equivalent to false. Thus, you can use the value of this
property as a logical value. The value is stored as an on/off logical value of type
matlab.lang.OnOffSwitchState.
Parent/Child
5-1162
PDEVisualization Properties
Parent container of the chart, specified as a Figure, Panel, Tab, or TiledChartLayout object.
Visibility of the object handle in the Children property of the parent, specified as one of these
values:
If the object is not listed in the Children property of the parent, then functions that obtain object
handles by searching the object hierarchy or querying handle properties cannot return it. Examples
of such functions include the get, findobj, gca, gcf, gco, newplot, cla, clf, and close
functions.
Hidden object handles are still valid. Set the root ShowHiddenHandles property to 'on' to list all
object handles regardless of their HandleVisibility property setting.
Position
Chart size and location, including the margins for decorations such as axis labels and tick marks.
Specify this property as a vector of form [left bottom width height]. The values are in the
units specified by the Units property.
• left — Distance from the left edge of the parent container to the outer-left edge of the chart that
includes the margins. Typically, the parent container is a figure, panel, or tab.
• bottom — Distance from the bottom edge of the parent container to the outer-bottom edge of the
chart that includes the margins.
• width — Width of chart, including the margins.
• height — Height of chart, including the margins.
Note Setting this property has no effect when the parent of the chart is a TiledChartLayout.
Chart size and location, excluding the margins for decorations such as axis labels and tick marks.
Specify this property as a vector of form [left bottom width height]. The values are in the
units specified by the Units property.
• left — Distance from the left edge of the parent container to the inner-left edge of the chart that
excludes the margins. Typically, the parent container is a figure, panel, or tab.
5-1163
5 Functions
• bottom — Distance from the bottom edge of the parent container to the inner-bottom edge of the
chart that excludes the margins.
• width — Width of chart, excluding the margins.
• height — Height of chart, excluding the margins.
Note Setting this property has no effect when the parent of the chart is a TiledChartLayout.
Chart size and location, excluding the margins for decorations such as axis labels and tick marks.
Specify this property as a vector of form [left bottom width height]. This property is
equivalent to the InnerPosition property.
Note Setting this property has no effect when the parent of the chart is a TiledChartLayout.
Position property to hold constant when adding, removing, or changing decorations, specified as one
of the following values:
• 'outerposition' — The OuterPosition property remains constant when you add, remove, or
change decorations such as a title or an axis label. If any positional adjustments are needed,
MATLAB adjusts the InnerPosition property.
• 'innerposition' — The InnerPosition property remains constant when you add, remove, or
change decorations such as a title or an axis label. If any positional adjustments are needed,
MATLAB adjusts the OuterPosition property.
Note Setting this property has no effect when the parent container is a TiledChartLayout.
Position units, specified as a value from the following table. To change the position of the chart in
specific units, set the Units property before specifying the Position property. If you specify the
Units and Position properties in a single command (using name-value pairs), be sure to specify
Units before Position.
Units Description
'normalized' (default) Normalized with respect to the parent container,
which is typically the figure, panel, or tab. The
lower left corner of the container maps to (0,0),
and the upper right corner maps to (1,1).
'inches' Inches.
'centimeters' Centimeters.
5-1164
PDEVisualization Properties
Units Description
'characters' Based on the default font of the graphics root
object:
For example, this code places chart object c into the third tile of a tiled chart layout.
c.Layout.Tile = 3;
To make the chart span multiple tiles, specify the TileSpan property as a two-element vector. For
example, this chart spans 2 rows and 3 columns of tiles.
c.Layout.TileSpan = [2 3];
Note Tiled chart layouts are not supported for the axes returned by the getAxes method. Instead,
you can place an instance of your chart into a tiled chart layout.
View
Azimuth and elevation of view, specified as a two-element vector of the form [azimuth elevation]
defined in degree units. Alternatively, use the view function to set the view.
5-1165
5 Functions
Version History
Introduced in R2021a
See Also
pdeviz
5-1166
poimesh
poimesh
(Not recommended) Generate 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 by dividing
the rectangle into nx pieces along the x-direction and ny pieces along the y-direction, thus resulting
in (nx + 1)*(ny + 1) nodes in the domain. The x-direction is the direction along the edge that
makes the smallest angle with the x-axis.
For best performance with poisolv, the larger of nx and ny must be a power of 2.
Examples
Solve the Poisson's equation −Δu = 3x2 on a square domain with Dirichlet boundary conditions using
the poisolv function.
Create a model object and include the square geometry created using the squareg function.
model = createpde;
g = @squareg;
geometryFromEdges(model,g);
pdegplot(model,"EdgeLabels","on")
axis([-1.1 1.1 -1.1 1.1])
5-1167
5 Functions
Apply the following Dirichlet boundary conditions. The solution is 0 . 2 cos πy/2 on the right
boundary (edge 2) and zero on all other boundaries.
The fast Poisson solver requires a regular rectangular grid. Use the poimesh function to generate a
mesh meeting this requirement. Plot the mesh.
[p,e,t] = poimesh(g,16);
figure;
pdemesh(p,e,t);
axis equal
5-1168
poimesh
c = 1;
a = 0;
f = '3*x.^2';
16 | 0.40916
32 | 0.096001
64 | 0.12434
128 | 0.15628
256 | 0.44511
512 | 0.98475
figure;
pdeplot(p,[],t,"XYData",u,"ZData",u)
5-1169
5 Functions
Input Arguments
g — Rectangular geometry
decomposed geometry matrix | geometry function | handle to geometry function
A geometry function must return the same result for the same input arguments in every function call.
Thus, it must not contain functions and expressions designed to return a variety of results, such as
random number generators.
5-1170
poimesh
n — Number of divisions
positive integer
Number of divisions along both the x- and y-direction, specified as a positive integer. In this case,
both the x- and y-edges are divided into the same number of pieces.
Data Types: double
Output Arguments
p — Mesh points
matrix
Mesh points, returned as a 2-by-Np matrix of points, where Np is the number of points in the mesh.
For details on the mesh data representation, see initmesh.
Data Types: double
e — Mesh edges
matrix
Mesh edges, returned as a 7-by-Ne matrix of edges, where Ne is the number of edges in the mesh. For
details on the mesh data representation, see initmesh.
Data Types: double
t — Mesh triangles
matrix
Mesh triangles, returned as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
Version History
Introduced before R2006a
poimesh is not recommended. To solve Poisson's equations, use solvepde. For details, see “Solve
Problems Using PDEModel Objects” on page 2-3. There are no plans to remove poimesh.
See Also
poisolv
Topics
“Mesh Data as [p,e,t] Triples” on page 2-181
5-1171
5 Functions
poisolv
(Not recommended) Fast solver for 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(model,p,e,t,f)
u = poisolv(b,p,e,t,f)
Description
u = poisolv(model,p,e,t,f) solves a Poisson's equation Δu = f on a regular rectangular
[p,e,t] mesh. The model must have only Dirichlet boundary conditions. A combination of sine
transforms and tridiagonal solutions is used for increased performance.
Examples
Solve the Poisson's equation −Δu = 3x2 on a square domain with Dirichlet boundary conditions using
the poisolv function.
Create a model object and include the square geometry created using the squareg function.
model = createpde;
g = @squareg;
geometryFromEdges(model,g);
pdegplot(model,"EdgeLabels","on")
axis([-1.1 1.1 -1.1 1.1])
5-1172
poisolv
Apply the following Dirichlet boundary conditions. The solution is 0 . 2 cos πy/2 on the right
boundary (edge 2) and zero on all other boundaries.
The fast Poisson solver requires a regular rectangular grid. Use the poimesh function to generate a
mesh meeting this requirement. Plot the mesh.
[p,e,t] = poimesh(g,16);
figure;
pdemesh(p,e,t);
axis equal
5-1173
5 Functions
c = 1;
a = 0;
f = '3*x.^2';
16 | 0.40916
32 | 0.096001
64 | 0.12434
128 | 0.15628
256 | 0.44511
512 | 0.98475
figure;
pdeplot(p,[],t,"XYData",u,"ZData",u)
5-1174
poisolv
Input Arguments
model — PDE model
PDEModel object
Dirichlet boundary conditions for all boundary points, 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.
Example: b = 'circleb1', b = "circleb1", or b = @circleb1
Data Types: double | char | string | function_handle
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 details on the mesh data representation, see initmesh.
5-1175
5 Functions
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
details on the mesh data representation, see initmesh.
Data Types: double
t — Mesh triangles
matrix
Mesh triangles, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For details on the mesh data representation, see initmesh.
Data Types: double
Right side of a Poisson's equation, specified as a scalar, matrix, character vector, character array,
string scalar, string vector, or coefficient function.
Data Types: double | char | string | function_handle
Output Arguments
u — PDE solution
vector
Version History
Introduced before R2006a
poisolv is not recommended. To solve Poisson's equations, use solvepde. For details, see “Solve
Problems Using PDEModel Objects” on page 2-3. There are no plans to remove poisolv.
References
[1] Strang, G. Introduction to Applied Mathematics. Wellesley-Cambridge Press, Cambridge, MA,
1986, pp. 453–458.
See Also
poimesh
Topics
“Mesh Data as [p,e,t] Triples” on page 2-181
5-1176
reconstructSolution
reconstructSolution
Package: pde
Syntax
structuralresults = reconstructSolution(Rcb,u,ut,utt,tlist)
thermalresults = reconstructSolution(Rtherm,u_therm,tlist)
Description
structuralresults = reconstructSolution(Rcb,u,ut,utt,tlist) recovers the full
transient structural solution from the reduced-order model Rcb, displacement u, velocity ut, and
acceleration utt. Typically, the displacement, velocity, and acceleration are the values returned by
Simscape.
Examples
Knowing the solution in terms of the interface degrees of freedom (DoFs) and modal DoFs,
reconstruct the solution for the full structural transient model.
modelT = createpde("structural","transient-solid");
gm = multicuboid(0.05,0.003,0.003);
modelT.Geometry = gm;
figure
pdegplot(modelT,"FaceLabels","on","FaceAlpha",0.5)
view([71 4])
5-1177
5 Functions
figure
pdegplot(modelT,"EdgeLabels","on","FaceAlpha",0.5)
view([71 4])
5-1178
reconstructSolution
Specify Young's modulus, Poisson's ratio, and the mass density of the material.
structuralProperties(modelT,"YoungsModulus",210E9, ...
"PoissonsRatio",0.3, ...
"MassDensity",7800);
Generate a mesh.
generateMesh(modelT);
Define superelement interfaces using the fixed and loaded boundaries. In this case, the reduced-order
model retains the DoFs on the fixed face and the loaded vertex while condensing all other DoFs in
5-1179
5 Functions
favor of modal DoFs. For better performance, use the set of edges bounding face 5 instead of using
the entire face.
structuralSEInterface(modelT,"Edge",[2 8 11 12]);
structuralSEInterface(modelT,"Vertex",loadedVertex);
rom = reduce(modelT,"FrequencyRange",[-0.1,5e5]);
Next, use the reduced-order model to simulate the transient dynamics. Use the ode15s function
directly to integrate the reduced system ODE. Working with the reduced model requires indexing into
the reduced system matrices rom.K and rom.M. First, construct mappings of indices of K and M to
loaded and fixed DoFs by using the data available in rom.
DoFs correspond to translational displacements. If the number of mesh points in a model is Nn, then
the toolbox assigns the IDs to the DoFs as follows: the first 1 to Nn are x-displacements, Nn+1 to 2*Nn
are y-displacements, and 2Nn+1 to 3*Nn are z-displacements. The reduced model object rom contains
these IDs for the retained DoFs in rom.RetainedDoF.
Create a function that returns DoF IDs given node IDs and the number of nodes.
Knowing the DoF IDs for the given node IDs, use the intersect function to find the required
indices.
numNodes = size(rom.Mesh.Nodes,2);
loadedNode = findNodes(rom.Mesh,"region","Vertex",loadedVertex);
loadDoFs = getDoF(loadedNode,numNodes);
[~,loadNodeROMIds,~] = intersect(rom.RetainedDoF,loadDoFs);
In the reduced matrices rom.K and rom.M, generalized modal DoFs appear after the retained DoFs.
Because fixed-end DoFs are not a part of the ODE system, the indices for the ODE DoFs in reduced
matrices are as follows.
odeDoFs = [loadNodeROMIds;fixedIntModeIds];
The relevant components of rom.K and rom.M for time integration are:
Kconstrained = rom.K(odeDoFs,odeDoFs);
Mconstrained = rom.M(odeDoFs,odeDoFs);
numODE = numel(odeDoFs);
Now you have a second-order system of ODEs. To use ode15s, convert this into a system of first-
order ODEs by applying linearization. Such a first-order system is twice the size of the second-order
system.
5-1180
reconstructSolution
The specified concentrated force load in the full system is along the z-direction, which is the third
DoF in the ODE system. Accounting for the linearization to obtain the first-order system gives the
loaded ODE DoF.
loadODEDoF = numODE + 3;
Specify the mass matrix and the Jacobian for the ODE solver.
odeoptions = odeset;
odeoptions = odeset(odeoptions,"Jacobian",-Kode);
odeoptions = odeset(odeoptions,"Mass",Mode);
u0 = zeros(2*numODE,1);
Solve the reduced system by using ode15s and the helper function CMSODEf, which is defined at the
end of this example.
tlist = 0:0.00005:3E-3;
sol = ode15s(@(t,y) CMSODEf(t,y,Kode,Fode,loadODEDoF), ...
tlist,u0,odeoptions);
Compute the values of the ODE variable and the time derivatives.
[displ,vel] = deval(sol,tlist);
Knowing the solution in terms of the interface DoFs and modal DoFs, you can reconstruct the solution
for the full model. The reconstructSolution function requires the displacement, velocity, and
acceleration at all DoFs in rom. Construct the complete solution vector, including the zero values at
the fixed DoFs.
u = zeros(size(rom.K,1),numel(tlist));
ut = zeros(size(rom.K,1),numel(tlist));
utt = zeros(size(rom.K,1),numel(tlist));
u(odeDoFs,:) = displ(1:numODE,:);
ut(odeDoFs,:) = vel(1:numODE,:);
utt(odeDoFs,:) = vel(numODE+1:2*numODE,:);
RTrom = reconstructSolution(rom,u,ut,utt,tlist);
Compute the displacement in the interior at the center of the beam using the reconstructed solution.
coordCenter = [0;0;0];
iDispRTrom = interpolateDisplacement(RTrom, coordCenter);
figure
plot(tlist,iDispRTrom.uz)
title("Z-Displacement at Geometric Center")
5-1181
5 Functions
function f = CMSODEf(t,u,Kode,Fode,loadedVertex)
Fode(loadedVertex) = 10*sin(6000*t);
f = -Kode*u +Fode;
end
Reconstruct the solution for a full thermal transient model from the reduced-order model.
thermalmodel = createpde("thermal","transient");
geometryFromEdges(thermalmodel,@squareg);
pdegplot(thermalmodel,"EdgeLabels","on")
xlim([-1.1 1.1])
ylim([-1.1 1.1])
5-1182
reconstructSolution
Specify the thermal conductivity, mass density, and specific heat of the material.
thermalProperties(thermalmodel,"ThermalConductivity",400, ...
"MassDensity",1300, ...
"SpecificHeat",600);
thermalBC(thermalmodel,"Edge",2,"Temperature",100);
thermalIC(thermalmodel,50);
Generate a mesh.
generateMesh(thermalmodel);
Solve the model for three different values of heat source and collect snapshots.
tlist = 0:10:600;
snapShotIDs = [1:10 59 60 61];
Tmatrix = [];
5-1183
5 Functions
Tmatrix = [Tmatrix,results.Temperature(:,snapShotIDs)];
end
thermalmodel.AnalysisType = "modal";
RModal = solve(thermalmodel,"Snapshots",Tmatrix);
Rtherm = reduce(thermalmodel,"ModalResults",RModal)
Rtherm =
ReducedThermalModel with properties:
K: [6x6 double]
M: [6x6 double]
F: [6x1 double]
InitialConditions: [6x1 double]
Mesh: [1x1 FEMesh]
ModeShapes: [1529x5 double]
SnapshotsAverage: [1529x1 double]
Next, use the reduced-order model to simulate the transient dynamics. Use the ode15s function
directly to integrate the reduced system ODE. Specify the mass matrix and the Jacobian for the ODE
solver.
odeoptions = odeset;
odeoptions = odeset(odeoptions,"Mass",Rtherm.M);
odeoptions = odeset(odeoptions,"JConstant","on");
f = @(t,u) -Rtherm.K*u + Rtherm.F;
df = -Rtherm.K;
odeoptions = odeset(odeoptions,"Jacobian",df);
sol = ode15s(f,tlist,Rtherm.InitialConditions,odeoptions);
u = deval(sol,tlist);
R = reconstructSolution(Rtherm,u,tlist);
pdeplot(thermalmodel,"XYData",R.Temperature(:,end))
5-1184
reconstructSolution
Input Arguments
Rcb — Structural results obtained using Craig-Bampton order reduction method
ReducedStructuralModel object
Structural results obtained using the Craig-Bampton order reduction method, specified as a
ReducedStructuralModel object.
u — Displacement
matrix
Displacement, specified as a matrix. The number of rows in the matrix must equal the sum of the
numbers of interface degrees of freedom and the number of modes. The x-displacements at the
retained degrees of freedom must appear first, then the y-displacements, and, for a 3-D geometry, z-
displacements, followed by the generalized modal degrees of freedom. The number of columns must
equal the number of elements in tlist.
Data Types: double
ut — Velocity
matrix
Velocity, specified as a matrix. The number of rows in the matrix must equal the sum of the numbers
of interface degrees of freedom and the number of modes. The x-velocities at the retained degrees of
freedom must appear first, then the y-velocities, and, for a 3-D geometry, z-velocities, followed by the
5-1185
5 Functions
generalized modal degrees of freedom. The number of columns must equal the number of elements in
tlist.
Data Types: double
utt — Acceleration
matrix
Acceleration, specified as a matrix. The number of rows in the matrix must equal the sum of the
numbers of interface degrees of freedom and the number of modes. The x-accelerations at the
retained degrees of freedom must appear first, then the y-accelerations, and, for a 3-D geometry, z-
accelerations, followed by the generalized modal degrees of freedom. The number of columns must
equal the number of elements in tlist.
Data Types: double
Solution times for solving the reduced-order model, specified as a real vector.
Data Types: double
Temperature in modal coordinates, specified as a matrix. The number of rows in the matrix must
equal the number of modes. The number of columns must equal the number of elements in tlist.
Data Types: double
Output Arguments
structuralresults — Transient structural analysis results
TransientStructuralResults object
Version History
Introduced in R2019b
5-1186
reconstructSolution
See Also
StructuralModel | ReducedStructuralModel | ThermalModel | ReducedThermalModel |
ModalThermalResults | reduce | structuralBC | structuralSEInterface | solve
5-1187
5 Functions
reduce
Package: pde
Syntax
Rcb = reduce(structuralmodel,"FrequencyRange",[omega1,omega2])
Rtherm = reduce(thermalmodel,"ModalResults",thermalModalR)
Rtherm = reduce(thermalmodel,"ModalResults",thermalModalR,"NumModes",N)
Description
Rcb = reduce(structuralmodel,"FrequencyRange",[omega1,omega2]) reduces a
structural analysis model to the fixed interface modes in the frequency range [omega1,omega2] and
the boundary interface degrees of freedom.
Examples
Reduce a transient structural model to the fixed interface modes in a specified frequency range and
the boundary interface degrees of freedom.
structuralmodel = createpde("structural","transient-solid");
gm = multicuboid(0.1,0.01,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,"FaceLabels","on","FaceAlpha",0.5)
5-1188
reduce
Specify Young's modulus, Poisson's ratio, and the mass density of the material.
structuralProperties(structuralmodel,"YoungsModulus",70E9, ...
"PoissonsRatio",0.3, ...
"MassDensity",2700);
Generate a mesh.
generateMesh(structuralmodel);
Specify the ends of the beam as structural superelement interfaces. The reduced-order model
technique retains the degrees of freedom on the superelement interfaces while condensing the
degrees of freedom on all other boundaries. For better performance, use the set of edges that bound
each side of the beam instead of using the entire face.
structuralSEInterface(structuralmodel,"Edge",[4,6,9,10]);
structuralSEInterface(structuralmodel,"Edge",[2,8,11,12]);
Reduce the model to the fixed interface modes in the frequency range [-Inf,500000] and the
boundary interface degrees of freedom.
R = reduce(structuralmodel,"FrequencyRange",[-Inf,500000])
R =
ReducedStructuralModel with properties:
K: [166x166 double]
M: [166x166 double]
5-1189
5 Functions
NumModes: 22
RetainedDoF: [144x1 double]
ReferenceLocations: []
Mesh: [1x1 FEMesh]
Reduce a thermal model using all modes or the specified number of modes from the modal solution.
thermalmodel = createpde("thermal","transient");
geometryFromEdges(thermalmodel,@squareg);
pdegplot(thermalmodel,"EdgeLabels","on")
xlim([-1.1 1.1])
ylim([-1.1 1.1])
Specify the thermal conductivity, mass density, and specific heat of the material.
5-1190
reduce
thermalProperties(thermalmodel,"ThermalConductivity",400, ...
"MassDensity",1300, ...
"SpecificHeat",600);
thermalBC(thermalmodel,"Edge",2,"Temperature",100);
thermalIC(thermalmodel,0);
Generate a mesh.
generateMesh(thermalmodel);
Solve the model for three different values of heat source and collect snapshots.
tlist = 0:10:600;
snapShotIDs = [1:10 59 60 61];
Tmatrix = [];
thermalmodel.AnalysisType = "modal";
RModal = solve(thermalmodel,"Snapshots",Tmatrix)
RModal =
ModalThermalResults with properties:
Rtherm = reduce(thermalmodel,"ModalResults",RModal)
Rtherm =
ReducedThermalModel with properties:
K: [7x7 double]
M: [7x7 double]
F: [7x1 double]
InitialConditions: [7x1 double]
Mesh: [1x1 FEMesh]
5-1191
5 Functions
Rtherm3 =
ReducedThermalModel with properties:
K: [4x4 double]
M: [4x4 double]
F: [4x1 double]
InitialConditions: [4x1 double]
Mesh: [1x1 FEMesh]
ModeShapes: [1529x3 double]
SnapshotsAverage: [1529x1 double]
Input Arguments
structuralmodel — Structural model
StructuralModel object
Structural model, specified as a StructuralModel object. The model contains the geometry, mesh,
structural properties of the material, body loads, boundary loads, and boundary conditions.
Example: structuralmodel = createpde("structural","transient-solid")
Frequency range, specified as a vector of two elements. Define omega1 as slightly lower than the
lowest mode's frequency and omega2 as slightly higher than the highest mode's frequency. For
example, if the lowest expected frequency is zero, then use a small negative value for omega1.
You can find natural frequencies and mode shapes for the specified frequency range by solving a
modal analysis problem first. Then you can use a more precise frequency range to reduce the model.
Note that a modal analysis problem still requires you to specify a frequency range. For example, see
“Modal Superposition Method for Structural Dynamics Problem” on page 3-112.
Example: [-0.1,1000]
Data Types: double
Modal thermal analysis model, specified as a ThermalModel object. ThermalModel contains the
geometry, mesh, thermal properties of the material, internal heat source, Stefan-Boltzmann constant,
boundary conditions, and initial conditions.
Example: thermalmodel = createpde("thermal","modal")
5-1192
reduce
N — Number of modes
positive integer
Output Arguments
Rcb — Structural results obtained using Craig-Bampton order reduction method
ReducedStructuralModel object
Structural results obtained using the Craig-Bampton order reduction method, returned as a
ReducedStructuralModel object.
Version History
Introduced in R2019b
See Also
reconstructSolution | StructuralModel | solve | structuralBC |
structuralSEInterface | ReducedStructuralModel | ThermalModel |
ModalThermalResults
5-1193
5 Functions
ReducedStructuralModel
Reduced-order structural model results
Description
A ReducedStructuralModel object contains the stiffness matrix K, mass matrix M, mesh,
multipoint constraint reference locations, and IDs of retained degrees of freedom.
To expand this data to a full solution that includes displacement, velocity, and acceleration, use
reconstructSolution.
Creation
Reduce a structural model by using the reduce function. This function returns structural results
obtained using the Craig-Bampton reduced order method as a ReducedStructuralModel object.
Properties
K — Reduced stiffness matrix
real matrix
• For models without multipoint constraints, N is the sum of the number of retained degrees of
freedom and the number of fixed interface modes.
• For models with Nmp multipoint constraints, N is the sum of 6*Nmp and the number of fixed
interface modes.
• For models without multipoint constraints, N is the sum of the number of retained degrees of
freedom and the number of fixed interface modes.
• For models with Nmp multipoint constraints, N is the sum of 6*Nmp and the number of fixed
interface modes.
5-1194
ReducedStructuralModel
Multipoint constraint reference locations, specified as a real 2-by-Nmp or 3-by-Nmp matrix for a 2-D or
3-D geometry, respectively. Here, Nmp is the number of multipoint constraints. If there are no
multipoint constraints, ReferenceLocations is an empty matrix.
Data Types: double
Finite element mesh, specified as a FEMesh object. For details, see FEMesh.
Object Functions
reconstructSolution Recover full-model transient solution from reduced-order model (ROM)
Examples
Reduce a transient structural model to the fixed interface modes in a specified frequency range and
the boundary interface degrees of freedom.
structuralmodel = createpde("structural","transient-solid");
gm = multicuboid(0.1,0.01,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,"FaceLabels","on","FaceAlpha",0.5)
5-1195
5 Functions
Specify Young's modulus, Poisson's ratio, and the mass density of the material.
structuralProperties(structuralmodel,"YoungsModulus",70E9, ...
"PoissonsRatio",0.3, ...
"MassDensity",2700);
Generate a mesh.
generateMesh(structuralmodel);
Specify the ends of the beam as structural superelement interfaces. The reduced-order model
technique retains the degrees of freedom on the superelement interfaces while condensing the
degrees of freedom on all other boundaries. For better performance, use the set of edges that bound
each side of the beam instead of using the entire face.
structuralSEInterface(structuralmodel,"Edge",[4,6,9,10]);
structuralSEInterface(structuralmodel,"Edge",[2,8,11,12]);
Reduce the model to the fixed interface modes in the frequency range [-Inf,500000] and the
boundary interface degrees of freedom.
R = reduce(structuralmodel,"FrequencyRange",[-Inf,500000])
R =
ReducedStructuralModel with properties:
K: [166x166 double]
M: [166x166 double]
5-1196
ReducedStructuralModel
NumModes: 22
RetainedDoF: [144x1 double]
ReferenceLocations: []
Mesh: [1x1 FEMesh]
More About
Degrees of Freedom (DoFs)
In Partial Differential Equation Toolbox, each node of a 2-D or 3-D geometry has two or three degrees
of freedom (DoFs), respectively. DoFs correspond to translational displacements. If the number of
mesh points in a model is NumNodes, then the toolbox assigns the IDs to the degrees of freedom as
follows:
Version History
Introduced in R2019b
See Also
reduce | reconstructSolution | structuralSEInterface | structuralBC |
StructuralModel
5-1197
5 Functions
ReducedThermalModel
Reduced-order thermal model
Description
A ReducedThermalModel object contains the reduced stiffness matrix K, reduced mass matrix M,
reduced load vector F, initial conditions, mode shapes, mesh, and the average of snapshots used for
proper orthogonal decomposition (POD).
Creation
Reduce a thermal model by using the reduce function. This function returns a reduced-order thermal
model as a ReducedThermalModel object.
Properties
K — Reduced stiffness matrix
matrix
5-1198
ReducedThermalModel
Finite element mesh, specified as an FEMesh object. For details, see FEMesh.
Object Functions
reconstructSolution Recover full-model transient solution from reduced-order model (ROM)
Examples
Reduce a thermal model using all modes or the specified number of modes from the modal solution.
thermalmodel = createpde("thermal","transient");
geometryFromEdges(thermalmodel,@squareg);
pdegplot(thermalmodel,"EdgeLabels","on")
xlim([-1.1 1.1])
ylim([-1.1 1.1])
5-1199
5 Functions
Specify the thermal conductivity, mass density, and specific heat of the material.
thermalProperties(thermalmodel,"ThermalConductivity",400, ...
"MassDensity",1300, ...
"SpecificHeat",600);
thermalBC(thermalmodel,"Edge",2,"Temperature",100);
thermalIC(thermalmodel,0);
Generate a mesh.
generateMesh(thermalmodel);
Solve the model for three different values of heat source and collect snapshots.
tlist = 0:10:600;
snapShotIDs = [1:10 59 60 61];
Tmatrix = [];
5-1200
ReducedThermalModel
Tmatrix = [Tmatrix,results.Temperature(:,snapShotIDs)];
end
thermalmodel.AnalysisType = "modal";
RModal = solve(thermalmodel,"Snapshots",Tmatrix)
RModal =
ModalThermalResults with properties:
Rtherm = reduce(thermalmodel,"ModalResults",RModal)
Rtherm =
ReducedThermalModel with properties:
K: [7x7 double]
M: [7x7 double]
F: [7x1 double]
InitialConditions: [7x1 double]
Mesh: [1x1 FEMesh]
ModeShapes: [1529x6 double]
SnapshotsAverage: [1529x1 double]
Rtherm3 =
ReducedThermalModel with properties:
K: [4x4 double]
M: [4x4 double]
F: [4x1 double]
InitialConditions: [4x1 double]
Mesh: [1x1 FEMesh]
ModeShapes: [1529x3 double]
SnapshotsAverage: [1529x1 double]
Version History
Introduced in R2022a
5-1201
5 Functions
See Also
reduce | reconstructSolution | solve | ThermalModel
5-1202
refinemesh
refinemesh
Package: 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 generateMesh.
Syntax
[p1,e1,t1] = refinemesh(g,p,e,t)
[p1,e1,t1,u1] = refinemesh(g,p,e,t,u)
[ ___ ] = refinemesh( ___ ,it)
[ ___ ] = refinemesh( ___ ,"longest")
Description
[p1,e1,t1,u1] = refinemesh(g,p,e,t,u) refines the mesh and extends the solution u to the
new mesh nodes by linear interpolation. The number of rows in u must correspond to the number of
columns in p, and u1 has as many rows as there are points in p1.
[ ___ ] = refinemesh( ___ ,it) uses the input and output arguments from the previous syntaxes
and specifies the list it of geometric faces or triangles to refine. A scalar or a row vector specifies
faces. A column vector specifies triangles.
[ ___ ] = refinemesh( ___ ,"longest") uses the longest edge refinement, where the longest
edge of each triangle is bisected. By default, refinemesh uses the regular refinement, where all
triangles are divided into four triangles of the same shape. You also can explicitly specify "regular"
instead of "longest". If you use a column vector it to specify the triangles to refine, then
refinemesh can refine some triangles outside of the specified set to preserve the triangulation and
its quality.
Examples
Mesh Refinement
Refine the mesh of the L-shaped membrane several times. Plot the initial mesh and refined meshes at
each step.
5-1203
5 Functions
[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)
pdegplot("lshapeg","FaceLabels","on")
5-1204
refinemesh
Create the initial mesh for the entire geometry, then refine the mesh for face 3 several times. Plot the
initial mesh and refined meshes at each step.
[p,e,t] = initmesh("lshapeg","Hmax",Inf);
subplot(2,2,1)
pdemesh(p,e,t)
[p,e,t] = refinemesh("lshapeg",p,e,t,3);
subplot(2,2,2)
pdemesh(p,e,t)
[p,e,t] = refinemesh("lshapeg",p,e,t,3);
subplot(2,2,3)
pdemesh(p,e,t)
[p,e,t] = refinemesh("lshapeg",p,e,t,3);
subplot(2,2,4)
pdemesh(p,e,t)
5-1205
5 Functions
Input Arguments
g — Geometry description
decomposed geometry matrix | geometry function | handle to geometry function
A geometry function must return the same result for the same input arguments in every function call.
Thus, it must not contain functions and expressions designed to return a variety of results, such as
random number generators.
Data Types: double | char | string | function_handle
p — Mesh points
2-by-Np matrix
Mesh points, specified as a 2-by-Np matrix. 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) and the y-coordinate of point k in p(2,k). For
details, see “Mesh Data as [p,e,t] Triples” on page 2-181.
e — Mesh edges
7-by-Ne matrix
5-1206
refinemesh
Mesh edges, specified as a 7-by-Ne matrix, where 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 as [p,e,t] Triples” on page 2-181.
t — Mesh elements
4-by-Nt matrix
Mesh elements, specified as a 4-by-Nt matrix. Nt is the number of triangles in the mesh.
The t(i,k), with i ranging from 1 through end - 1, contain indices to the corner points of element
k. For details, see “Mesh Data as [p,e,t] Triples” on page 2-181. The last row, t(end,k), contains the
subdomain number of the element.
u — PDE solution
vector
• If the PDE is scalar, meaning that it 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 represent the solution of
equation 1, the next Np elements represent the solution of equation 2, and so on.
Faces or triangles to refine, specified as a positive number or a row or column vector of positive
numbers. A scalar or a row vector specifies faces. A column vector specifies triangles.
Output Arguments
p1 — Refined mesh points
2-by-Np matrix
Refined mesh points, returned as a 2-by-Np matrix. 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) and the y-coordinate of point k in
p(2,k). For details, see “Mesh Data as [p,e,t] Triples” on page 2-181.
Refined mesh edges, returned as a 7-by-Ne matrix, where 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 as [p,e,t] Triples” on page 2-181.
Refined mesh elements, returned as a 4-by-Nt matrix. Nt is the number of triangles in the mesh.
The t(i,k), with i ranging from 1 through end-1, contain indices to the corner points of element k.
For details, see “Mesh Data as [p,e,t] Triples” on page 2-181. The last row, t(end,k), contains the
subdomain number of the element.
5-1207
5 Functions
u1 — PDE solution
vector
• If the PDE is scalar, meaning that it has only one equation, then u1 is a column vector
representing the solution u1 at each node in the mesh.
• If the PDE is a system of N > 1 equations, then u1 is a column vector with N*Np elements, where
Np is the number of nodes in the mesh. The first Np elements of u1 represent the solution of
equation 1, the next Np elements represent the solution of equation 2, and so on.
Algorithms
The refinement algorithm follows these steps:
Version History
Introduced before R2006a
See Also
initmesh
Topics
“Mesh Data as [p,e,t] Triples” on page 2-181
5-1208
rotate
rotate
Package: pde
Rotate geometry
Syntax
h = rotate(g,theta)
h = rotate(g,theta,refpoint)
h = rotate(g,theta,refpoint1,refpoint2)
Description
h = rotate(g,theta) rotates the geometry g about the z-axis by the angle theta, specified in
degrees. Rotation follows the right-hand rule: a positive angle theta rotates counterclockwise, while
sighting along the z-axis toward the origin.
Examples
Rotate a geometry with and without specifying the reference point for the axis of rotation.
Create a model.
model = createpde;
g = importGeometry(model,"PlateHolePlanar.stl");
pdegplot(g)
5-1209
5 Functions
generateMesh(model);
figure
pdemesh(model)
5-1210
rotate
Rotate the geometry around the default z-axis by 45 degrees. Plot the result.
rotate(g,45);
figure
pdegplot(g)
5-1211
5 Functions
Plot the geometry and mesh. The rotate function modifies a geometry, but it does not modify a
mesh.
figure
pdegplot(g)
hold on
pdemesh(model)
5-1212
rotate
generateMesh(model);
figure
pdegplot(g)
hold on
pdemesh(model)
5-1213
5 Functions
rotate(g,-45);
Rotate the geometry by the same angle, but this time use the center of the geometry as a reference
point. The axis of rotation is the line in the z-direction passing through the reference point.
rotate(g,45,[5 10]);
generateMesh(model);
figure
subplot(1,2,1)
pdegplot(model)
axis([-6 16 -1 21])
subplot(1,2,2)
pdemesh(model)
axis([-6 16 -1 21])
5-1214
rotate
Rotate a geometry with and without specifying the reference points for the axis of rotation.
g = multicuboid(1,5,1);
pdegplot(g)
5-1215
5 Functions
Rotate a 3-D geometry around the default z-axis by 45 degrees. Plot the result.
rotate(g,45);
pdegplot(g)
5-1216
rotate
rotate(g,-45);
pdegplot(g)
5-1217
5 Functions
Rotate the geometry by the same angle, but this time around the y-axis.
5-1218
rotate
Input Arguments
g — Geometry
fegeometry object | DiscreteGeometry object | AnalyticGeometry object
Reference point for a rotation axis, specified as a vector of two or three real numbers. The axis of
rotation is the line in the z-direction passing through the reference point.
Example: rotate(g,45,[1 1.5])
5-1219
5 Functions
Reference points that define a rotation axis for a 3-D geometry, specified as a vector of three real
numbers.
Example: rotate(g,45,[0 0 0],[1 1 1])
Output Arguments
h — Resulting geometry
fegeometry object | handle
Tips
• After modifying a geometry, regenerate the mesh to ensure a proper mesh association with the
new geometry.
• If g is an fegeometry or AnalyticGeometry object, and you want to replace it with the
modified geometry, assign the output to the original geometry, for example, g = rotate(g,90).
Version History
Introduced in R2020a
See Also
Functions
scale | translate | pdegplot | importGeometry | geometryFromMesh | generateMesh |
mergeCells
Objects
fegeometry | DiscreteGeometry | AnalyticGeometry
5-1220
scale
scale
Package: pde
Scale geometry
Syntax
h = scale(g,s)
h = scale(g,s,refpoint)
Description
h = scale(g,s) scales the geometry g by the factor s with respect to the origin.
h = scale(g,s,refpoint) scales the geometry with respect to the reference point refpoint.
Examples
Scale a 2-D geometry along the x- and y-axis and ensure consistency with the mesh.
Create a model.
model = createpde;
g = importGeometry(model,"PlateHolePlanar.stl");
pdegplot(model)
5-1221
5 Functions
generateMesh(model);
figure
pdemesh(model)
5-1222
scale
scale(g,[10 1])
ans =
DiscreteGeometry with properties:
NumCells: 0
NumFaces: 1
NumEdges: 5
NumVertices: 5
Vertices: [5x3 double]
figure
pdegplot(model)
5-1223
5 Functions
Plot the geometry and mesh. The scale function modifies a geometry, but it does not modify a mesh.
figure
pdegplot(model)
hold on
pdemesh(model)
5-1224
scale
generateMesh(model);
figure
pdegplot(model)
hold on
pdemesh(model)
5-1225
5 Functions
Reflect the geometry across the x-axis and regenerate the mesh.
scale(g,[1 -1]);
generateMesh(model);
figure
subplot(2,1,1)
pdegplot(model)
subplot(2,1,2)
pdemesh(model)
5-1226
scale
Enlarge a geometry: first uniformly in all directions, and then using different scaling factors along
different axes.
g = multicuboid(1,1,1);
pdegplot(g,"VertexLabels","on","FaceAlpha",0.5)
5-1227
5 Functions
Scale the geometry by a factor of 2 uniformly along all coordinate axes. Plot the result.
scale(g,2);
pdegplot(g,"VertexLabels","on","FaceAlpha",0.5)
5-1228
scale
Now scale by factors of 2, 3, and 4 along the x-, y-, and z-axes, respectively. Plot the result.
scale(g,[2 3 4]);
pdegplot(g,"VertexLabels","on","FaceAlpha",0.5)
5-1229
5 Functions
Flip the geometry upside down by scaling it with the factor -1 and using the bottom front corner
(vertex 1) as a reference point.
5-1230
scale
Input Arguments
g — Geometry
fegeometry object | DiscreteGeometry object | AnalyticGeometry object
s — Scaling factor
nonzero real number | vector of two or three nonzero real numbers
Scaling factor, specified as a real number or vector of two or three real numbers. Use one value for
uniform scaling in all directions. Use a vector of two or three elements to specify different scaling
factors along the x-, y-, and, for a 3-D geometry, z-axes.
Reference point for scaling specified as a vector of two or three real numbers for a 2-D and 3-D
geometry, respectively
5-1231
5 Functions
Output Arguments
h — Resulting geometry
fegeometry object | handle
Tips
• After modifying a geometry, regenerate the mesh to ensure a proper mesh association with the
new geometry.
• If the scaling factor is negative, then the coordinates will flip their signs. The scaling factor of -1
mirrors the existing geometry if the reference point is the origin.
• If g is an fegeometry or AnalyticGeometry object, and you want to replace it with the
modified geometry, assign the output to the original geometry, for example, g = scale(g,20).
Version History
Introduced in R2020a
See Also
Functions
rotate | translate | pdegplot | importGeometry | geometryFromMesh | generateMesh |
mergeCells
Objects
fegeometry | DiscreteGeometry | AnalyticGeometry
5-1232
setInitialConditions
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.
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);
5-1233
5 Functions
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: []
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-1234
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 x2 + y2, except in the lower left
square where it is x2 − y4.
model = createpde();
geometryFromEdges(model,@lshapeg);
pdegplot(model,"FaceLabels","on")
axis equal
ylim([-1.1,1.1])
5-1235
5 Functions
Set the initial conditions on region 2 to x2 − y4. This setting overrides the first setting because you
apply it after the first setting.
Hyperbolic equations have nonzero m coefficient, so you must set both the u0 and ut0 arguments.
model = createpde(3);
importGeometry(model,"Block.stl");
Set the initial condition value to be 0 for all components. Set the initial derivative.
5-1236
setInitialConditions
x
4+
x2 + y2 + z2
ut0 = 5 − tanh z
y
10 2
x + y 2 + z2
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:
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-1237
5 Functions
pdegplot(dl,"EdgeLabels","on","FaceLabels","on")
axis equal
ylim([-0.1,2.1])
Include the geometry in a PDE model, set boundary and initial conditions, and specify coefficients.
model = createpde();
geometryFromEdges(model,dl);
specifyCoefficients(model,"m",0,...
"d",1,...
"c",1,...
"a",0,...
"f",0);
5-1238
setInitialConditions
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")
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)
5-1239
5 Functions
ans =
NodalInitialConditions with properties:
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-1240
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:
tlist2 = 0.2:0.01:1.0;
results2 = solvepde(model,tlist2);
Input Arguments
model — PDE model
PDEModel object
5-1241
5 Functions
u0 — Initial condition
scalar | column vector of length N | function handle
Initial conditions, 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 PDE Toolbox” on page 1-3.
• 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 PDE Toolbox” on
page 1-3. 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
5-1242
setInitialConditions
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)
Data Types: char | string
Geometric region ID, specified as a vector of positive integers. Find the region IDs by using
pdegplot.
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-1243
5 Functions
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.
Version History
Introduced in R2016a
You can now set initial conditions at the mesh nodes by using the solution from a previous analysis on
the same geometry and mesh.
See Also
findInitialConditions | pdegplot | PDEModel
Topics
“Set Initial Conditions” on page 2-113
“Set Initial Condition for Model with Fine Mesh Using Solution Obtained with Coarser Mesh” on page
2-120
“Nonlinear System with Cross-Coupling Between Components” on page 2-116
“Solve Problems Using PDEModel Objects” on page 2-3
“Equations You Can Solve Using PDE Toolbox” on page 1-3
5-1244
setupRadiation
setupRadiation
Specify radiation parameters for surface-to-surface heat transfer
Syntax
fem = setupRadiation(fem)
fem = setupRadiation(fem,Name=Value)
Description
fem = setupRadiation(fem) enables surface-to-surface radiation analysis using the enclosure
formed by all faces of the specified model. An enclosure is a group of surfaces between which heat
transfer occurs due to radiation without conductive media. The function creates a
surfaceToSurfaceSettings object and returns the specified model, fem, with its
ThermalRadiation property set to that object.
Examples
Specify radiation parameters for heat transfer between two parallel plates.
Create the geometry representing two parallel plates of the same dimensions. The distance between
the plates is 0.4 m.
dist = 0.4;
W = 0.05;
L = 0.5;
H = 0.5;
R1 = [3 4 0 W W 0 0 0 L L];
R2 = [3 4 W+dist 2*W+dist 2*W+dist W+dist 0 0 L L];
geom2D = fegeometry(decsg([R1(:) R2(:)], ...
'R1+R2',[char('R1')' char('R2')']));
geom3D = extrude(geom2D,H);
pdegplot(geom3D,FaceLabels="on",FaceAlpha=0.3)
5-1245
5 Functions
Create a finite element model for thermal analysis and include the geometry.
fem = femodel(AnalysisType="thermalSteady",Geometry=geom3D);
Generate a mesh.
fem = generateMesh(fem,Hmax=H/4);
Account for surface-to-surface radiation in the enclosure formed by the plates by using the
setupRadiation function.
fem = setupRadiation(fem,EnclosureFaces=[5 6]);
fem.ThermalRadiation
ans =
surfaceToSurfaceSettings with properties:
If you do not specify enclosure names, setupRadiation uses the default names, such as
"Enclosure_1". The function also sets the enclosure perfectness to true, which means that the
solver ignores ambient radiation. To change these settings, use the EnclosureNames and
PerfectEnclosure name-value arguments.
fem = setupRadiation(fem,EnclosureFaces=[5 6], ...
EnclosureNames="two_plates", ...
5-1246
setupRadiation
PerfectEnclosure=false);
fem.ThermalRadiation
ans =
surfaceToSurfaceSettings with properties:
Specify ambient temperature and emissivity for the enclosure formed by the plates.
fem.FaceLoad([5 6]) = faceLoad(AmbientTemperature=0,Emissivity=0.5);
Input Arguments
fem — Finite element model
femodel object
Faces to form enclosures, specified as a vector of positive integers for one enclosure in the model or a
cell array of vectors of positive integers for multiple enclosures in the model.
Example: EnclosureFaces={[1 2 50],[68 97]}
Names of enclosures, specified as a string or a character vector for a single enclosure or a vector of
strings or cell array of character vectors for multiple enclosures.
Example: EnclosureNames=["groupA" "groupB"]
Data Types: string | char
Enclosure perfectness, specified as true or false for a single enclosure or a vector of these values
for multiple enclosures. Setting perfectness to true ignores ambient radiation.
Example: PerfectEnclosure=[true false]
5-1247
5 Functions
Tips
• You must generate a mesh before specifying radiation parameters. Call generateMesh before
calling setupRadiation.
• When calling setupRadiation, always use fem as the output argument to assign the resulting
surfaceToSurfaceSettings object to the ThermalRadiation property of the model.
Version History
Introduced in R2023b
See Also
Objects
femodel | faceLoad | surfaceToSurfaceSettings
5-1248
solve
solve
Package: pde
Syntax
results = solve(fem)
results = solve(fem,tlist)
results = solve(fem,flist)
results = solve(fem,"FrequencyRange",[omega1,omega2])
results = solve(fem,"DecayRange",[lambda1,lambda2])
results = solve(fem,"Snapshots",Tmatrix)
results = solve(fem,tlist,"ModalResults",thermalModalR)
results = solve(fem,tlist,"ModalResults",structuralModalR)
results = solve(fem,flist,"ModalResults",structuralModalR)
results = solve(fem,tlist,"ModalResults",structuralModalR,"DampingZeta",z)
results = solve(fem,flist,"ModalResults",structuralModalR,"DampingZeta",z)
structuralStaticResults = solve(structuralStatic)
structuralTransientResults = solve(structuralTransient,tlist)
structuralFrequencyResponseResults = solve(structuralFrequencyResponse,flist)
structuralModalResults = solve(structuralModal,"FrequencyRange",
[omega1,omega2])
structuralTransientResults = solve(structuralTransient,tlist,"ModalResults",
structuralModalR)
structuralFrequencyResponseResults = solve(structuralFrequencyResponse,
flist,"ModalResults",structuralModalR)
thermalSteadyStateResults = solve(thermalSteadyState)
thermalTransientResults = solve(thermalTransient,tlist)
thermalModalResults = solve(thermalModal,"DecayRange",[lambda1,lambda2])
thermalModalResults = solve(thermalModal,"Snapshots",Tmatrix)
thermalTransientResults = solve(thermalTransient,tlist,"ModalResults",
thermalModalR)
emagStaticResults = solve(emagmodel)
emagHarmonicResults = solve(emagmodel,"Frequency",omega)
Description
results = solve(fem) solves the structural, thermal, or electromagnetic problem represented by
the finite element analysis model fem.
5-1249
5 Functions
range [omega1,omega2]. Define omega1 as slightly lower than the lowest expected frequency and
omega2 as slightly higher than the highest expected frequency. For example, if the lowest expected
frequency is zero, then use a small negative value for omega1.
structuralFrequencyResponseResults = solve(structuralFrequencyResponse,flist)
returns the solution to the frequency response model represented in
structuralFrequencyResponse at the frequencies specified in flist.
structuralModalResults = solve(structuralModal,"FrequencyRange",
[omega1,omega2]) returns the solution to the modal analysis model for all modes in the frequency
range [omega1,omega2]. Define omega1 as slightly lower than the lowest expected frequency and
omega2 as slightly higher than the highest expected frequency. For example, if the lowest expected
frequency is zero, then use a small negative value for omega1.
structuralTransientResults = solve(structuralTransient,tlist,"ModalResults",
structuralModalR) and structuralFrequencyResponseResults = solve(
structuralFrequencyResponse,flist,"ModalResults",structuralModalR) solves a
transient and a frequency response structural model, respectively, by using the modal superposition
method to speed up computations. First, perform modal analysis to compute natural frequencies and
mode shapes in a particular frequency range. Then, use this syntax to invoke the modal superposition
method. The accuracy of the results depends on the modes in the modal analysis results.
5-1250
solve
thermalModalResults = solve(thermalModal,"DecayRange",[lambda1,lambda2])
performs an eigen decomposition of a linear thermal model thermalModal for all modes in the decay
range [lambda1,lambda2]. The resulting modes enable you to:
thermalTransientResults = solve(thermalTransient,tlist,"ModalResults",
thermalModalR) solves a transient thermal model by using the modal superposition method to
speed up computations. First, perform modal decomposition to compute mode shapes for a particular
decay range. Then, use this syntax to invoke the modal superposition method. The accuracy of the
results depends on the modes in the modal analysis results.
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-1251
5 Functions
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]);
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel)
structuralresults =
StaticStructuralResults with properties:
5-1252
solve
The solver finds the values of the displacement, stress, strain, and von Mises stress at the nodal
locations. To access these values, use structuralresults.Displacement,
structuralresults.Stress, and so on. The displacement, stress, and strain values at the nodal
locations are returned as FEStruct objects with the properties representing their components. Note
that properties of an FEStruct object are read-only.
structuralresults.Displacement
ans =
FEStruct with properties:
structuralresults.Stress
ans =
FEStruct with properties:
structuralresults.Strain
ans =
FEStruct with properties:
pdeplot3D(structuralmodel, ...
"ColorMapData",structuralresults.Stress.szz, ...
"Deformation",structuralresults.Displacement)
5-1253
5 Functions
Solve for the 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-1254
solve
Zoom in to see the face labels on the small plate at the center.
figure
pdegplot(structuralmodel,"FaceLabels","on","FaceAlpha",0.25)
axis([-0.2 0.2 -0.2 0.2 -0.1 0.1])
5-1255
5 Functions
Specify Young's modulus, Poisson's ratio, and the 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);
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);
5-1256
solve
The solver finds the values of the displacement, velocity, and acceleration at the nodal locations. To
access these values, use structuralresults.Displacement, structuralresults.Velocity,
and so on. The displacement, velocity, and acceleration values are returned as FEStruct objects with
the properties representing their components. Note that properties of an FEStruct object are read-
only.
structuralresults.Displacement
ans =
FEStruct with properties:
structuralresults.Velocity
ans =
FEStruct with properties:
structuralresults.Acceleration
ans =
FEStruct with properties:
First, create a structural model for modal analysis of a solid tuning fork.
model = createpde("structural","frequency-solid");
importGeometry(model,"TuningFork.stl");
Specify Young's modulus, Poisson's ratio, and the mass density to model linear elastic material
behavior. Specify all physical properties in consistent units.
5-1257
5 Functions
structuralProperties(model,"YoungsModulus",210E9, ...
"PoissonsRatio",0.3, ...
"MassDensity",8000);
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(model,"FaceLabels","on")
view(-50,15)
title("Geometry with Face Labels")
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. To create a simple approximation of this
boundary condition, fix a region near the intersection of tines and the handle (faces 21 and 22).
structuralBC(model,"Face",[21,22],"Constraint","fixed");
5-1258
solve
Specify the pressure loading on a tine (face 11) as a short rectangular pressure pulse. In the
frequency domain, this pressure pulse is a unit load uniformly distributed across all frequencies.
structuralBoundaryLoad(model,"Face",11,"Pressure",1);
flist = linspace(0,4000,150);
mesh = generateMesh(model,"Hmax",0.005);
R = solve(model,2*pi*flist);
Plot the vibration frequency of the tine tip, which is face 12. Find nodes on the tip face and plot the y-
component of the displacement over the frequency, using one of these nodes.
excitedTineTipNodes = findNodes(mesh,"region","Face",12);
tipDisp = R.Displacement.uy(excitedTineTipNodes(1),:);
figure
plot(flist,abs(tipDisp))
xlabel("Frequency");
ylabel("|Y-Displacement|");
Find the fundamental (lowest) mode of a 2-D cantilevered beam, assuming prevalence of the plane-
stress condition.
Specify geometric and structural properties of the beam, along with a unit plane-stress thickness.
5-1259
5 Functions
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.
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
5-1260
solve
0.1462
0.1930
0.2455
⋮
modalresults.ModeShapes
ans =
FEStruct with properties:
pdeplot(modalresults.Mesh,XYData=modalresults.ModeShapes.uy(:,1))
title(['First Mode with Frequency ', ...
num2str(modalresults.NaturalFrequencies(1)/(2*pi)),' Hz'])
axis equal
5-1261
5 Functions
Solve for the transient response at the center of a 3-D beam under a harmonic load on one of its
corners.
Modal Analysis
structuralmodel = createpde("structural","modal-solid");
Create the geometry and include it in the model. Plot the geometry and display the edge and vertex
labels.
gm = multicuboid(0.05,0.003,0.003);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,"EdgeLabels","on", ...
"VertexLabels","on");
view([95 5])
Generate a mesh.
msh = generateMesh(structuralmodel);
Specify Young's modulus, Poisson's ratio, and the mass density of the material.
5-1262
solve
structuralProperties(structuralmodel,"YoungsModulus",210E9, ...
"PoissonsRatio",0.3, ...
"MassDensity",7800);
Specify minimal constraints on one end of the beam to prevent rigid body modes. For example,
specify that edge 4 and vertex 7 are fixed boundaries.
structuralBC(structuralmodel,"Edge",4,"Constraint","fixed");
structuralBC(structuralmodel,"Vertex",7,"Constraint","fixed");
Solve the problem for the frequency range from 0 to 500,000. The recommended approach is to use a
value that is slightly lower than the expected lowest frequency. Thus, use -0.1 instead of 0.
Rm = solve(structuralmodel,"FrequencyRange",[-0.1,500000]);
Transient Analysis
structuralmodel.AnalysisType = "transient-solid";
Apply a sinusoidal force on the corner opposite of the constrained edge and vertex.
structuralBoundaryLoad(structuralmodel,"Vertex",5, ...
"Force",[0,0,10], ...
"Frequency",7600);
structuralIC(structuralmodel,"Velocity",[0;0;0], ...
"Displacement",[0;0;0]);
structuralmodel.SolverOptions.RelativeTolerance = 1E-5;
structuralmodel.SolverOptions.AbsoluteTolerance = 1E-9;
tlist = linspace(0,0.004,120);
Rdm = solve(structuralmodel,tlist,"ModalResults",Rm);
intrpUdm = interpolateDisplacement(Rdm,0,0,0.0015);
plot(Rdm.SolutionTimes,intrpUdm.uz)
grid on
xlabel("Time");
ylabel("Center of beam displacement")
5-1263
5 Functions
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-1264
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 of the beam.
thermalBC(thermalmodel,"Face",3,"Temperature",100);
thermalBC(thermalmodel,"Face",5,"Temperature",0);
internalHeatSource(thermalmodel,10);
thermalIC(thermalmodel,0);
tlist = 0:1e-4:2e-4;
thermalresults = solve(thermalmodel,tlist)
5-1265
5 Functions
thermalresults =
TransientThermalResults with properties:
for n = 1:numel(thermalresults.SolutionTimes)
figure
pdeplot3D(thermalmodel, ...
"ColorMapData", ...
thermalresults.Temperature(:,n))
title(["Temperature at Time = " ...
num2str(tlist(n))])
end
5-1266
solve
5-1267
5 Functions
structuralmodel = createpde("structural","static-solid");
structuralmodel.Geometry = gm;
Use the same mesh that you used to obtain the thermal solution.
structuralmodel.Mesh = mesh;
Specify Young's modulus, Poisson's ratio, and the coefficient of thermal expansion.
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);
5-1268
solve
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))])
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);
5-1269
5 Functions
figure
pdeplot3D(structuralmodel, ...
"ColorMapData", ...
thermalstressresults.Displacement.Magnitude, ...
"Deformation", ...
thermalstressresults.Displacement)
title(["Thermal Results at Solution Time = " ...
num2str(tlist(n))])
end
5-1270
solve
5-1271
5 Functions
thermalmodel = createpde(thermal="steadystate");
importGeometry(thermalmodel,"Block.stl");
pdegplot(thermalmodel,FaceLabels="on",FaceAlpha=0.5)
axis equal
5-1272
solve
Apply a constant temperature of 100 °C to the left side of the block (face 1) and a constant
temperature of 300 °C 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);
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 the nodal locations.
5-1273
5 Functions
pdeplot3D(thermalresults.Mesh,ColorMapData=thermalresults.Temperature)
thermalmodel = createpde(thermal="transient");
5-1274
solve
• Thermal conductivity is 10 W/ m ⋅∘ C
• Mass density is 2 kg/m3
• Specific heat is 0 . 1 J/ kg ⋅ ∘C
thermalProperties(thermalmodel,ThermalConductivity=10, ...
MassDensity=2, ...
SpecificHeat=0.1, ...
Face=1);
• Thermal conductivity is 2 W/ m ⋅∘ C
• Mass density is 1 kg/m3
• Specific heat is 0 . 1 J/ kg ⋅ ∘C
thermalProperties(thermalmodel,ThermalConductivity=2, ...
MassDensity=1, ...
SpecificHeat=0.1, ...
Face=2);
Assume that the diamond-shaped region is a heat source with a density of 4 W/m2.
internalHeatSource(thermalmodel,4,Face=2);
5-1275
5 Functions
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 most active 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);
T = thermalresults.Temperature;
msh = thermalresults.Mesh;
pdeplot(msh,XYData=T(:,10),Contour="on",ColorMap="hot")
5-1276
solve
Solve a transient thermal problem by first obtaining mode shapes for a particular decay range and
then using the modal superposition method.
Modal Decomposition
5-1277
5 Functions
• Thermal conductivity is 10 W/ m ⋅∘ C .
• Mass density is 2 kg/m3.
• Specific heat is 0 . 1 J/ kg ⋅ ∘C .
thermalProperties(thermalmodel,"ThermalConductivity",10, ...
"MassDensity",2, ...
"SpecificHeat",0.1, ...
"Face",1);
• Thermal conductivity is 2 W/ m ⋅∘ C .
• Mass density is 1 kg/m3.
• Specific heat is 0 . 1 J/ kg ⋅ ∘C .
thermalProperties(thermalmodel,"ThermalConductivity",2, ...
"MassDensity",1, ...
"SpecificHeat",0.1, ...
"Face",2);
Assume that the diamond-shaped region is a heat source with a density of 4 W/m2.
internalHeatSource(thermalmodel,4,"Face",2);
thermalBC(thermalmodel,"Temperature",0,"Edge",[1 2 7 8]);
thermalIC(thermalmodel,0);
generateMesh(thermalmodel);
Compute eigenmodes of the thermal model in the decay range [100,10000] s−1.
RModal = solve(thermalmodel,"DecayRange",[100,10000])
RModal =
ModalThermalResults with properties:
Transient Analysis
Knowing the mode shapes, you can now use the modal superposition method to solve the transient
thermal problem. First, switch the thermal model analysis type to transient.
5-1278
solve
thermalmodel.AnalysisType = "transient";
The dynamics for this problem are very fast. The temperature reaches a steady state in about 0.1
second. To capture the most active part of the dynamics, set the solution time to
logspace(-2,-1,100). This command returns 100 logarithmically spaced solution times between
0.01 and 0.1.
tlist = logspace(-2,-1,10);
Obtain POD modes of a linear thermal model using several instances of the transient solution
(snapshots).
5-1279
5 Functions
thermalmodel = createpde("thermal","transient");
Specify the thermal conductivity, mass density, and specific heat of the material.
thermalProperties(thermalmodel,"ThermalConductivity",400, ...
"MassDensity",1300, ...
"SpecificHeat",600);
Generate a mesh.
generateMesh(thermalmodel);
5-1280
solve
Solve the model for three different values of heat source and collect snapshots.
tlist = 0:10:600;
snapShotIDs = [1:10 59 60 61];
Tmatrix = [];
thermalmodel.AnalysisType = "modal";
RModal = solve(thermalmodel,"Snapshots",Tmatrix)
RModal =
ModalThermalResults with properties:
Solve an electromagnetic problem and find the electric potential and field distribution for a 2-D
geometry representing a plate with a hole.
emagmodel = createpde(electromagnetic="electrostatic");
importGeometry(emagmodel,"PlateHolePlanar.stl");
pdegplot(emagmodel,EdgeLabels="on")
5-1281
5 Functions
emagmodel.VacuumPermittivity = 8.8541878128E-12;
electromagneticProperties(emagmodel,RelativePermittivity=1);
Apply the voltage boundary conditions on the edges framing the rectangle and the circle.
electromagneticBC(emagmodel,Voltage=0,Edge=1:4);
electromagneticBC(emagmodel,Voltage=1000,Edge=5);
electromagneticSource(emagmodel,ChargeDensity=5E-9);
generateMesh(emagmodel);
R = solve(emagmodel)
R =
ElectrostaticResults with properties:
5-1282
solve
Solve a 3-D electromagnetic problem on a geometry representing a plate with a hole in its center. Plot
the resulting magnetic potential and field distribution.
5-1283
5 Functions
emagmodel.VacuumPermeability = 1.2566370614e-6;
electromagneticProperties(emagmodel,"RelativePermeability",5000);
Apply the magnetic potential boundary conditions on the side faces and the face bordering the hole.
electromagneticBC(emagmodel,"MagneticPotential",[0;0;0],"Face",3:6);
electromagneticBC(emagmodel,"MagneticPotential",[0;0;0.01],"Face",7);
electromagneticSource(emagmodel,"CurrentDensity",[0;0;0.5]);
generateMesh(emagmodel);
R = solve(emagmodel)
R =
MagnetostaticResults with properties:
5-1284
solve
pdeplot3D(emagmodel,"ColormapData",R.MagneticPotential.Az)
pdeplot3D(emagmodel,"FlowData",[R.MagneticField.Hx ...
R.MagneticField.Hy ...
R.MagneticField.Hz])
5-1285
5 Functions
Solve a DC conduction problem on a geometry representing a 3-D plate with a hole in its center. Plot
the electric potential and the components of the current density.
emagmodel = createpde("electromagnetic","conduction");
gm = importGeometry(emagmodel,"PlateHoleSolid.stl");
pdegplot(gm,"FaceLabels","on","FaceAlpha",0.3)
5-1286
solve
electromagneticProperties(emagmodel,"Conductivity",6e4);
Apply the voltage boundary conditions on the left, right, top, and bottom faces of the plate.
electromagneticBC(emagmodel,"Voltage",0,"Face",3:6);
Specify the surface current density on the face bordering the hole.
electromagneticBC(emagmodel,"SurfaceCurrentDensity",100,"Face",7);
generateMesh(emagmodel);
R = solve(emagmodel)
R =
ConductionResults with properties:
5-1287
5 Functions
figure
pdeplot3D(emagmodel,"ColorMapData",R.ElectricPotential)
figure
pdeplot3D(emagmodel,"ColorMapData",R.CurrentDensity.Jx)
title("x-Component of Current Density")
5-1288
solve
figure
pdeplot3D(emagmodel,"ColorMapData",R.CurrentDensity.Jy)
title("y-Component of Current Density")
5-1289
5 Functions
figure
pdeplot3D(emagmodel,"ColorMapData",R.CurrentDensity.Jz)
title("z-Component of Current Density")
5-1290
solve
Use a solution obtained by performing a DC conduction analysis to specify current density for a
magnetostatic model.
emagmodel = createpde("electromagnetic","conduction");
gm = importGeometry(emagmodel,"PlateHoleSolid.stl");
pdegplot(gm,"FaceLabels","on","FaceAlpha",0.3)
5-1291
5 Functions
Apply the voltage boundary conditions on the left, right, top, and bottom faces of the plate.
electromagneticBC(emagmodel,"Voltage",0,"Face",3:6);
Specify the surface current density on the face bordering the hole.
electromagneticBC(emagmodel,"SurfaceCurrentDensity",100,"Face",7);
This model already has a quadratic mesh that you generated for the DC conduction analysis. For a 3-
D magnetostatic model, the mesh must be linear. Generate a new linear mesh. The generateMesh
function creates a linear mesh by default if the model is 3-D and magnetostatic.
generateMesh(emagmodel);
5-1292
solve
emagmodel.VacuumPermeability = 1.2566370614e-6;
electromagneticProperties(emagmodel,"RelativePermeability",5000);
Apply the magnetic potential boundary conditions on the side faces and the face bordering the hole.
electromagneticBC(emagmodel,"MagneticPotential",[0;0;0],"Face",3:6);
electromagneticBC(emagmodel,"MagneticPotential",[0;0;0.01],"Face",7);
Specify the current density for the entire geometry using the DC conduction solution.
electromagneticSource(emagmodel,"CurrentDensity",R);
Rmagnetostatic = solve(emagmodel);
pdeplot3D(emagmodel,"ColormapData",Rmagnetostatic.MagneticPotential.Ax)
pdeplot3D(emagmodel,"ColormapData",Rmagnetostatic.MagneticPotential.Az)
5-1293
5 Functions
Solve a magnetostatic model of a copper square with a permanent neodymium magnet in its center.
L = 0.8;
r = 0.25;
sq = [3 4 -L L L -L -L -L L L]';
circ = [1 0 0 r 0 0 0 0 0 0]';
gd = [sq,circ];
sf = "sq + circ";
ns = char('sq','circ');
ns = ns';
g = decsg(gd,sf,ns);
pdegplot(g,"FaceLabels","on","EdgeLabels","on")
5-1294
solve
emagmodel = createpde("electromagnetic","magnetostatic");
geometryFromEdges(emagmodel,g);
emagmodel.VacuumPermeability = 1.2566370614e-6;
electromagneticProperties(emagmodel,"Face",1, ...
"RelativePermeability",1);
electromagneticProperties(emagmodel,"Face",2, ...
"RelativePermeability",1.05);
M = 1e6;
Specify magnetization on the circular face in the positive x-direction. Magnetization for a 2-D model
is a column vector of two elements.
dir = [1;0];
electromagneticSource(emagmodel,"Face",2,"Magnetization",M*dir);
5-1295
5 Functions
Apply the magnetic potential boundary conditions on the edges framing the square.
electromagneticBC(emagmodel,"Edge",1:4,"MagneticPotential",0);
Generate the mesh with finer meshing near the edges of the circle.
generateMesh(emagmodel,"Hedge",{5:8,0.007});
figure
pdemesh(emagmodel)
Solve the model, and find the resulting magnetic fields B and H. Here, B = μH + μ0M, where μ is the
absolute magnetic permeability of the material, μ0 is the vacuum permeability, and M is the
magnetization.
R = solve(emagmodel);
Bmag = sqrt(R.MagneticFluxDensity.Bx.^2 + R.MagneticFluxDensity.By.^2);
Hmag = sqrt(R.MagneticField.Hx.^2 + R.MagneticField.Hy.^2);
figure
pdeplot(emagmodel,"XYData",Bmag, ...
"FlowData",[R.MagneticFluxDensity.Bx ...
R.MagneticFluxDensity.By])
5-1296
solve
figure
pdeplot(emagmodel,"XYData",Hmag, ...
"FlowData",[R.MagneticField.Hx R.MagneticField.Hy])
5-1297
5 Functions
For an electromagnetic harmonic analysis problem, find the x- and y-components of the electric field.
Solve the problem on a domain consisting of a square with a circular hole.
Define a circle in a square, place them in one matrix, and create a set formula that subtracts the
circle from the square.
SQ = [3,4,-5,-5,5,5,-5,5,5,-5]';
C = [1,0,0,1]';
C = [C;zeros(length(SQ) - length(C),1)];
gm = [SQ,C];
sf = 'SQ-C';
Include the geometry in the model and plot the geometry with the edge labels.
5-1298
solve
geometryFromEdges(emagmodel,g);
pdegplot(emagmodel,"EdgeLabels","on")
xlim([-5.5 5.5])
ylim([-5.5 5.5])
Specify the relative permittivity, relative permeability, and conductivity of the material.
electromagneticProperties(emagmodel,"RelativePermittivity",1, ...
"RelativePermeability",1, ...
"Conductivity",0);
Apply the absorbing boundary condition with a thickness of 2 on the edges of the square. Use the
default attenuation rate for the absorbing region.
electromagneticBC(emagmodel,"Edge",1:4, ...
"FarField","absorbing", ...
"Thickness",2);
Generate a mesh.
5-1299
5 Functions
generateMesh(emagmodel,"Hmax",1/2^3);
result = solve(emagmodel,"Frequency",2*pi);
Plot the real part of the x-component of the resulting electric field.
figure
pdeplot(emagmodel,"XYData",real(result.ElectricField.Ex));
title("Real Part of x-Component of Electric Field")
Plot the real part of the y-component of the resulting electric field.
figure
pdeplot(emagmodel,"XYData",real(result.ElectricField.Ey));
title("Real Part of y-Component of Electric Field")
5-1300
solve
Input Arguments
fem — Finite element analysis model
femodel object
Finite element analysis model, specified as an femodel object. The model contains information about
a finite element problem: analysis type, geometry, material properties, boundary conditions, loads,
initial conditions, and other parameters. Depending on the analysis type, it represents a structural,
thermal, or electromagnetic problem.
Example: model = femodel(AnalysisType = "structuralStatic")
Static structural analysis model, specified as a StructuralModel object. The model contains the
geometry, mesh, structural properties of the material, body loads, boundary loads, and boundary
conditions.
Example: structuralmodel = createpde("structural","static-solid")
5-1301
5 Functions
Transient structural analysis model, specified as a StructuralModel object. The model contains the
geometry, mesh, structural properties of the material, body loads, boundary loads, and boundary
conditions.
Example: structuralmodel = createpde("structural","transient-solid")
Frequency response analysis structural model, specified as a StructuralModel object. The model
contains the geometry, mesh, structural properties of the material, body loads, boundary loads, and
boundary conditions.
Example: structuralmodel = createpde("structural","frequency-solid")
Modal analysis structural model, specified as a StructuralModel object. The model contains the
geometry, mesh, structural properties of the material, body loads, boundary loads, and boundary
conditions.
Example: structuralmodel = createpde("structural","modal-solid")
Solution times for structural or thermal transient analysis, specified as a real vector of monotonically
increasing or decreasing values.
Example: 0:20
Data Types: double
Solution frequencies for a frequency response structural analysis, specified as a real vector of
monotonically increasing or decreasing values.
Example: linspace(0,4000,150)
Data Types: double
Frequency range for a structural modal analysis, specified as a vector of two elements. Define
omega1 as slightly lower than the lowest expected frequency and omega2 as slightly higher than the
highest expected frequency. For example, if the lowest expected frequency is zero, then use a small
negative value for omega1.
Example: [-0.1,1000]
Data Types: double
5-1302
solve
Transient thermal analysis model, specified as a ThermalModel object. ThermalModel contains the
geometry, mesh, thermal properties of the material, internal heat source, Stefan-Boltzmann constant,
boundary conditions, and initial conditions.
Modal thermal analysis model, specified as a ThermalModel object. ThermalModel contains the
geometry, mesh, thermal properties of the material, internal heat source, Stefan-Boltzmann constant,
boundary conditions, and initial conditions.
Decay range for modal thermal analysis, specified as a vector of two elements. The solve function
solves a modal thermal analysis model for all modes in the decay range.
Data Types: double
Modal damping ratio, specified as a nonnegative number or a function handle. Use a function handle
when each mode has its own damping ratio. The function must accept a vector of natural frequencies
as an input argument and return a vector of corresponding damping ratios. It must cover the full
frequency range for all modes used for modal solution. For details, see “Modal Damping Depending
on Frequency” on page 5-1401.
5-1303
5 Functions
Output Arguments
results — Structural, thermal, or electromagnetic analysis results
StaticStructuralResults object | TransientStructuralResults object |
FrequencyStructuralResults object | ModalStructuralResults object |
SteadyStateThermalResults object | TransientThermalResults object |
ModalThermalResults object | ElectrostaticResults object | MagnetostaticResults object
| ConductionResults object | HarmonicResults object
5-1304
solve
Tips
• When you use modal analysis results to solve a transient structural dynamics model, the
modalresults argument must be created in Partial Differential Equation Toolbox from R2019a or
newer.
• For a frequency response model with damping, the results are complex. Use functions such as abs
and angle to obtain real-valued results, such as the magnitude and phase.
Version History
Introduced in R2017a
The solver accepts the femodel object that defines structural mechanics, thermal, and
electromagnetic problems.
You can now solve stationary current distribution in conductors due to applied voltage. You also can
solve electromagnetic problems accounting for magnetization of materials.
You can now solve 2-D and 3-D time-harmonic Maxwell’s equations (the Helmholtz equation).
5-1305
5 Functions
You can now compute modes of a thermal model using eigenvalue or proper orthogonal
decomposition. You also can speed up computations for a transient thermal model by using the
computed modes.
You can now solve axisymmetric structural and thermal problems. Axisymmetric analysis simplifies 3-
D thermal problems to 2-D using their symmetry around the axis of rotation.
You can now solve frequency response structural problems and find displacement, velocity,
acceleration, and solution frequencies at nodal locations of the mesh. To speed up computations, you
can use modal analysis results for frequency response analysis. The ModalResults argument
triggers the solve function to use the modal superposition method.
You can now specify the maximum number of Lanczos shifts and the block size for block Lanczos
recurrence by using the SolverOptions property of StructuralModel. For details, see
PDESolverOptions.
The new ModalResults argument triggers the solve function to switch to the modal transient
solver instead of using the direct integration approach.
The solver now solves accounts for mechanical and thermal effects when solving a static structural
analysis model. The function returns a displacement, stress, strain, and von Mises stress induced by
both mechanical and thermal loads.
You can now solve dynamic linear elasticity problems and find displacement, velocity, and
acceleration at nodal locations of the mesh.
5-1306
solve
You also can solve modal analysis problems and find natural frequencies and mode shapes of a
structure. When solving a modal analysis model, the solver requires a frequency range parameter and
returns the modal solution in that frequency range.
You can now solve static linear elasticity problems and find displacement, stress, strain, and von
Mises stress at nodal locations of the mesh.
See Also
Functions
geometryFromEdges | geometryFromMesh | importGeometry | reduce
Objects
femodel | StructuralModel | ThermalModel | ElectromagneticModel | PDEModel
5-1307
5 Functions
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-1308
solvepde
applyBoundaryCondition(model,"dirichlet", ...
"Edge",1:model.Geometry.NumEdges, ...
"u",0);
Poisson's equation is
− ∇ ⋅ ∇u = 1 .
∂2 u ∂u
m +d − ∇ c ∇u + au = f .
∂t2 ∂t
specifyCoefficients(model,"m",0,...
"d",0,...
"c",1,...
"a",0,...
"f",1);
generateMesh(model,"Hmax",0.25);
results = solvepde(model);
5-1309
5 Functions
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-1310
solvepde
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))
figure
pdeplot3D(model,"ColorMapData",results.NodalSolution(:,21))
5-1311
5 Functions
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)
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
5-1312
solvepde
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.
Version History
Introduced in R2016a
See Also
applyBoundaryCondition | setInitialConditions | solvepdeeig | specifyCoefficients |
PDEModel
Topics
“Solve Problems Using PDEModel Objects” on page 2-3
5-1313
5 Functions
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. If the range does not contain any eigenvalues, solvepdeeig returns
an EigenResults object with the empty EigenVectors, EigenValues, and Mesh properties.
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.4)
5-1314
solvepdeeig
Set the model coefficients to represent a steel bracket. For details, see “Linear Elasticity Equations”
on page 3-194. When specifying the f-coefficient, assume that all body forces are zero.
E = 200e9; % elastic modulus of steel in Pascals
nu = 0.3; % Poisson's ratio
specifyCoefficients(model,"m",0,...
"d",1,...
"c",elasticityC3D(E,nu),...
"a",0,...
"f",[0;0;0]);
ans = 3
5-1315
5 Functions
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")
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-1316
solvepdeeig
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)
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
5-1317
5 Functions
Eigenvalue results, returned as an EigenResults object. If the range env does not contain any
eigenvalues, the returned EigenResults object has the empty EigenVectors, EigenValues, and
Mesh properties.
Tips
• The equation coefficients cannot depend on the solution u or its gradient.
Version History
Introduced in R2016a
See Also
applyBoundaryCondition | solvepde | specifyCoefficients | PDEModel
Topics
“Eigenvalues and Eigenmodes of L-Shaped Membrane” on page 3-353
“Eigenvalues and Eigenmodes of Square” on page 3-364
“Solve Problems Using PDEModel Objects” on page 2-3
5-1318
specifyCoefficients
specifyCoefficients
Package: pde
Syntax
specifyCoefficients(model,m=m,d=d,c=c,a=a,f=f)
specifyCoefficients(model,m=m,d=d,c=c,a=a,f=f,RegionType=RegionID)
CA = specifyCoefficients( ___ )
Description
specifyCoefficients(model,m=m,d=d,c=c,a=a,f=f) defines the PDE coefficients and
includes them in model. You must specify coefficients: m, d, c, a, and f. This syntax applies
coefficients to the entire geometry.
specifyCoefficients(model,m=m,d=d,c=c,a=a,f=f,RegionType=RegionID) assigns
coefficients for a specified geometry region.
Examples
∂2 u ∂u
m +d − ∇ ⋅ c ∇u + au = f .
∂t 2 ∂t
Specify zero Dirichlet boundary conditions, mesh the model, and solve the PDE.
5-1319
5 Functions
applyBoundaryCondition(model,"dirichlet", ...
"Edge",1:model.Geometry.NumEdges, ...
"u",0);
generateMesh(model,"Hmax",0.25);
results = solvepde(model);
Specify coefficients for Poisson's equation in 3-D with a nonconstant source term, and obtain the
coefficient object.
The equation coefficients are m = 0, d = 0, c = 1, a = 0. For the nonconstant source term, take
f = y2tanh z /1000.
f = @(location,state)location.y.^2.*tanh(location.z)/1000;
5-1320
specifyCoefficients
"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);
5-1321
5 Functions
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])
Set the c coefficient to 1 in all domains, but the f coefficient to 1 in subdomain 1, 5 in subdomain 2,
and -8 in subdomain 3. Set all other coefficients to 0.
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-1322
specifyCoefficients
Perform transient analysis of a simple cantilever beam with and without damping. To include damping
in the analysis, specify nonzero m and d coefficients.
Create a geometry representing a cantilever beam. The beam is 5 inches long and 0.1 inch thick.
height = 0.1;
width = 5;
gm = [3;4;0;width;width;0;0;0;height;height];
g = decsg(gm,'S1',('S1')');
Create a PDEModel object with two independent variables, and include a geometry in the model.
model = createpde(2);
geometryFromEdges(model,g);
pdegplot(model,EdgeLabels="on")
5-1323
5 Functions
applyBoundaryCondition(model,"dirichlet",Edge=4,u=[0,0]);
Specify Young's modulus, Poisson's ratio, and the mass density of the beam assuming that it is made
of steel.
E = 3.0e7;
nu = 0.3;
rho = 0.3/386;
Specify the PDE coefficients for the undamped model by setting the d coefficient to 0.
G = E/(2.*(1+nu));
mu = 2.0*G*nu/(1-nu);
specifyCoefficients(model, ...
m=rho, ...
d=0, ...
c=[2*G+mu;0;G;0;G;mu;0;G;0;2*G+mu], ...
a=0, ...
f=[0;0]);
−4 2
Set the initial displacement to 0; 10 x and the initial velocity to (0; 0).
setInitialConditions(model,@(location) location.x.^2.*[0;0.0001],[0;0]);
5-1324
specifyCoefficients
generateMesh(model);
tlist = 0:0.25/1000:0.25;
tres = solvepde(model,tlist);
uu = tres.NodalSolution;
utip = uu(2,2,:);
plot(tlist,utip(:))
fem = assembleFEMatrices(model);
Now specify the coefficients for the beam model with Rayleigh damping. The d coefficient represents
the damping matrix. The d coefficient is a linear combination of the mass matrix fem.M and the
stiffness matrix fem.K.
alpha = 10;
beta = 0;
dampmat = alpha*fem.M + beta*fem.K;
specifyCoefficients(model, ...
m=rho, ...
d=dampmat, ...
c=[2*G+mu;0;G;0;G;mu;0;G;0;2*G+mu], ...
a=0, ...
f=[0;0]);
5-1325
5 Functions
tres = solvepde(model,tlist);
uu = tres.NodalSolution;
utip = uu(2,2,:);
plot(tlist,utip(:))
Input Arguments
model — PDE model
PDEModel object
Second-order time derivative 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-106.
Specify 0 on the entire geometry if the term is not part of your problem. If this coefficient is zero in
one subdomain of the geometry, it must be zero on the entire geometry.
5-1326
specifyCoefficients
Example: specifyCoefficients("m",@mcoef,"d",0,"c",1,"a",0,"f",1,"Face",1:4)
Data Types: double | function_handle
Complex Number Support: Yes
First-order time derivative 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-106.
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-1329.
Specify 0 on the entire geometry if the term is not part of your problem. If this coefficient is zero in
one subdomain of the geometry, it must be zero on the entire geometry.
Example: specifyCoefficients("m",0,"d",@dcoef,"c",1,"a",0,"f",1,"Face",1:4)
Data Types: double | function_handle
Complex Number Support: Yes
Second-order space derivative 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 “c Coefficient
for specifyCoefficients” on page 2-91.
This coefficient must not be zero in one subdomain of the geometry while nonzero in another
subdomain.
Example: specifyCoefficients("m",0,"d",0,"c",@ccoef,"a",0,"f",1,"Face",1:4)
Data Types: double | function_handle
Complex Number Support: Yes
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-106.
Specify 0 if the term is not part of your problem. This coefficient can be zero in one subdomain and
nonzero in another.
Example: specifyCoefficients("m",0,"d",0,"c",1,"a",@acoef,"f",1,"Face",1:4)
Data Types: double | function_handle
Complex Number Support: Yes
f — Source coefficient
scalar | column vector | function handle
5-1327
5 Functions
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-89.
Specify 0 if the term is not part of your problem. This coefficient can be zero in one subdomain and
nonzero in another.
Example: specifyCoefficients("m",0,"d",0,"c",1,"a",0,"f",@fcoeff,"Face",1:4)
Data Types: double | function_handle
Complex Number Support: Yes
Geometric region ID, specified as a positive integer or vector of positive integers. Find the region IDs
by using pdegplot.
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
More About
PDE Coefficients
∂2 u ∂u
m +d − ∇ · c ∇u + au = f
∂t2 ∂t
− ∇ · c ∇u + au = λdu
or
2
− ∇ · c ∇u + au = λ mu
5-1328
specifyCoefficients
The d coefficient takes a special matrix form when m is nonzero. You must specify d as a matrix of a
particular size, not as a function handle.
In the case of nonzero m, the d coefficient represents a damping matrix. To specify d, perform these
two steps:
1 Assemble finite element matrices for the PDE problem with your original coefficients and d = 0
by calling assembleFEMatrices. Use the default "none" method for assembleFEMatrices.
model = createpde();
geometryFromEdges(model,@lshapeg);
generateMesh(model,Hmax=0.25);
specifyCoefficients(model,m=1,d=0,c=1,a=0,f=0,Face=1);
specifyCoefficients(model,m=1,d=0,c=1,a=0,f=2,Face=2);
specifyCoefficients(model,m=1,d=0,c=1,a=0,f=-8,Face=3);
results = assembleFEMatrices(model);
2 Define the d coefficient as a matrix of size results.M. Generally, d is either proportional to
results.M or is a linear combination of results.M and results.K.
specifyCoefficients(model,m=1,d=0*results.M,c=1,a=0,f=0,Face=1);
specifyCoefficients(model,m=1,d=1*results.M, ... % nonzero d
c=1,a=0,f=2,Face=2);
specifyCoefficients(model,m=1,d=0*results.M,c=1,a=0,f=-8,Face=3);
For an example with nonzero m and d coefficients, see “Damped Cantilever Beam” on page 5-1323.
Tips
• For eigenvalue equations, the coefficients cannot depend on the solution u or its gradient.
• You can transform a partial differential equation into the required form by using Symbolic Math
Toolbox. The pdeCoefficients function converts a PDE into the required form and extracts the
coefficients into a structure that can be used by specifyCoefficients.
The pdeCoefficients function also can return a structure of symbolic expressions, in which
case you need to use pdeCoefficientsToDouble to convert these expressions to double
format before passing them to specifyCoefficients.
Version History
Introduced in R2016a
See Also
findCoefficients | PDEModel | pdeCoefficients | pdeCoefficientsToDouble
Topics
“m, d, or a Coefficient for specifyCoefficients” on page 2-106
“c Coefficient for specifyCoefficients” on page 2-91
“f Coefficient for specifyCoefficients” on page 2-89
“Specify Nonconstant PDE Coefficients” on page 2-145
“Solve Problems Using PDEModel Objects” on page 2-3
5-1329
5 Functions
5-1330
ModalStructuralResults
ModalStructuralResults
Modal structural 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 an FEStruct object in the
ModeShapes property. The properties of this object contain the components of the displacement at
the nodal locations.
You can use a ModalStructuralResults object to approximate solutions for transient dynamics
problems. For details, see solve.
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 an FEStruct object. The properties of this
object contain components of modal displacement at nodal locations.
Finite element mesh, returned as a FEMesh object. For details, see FEMesh.
5-1331
5 Functions
Examples
Solution to Modal Analysis Structural Model
Find the fundamental (lowest) mode of a 2-D cantilevered beam, assuming prevalence of the plane-
stress condition.
Specify 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);
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 ×
5-1332
ModalStructuralResults
0.0013
0.0079
0.0222
0.0433
0.0711
0.0983
0.1055
0.1462
0.1930
0.2455
⋮
modalresults.ModeShapes
ans =
FEStruct with properties:
pdeplot(modalresults.Mesh,XYData=modalresults.ModeShapes.uy(:,1))
title(['First Mode with Frequency ', ...
num2str(modalresults.NaturalFrequencies(1)/(2*pi)),' Hz'])
axis equal
5-1333
5 Functions
Version History
Introduced in R2018a
See Also
Functions
solve
Objects
StaticStructuralResults | TransientStructuralResults |
FrequencyStructuralResults
5-1334
FrequencyStructuralResults
FrequencyStructuralResults
Frequency response structural solution and derived quantities
Description
A FrequencyStructuralResults 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 FEStruct objects in the Displacement, Velocity, and Acceleration properties. The
properties of these objects 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.
For a frequency response model with damping, the results are complex. Use functions such as abs
and angle to obtain real-valued results, such as the magnitude and phase. See “Solution to
Frequency Response Structural Model with Damping” on page 5-1336.
Creation
Solve a frequency response problem by using the solve function. This function returns a frequency
response structural solution as a FrequencyStructuralResults object.
Properties
Displacement — Displacement values at nodes
FEStruct object
Displacement values at the nodes, returned as an FEStruct object. The properties of this object
contain the components of the displacement at the nodal locations.
5-1335
5 Functions
Velocity values at the nodes, returned as an FEStruct object. The properties of this object contain
the components of the velocity at the nodal locations.
Acceleration values at the nodes, returned as an FEStruct object. The properties of this object
contain the components of the acceleration at the nodal locations.
Solution frequencies, returned as a real vector. SolutionFrequencies is the same as the flist
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
evaluateStrain Evaluate strain for dynamic structural analysis problem
evaluateVonMisesStress Evaluate von Mises stress for dynamic structural analysis problem
evaluateReaction Evaluate reaction forces on boundary
evaluatePrincipalStress Evaluate principal stress at nodal locations
evaluatePrincipalStrain Evaluate principal strain at nodal locations
interpolateDisplacement Interpolate displacement at arbitrary spatial locations
interpolateVelocity Interpolate velocity at arbitrary spatial locations for all time or
frequency steps for dynamic structural model
interpolateAcceleration Interpolate acceleration at arbitrary spatial locations for all time or
frequency steps for dynamic structural model
interpolateStress Interpolate stress at arbitrary spatial locations
interpolateStrain Interpolate strain at arbitrary spatial locations
interpolateVonMisesStress Interpolate von Mises stress at arbitrary spatial locations
Examples
Solve a frequency response problem with damping. The resulting displacement values are complex.
To obtain the magnitude and phase of displacement, use the abs and angle functions, respectively.
To speed up computations, solve the model using the results of modal analysis.
5-1336
FrequencyStructuralResults
Modal Analysis
modelM = createpde("structural","modal-solid");
gm = multicuboid(10,10,0.025);
modelM.Geometry = gm;
Generate a mesh.
msh = generateMesh(modelM);
Specify Young's modulus, Poisson's ratio, and the mass density of the material.
structuralProperties(modelM,"YoungsModulus",2E11, ...
"PoissonsRatio",0.3, ...
"MassDensity",8000);
Identify faces for applying boundary constraints and loads by plotting the geometry with the face and
edge labels.
pdegplot(gm,"FaceLabels","on","FaceAlpha",0.5)
figure
pdegplot(gm,"EdgeLabels","on","FaceAlpha",0.5)
5-1337
5 Functions
Specify constraints on the sides of the plate (faces 3, 4, 5, and 6) to prevent rigid body motions.
structuralBC(modelM,"Face",[3,4,5,6],"Constraint","fixed");
Solve the problem for the frequency range from -Inf to 12*pi.
Rm = solve(modelM,"FrequencyRange",[-Inf,12*pi]);
modelFR = createpde("structural","frequency-solid");
Use the same geometry and mesh as you used for the modal analysis.
modelFR.Geometry = gm;
modelFR.Mesh = msh;
Specify the same values for Young's modulus, Poisson's ratio, and the mass density of the material.
structuralProperties(modelFR,"YoungsModulus",2E11, ...
"PoissonsRatio",0.3, ...
"MassDensity",8000);
Specify the same constraints on the sides of the plate to prevent rigid body modes.
structuralBC(modelFR,"Face",[3,4,5,6],"Constraint","fixed");
5-1338
FrequencyStructuralResults
Specify the pressure loading on top of the plate (face 2) to model an ideal impulse excitation. In the
frequency domain, this pressure pulse is uniformly distributed across all frequencies.
structuralBoundaryLoad(modelFR,"Face",2,"Pressure",1E2);
flist = [0,1,1.5,linspace(2,3,100),3.5,4,5,6]*2*pi;
RfrModalU = solve(modelFR,flist,"ModalResults",Rm);
Now, solve the model with damping equal to 2% of critical damping for all modes.
structuralDamping(modelFR,"Zeta",0.02);
RfrModalAll = solve(modelFR,flist,"ModalResults",Rm);
Solve the same model with frequency-dependent damping. In this example, use the solution
frequencies from flist and damping values between 1% and 10% of critical damping.
omega = flist;
zeta = linspace(0.01,0.1,length(omega));
zetaW = @(omegaMode) interp1(omega,zeta,omegaMode);
structuralDamping(modelFR,"Zeta",zetaW);
RfrModalFD = solve(modelFR,flist,"ModalResults",Rm);
Interpolate the displacement at the center of the top surface of the plate for all three cases.
iDispU = interpolateDisplacement(RfrModalU,[0;0;0.025]);
iDispAll = interpolateDisplacement(RfrModalAll,[0;0;0.025]);
iDispFD = interpolateDisplacement(RfrModalFD,[0;0;0.025]);
Plot the magnitude of the displacement. Zoom in on the frequencies around the first mode.
figure
hold on
plot(RfrModalU.SolutionFrequencies,abs(iDispU.Magnitude));
plot(RfrModalAll.SolutionFrequencies,abs(iDispAll.Magnitude));
plot(RfrModalFD.SolutionFrequencies,abs(iDispFD.Magnitude));
title("Magnitude")
xlim([10 25])
ylim([0 0.5])
5-1339
5 Functions
figure
hold on
plot(RfrModalU.SolutionFrequencies,angle(iDispU.Magnitude));
plot(RfrModalAll.SolutionFrequencies,angle(iDispAll.Magnitude));
plot(RfrModalFD.SolutionFrequencies,angle(iDispFD.Magnitude));
title("Phase")
5-1340
FrequencyStructuralResults
Version History
Introduced in R2019b
See Also
Functions
solve | evaluateStress | evaluateStrain | evaluateVonMisesStress | evaluateReaction
| evaluatePrincipalStress | evaluatePrincipalStrain | interpolateDisplacement |
interpolateVelocity | interpolateAcceleration | interpolateStress |
interpolateStrain | interpolateVonMisesStress
Objects
femodel | StructuralModel | StaticStructuralResults | ModalStructuralResults |
TransientStructuralResults
5-1341
5 Functions
StaticStructuralResults
Static structural solution and 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 an FEStruct object in the
Displacement property. The properties of this object contain components of displacement at nodal
locations.
Stress and strain values at the nodes appear as FEStruct objects 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.
Properties
Displacement — Displacement values at nodes
FEStruct object
Displacement values at the nodes, returned as an FEStruct object. The properties of this object
contain components of displacement at nodal locations.
Stress values at the nodes, returned as an FEStruct object. The properties of this object contain
components of stress at nodal locations.
5-1342
StaticStructuralResults
Strain values at the nodes, returned as an FEStruct object. The properties of this object contain
components of strain at nodal locations.
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
interpolateStrain Interpolate strain at arbitrary spatial locations
interpolateVonMisesStress Interpolate von Mises stress at arbitrary spatial locations
evaluateReaction Evaluate reaction forces on boundary
evaluatePrincipalStress Evaluate principal stress at nodal locations
evaluatePrincipalStrain Evaluate principal strain at nodal locations
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-1343
5 Functions
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]);
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel)
structuralresults =
StaticStructuralResults with properties:
5-1344
StaticStructuralResults
The solver finds the values of the displacement, stress, strain, and von Mises stress at the nodal
locations. To access these values, use structuralresults.Displacement,
structuralresults.Stress, and so on. The displacement, stress, and strain values at the nodal
locations are returned as FEStruct objects with the properties representing their components. Note
that properties of an FEStruct object are read-only.
structuralresults.Displacement
ans =
FEStruct with properties:
structuralresults.Stress
ans =
FEStruct with properties:
structuralresults.Strain
ans =
FEStruct with properties:
pdeplot3D(structuralmodel, ...
"ColorMapData",structuralresults.Stress.szz, ...
"Deformation",structuralresults.Displacement)
5-1345
5 Functions
Version History
Introduced in R2017b
See Also
Functions
solve | interpolateDisplacement | interpolateStress | interpolateStrain |
interpolateVonMisesStress | evaluateReaction | evaluatePrincipalStress |
evaluatePrincipalStrain
Objects
femodel | StructuralModel | FrequencyStructuralResults |
TransientStructuralResults | ModalStructuralResults
5-1346
TransientStructuralResults
TransientStructuralResults
Transient structural solution and 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 FEStruct objects in the Displacement, Velocity, and Acceleration properties. The
properties of these objects 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.
Properties
Displacement — Displacement values at nodes
FEStruct object
Displacement values at the nodes, returned as an FEStruct object. The properties of this object
contain components of displacement at nodal locations.
Velocity values at the nodes, returned as an FEStruct object. The properties of this object contain
components of velocity at nodal locations.
5-1347
5 Functions
Acceleration values at the nodes, returned as an FEStruct object. The properties of this object
contain components of acceleration at nodal locations.
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
evaluateStrain Evaluate strain for dynamic structural analysis problem
evaluateVonMisesStress Evaluate von Mises stress for dynamic structural analysis problem
evaluateReaction Evaluate reaction forces on boundary
evaluatePrincipalStress Evaluate principal stress at nodal locations
evaluatePrincipalStrain Evaluate principal strain at nodal locations
filterByIndex Access transient results for specified time steps
interpolateDisplacement Interpolate displacement at arbitrary spatial locations
interpolateVelocity Interpolate velocity at arbitrary spatial locations for all time or
frequency steps for dynamic structural model
interpolateAcceleration Interpolate acceleration at arbitrary spatial locations for all time or
frequency steps for dynamic structural model
interpolateStress Interpolate stress at arbitrary spatial locations
interpolateStrain Interpolate strain at arbitrary spatial locations
interpolateVonMisesStress Interpolate von Mises stress at arbitrary spatial locations
Examples
Solution to Transient Structural Model
Solve for the 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.
5-1348
TransientStructuralResults
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 at the center.
figure
pdegplot(structuralmodel,"FaceLabels","on","FaceAlpha",0.25)
axis([-0.2 0.2 -0.2 0.2 -0.1 0.1])
5-1349
5 Functions
Specify Young's modulus, Poisson's ratio, and the 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);
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);
5-1350
TransientStructuralResults
The solver finds the values of the displacement, velocity, and acceleration at the nodal locations. To
access these values, use structuralresults.Displacement, structuralresults.Velocity,
and so on. The displacement, velocity, and acceleration values are returned as FEStruct objects with
the properties representing their components. Note that properties of an FEStruct object are read-
only.
structuralresults.Displacement
ans =
FEStruct with properties:
structuralresults.Velocity
ans =
FEStruct with properties:
structuralresults.Acceleration
ans =
FEStruct with properties:
Version History
Introduced in R2018a
See Also
Functions
solve | evaluateStress | evaluateStrain | evaluateVonMisesStress | evaluateReaction
| evaluatePrincipalStress | evaluatePrincipalStrain | interpolateDisplacement |
interpolateVelocity | interpolateAcceleration | interpolateStress |
interpolateStrain | interpolateVonMisesStress
Objects
femodel | StructuralModel | StaticStructuralResults | ModalStructuralResults |
FrequencyStructuralResults
5-1351
5 Functions
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,"RDisplacement",
RDval,"ZDisplacement",ZDval)
structuralBC(structuralmodel,RegionType,RegionID,"XDisplacement",XDval,
Name,Value)
structuralBC(structuralmodel,RegionType,RegionID,"Constraint","multipoint")
structuralBC( ___ ,"Reference",Coords)
structuralBC( ___ ,"Reference",Coords,"Radius",R)
bc = structuralBC( ___ )
Description
Standard Boundary Constraints and Displacements
Avoid using "symmetric" for transient and modal analysis, since the symmetric constraint can
prevent the participation of some structural modes.
structuralBC(structuralmodel,RegionType,RegionID,"Displacement",Dval) enforces
displacement on the boundary of type RegionType with RegionID ID numbers.
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,"RDisplacement",
RDval,"ZDisplacement",ZDval) specifies the r- and z-components of the enforced displacement
for an axisymmetric model. The radial component (r-component) must be zero on the axis of rotation.
5-1352
structuralBC
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. You can also specify the form and duration of the other components of the
displacement as follows:
structuralBC(structuralmodel,RegionType,RegionID,"Constraint","multipoint")
sets the multipoint constraint using all degrees of freedom on the combination of geometric regions
specified by RegionType and RegionID. The reference location for the constraint is the geometric
center of all nodes on the combination of all specified geometric regions.
This syntax is required if you intend to use results obtained with the model order reduction technique
in the Simscape Multibody™ Reduced Order Flexible Solid block. Simscape models expect the
connections at all joints to have six degrees of freedom, while Partial Differential Equation Toolbox
uses two or three degrees of freedom at each node. Setting a multipoint constraint ensures that all
nodes and all degrees of freedom for the specified geometric regions have a rigid constraint with the
geometric center of all specified geometric regions altogether as the reference point. The reference
location has six degrees of freedom.
For better performance, specify geometric regions with a minimal number of nodes. For example, use
a set of edges instead of using a face, and a set of vertices instead of using an edge.
structuralBC( ___ ,"Reference",Coords) specifies the reference point for the multipoint
constraint instead of using the geometric center of all specified regions as a reference point.
Use this syntax with the input arguments from the previous syntax.
structuralBC( ___ ,"Label",labeltext) adds a label for the structural boundary condition to
be used by the linearizeInput function. This function lets you pass boundary conditions to the
linearize function that extracts sparse linear models for use with Control System Toolbox.
Vectorized Evaluation for Function Handles
structuralBC( ___ ,"Vectorized","on") uses vectorized function evaluation when you pass a
function handle as an argument. If your function handle computes in a vectorized fashion, then using
this argument saves time. See “Vectorization”. For details on this evaluation, see “Nonconstant
Boundary Conditions” on page 2-131.
Use this syntax with any of the input arguments from previous syntaxes.
5-1353
5 Functions
bc = structuralBC( ___ ) returns the structural boundary condition object using 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", ...
"FaceLabels","on", ...
"FaceAlpha",0.4)
5-1354
structuralBC
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: [1 4]
Vectorized: 'off'
Boundary Loads
Force: []
SurfaceTraction: []
Pressure: []
TranslationalStiffness: []
Label: []
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: [2 5]
Vectorized: 'off'
5-1355
5 Functions
Boundary Loads
Force: []
SurfaceTraction: [3x1 double]
Pressure: []
TranslationalStiffness: []
Label: []
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-1356
structuralBC
structuralProperties(structuralModel,"YoungsModulus",74e9,...
"PoissonsRatio",0.42,...
"MassDensity",19.29e3);
structuralBodyLoad(structuralModel, ...
"GravitationalAcceleration",[0;0;-9.8]);
structuralBC(structuralModel,"Face",5,"Constraint","fixed");
Specify z-displacement on face 3 of the model. By leaving the x- and y-displacements unspecified, you
enable face 3 to move in the x- and y-directions.
structuralBC(structuralModel,"Face",3,"ZDisplacement",0.0001);
generateMesh(structuralModel);
R = solve(structuralModel);
pdeplot3D(structuralModel,"ColorMapData",R.Stress.sxx, ...
"Deformation",R.Displacement)
5-1357
5 Functions
Now specify all three displacements on the same face. Here, the z-displacement is the same, but the
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);
R = solve(structuralModel);
pdeplot3D(structuralModel,"ColorMapData",R.Stress.sxx, ...
"Deformation",R.Displacement)
5-1358
structuralBC
Analyze a spinning disk with radial compression at the hub due to press-fit. The inner radius of the
disk is 0.05, and the outer radius is 0.2. The thickness of the disk is 0.05 with an interference fit of
50E-6. For this analysis, simplify the 3-D axisymmetric model to a 2-D model.
The 2-D model is a rectangular strip whose x-dimension extends from the hub to the outer surface,
and whose y-dimension extends over the height of the disk. Create the geometry by specifying the
coordinates of the strip's four corners. For axisymmetric models, the toolbox assumes that the axis of
rotation is the vertical axis passing through r = 0, which is equivalent to x = 0.
g = decsg([3 4 0.05 0.2 0.2 0.05 -0.025 -0.025 0.025 0.025]');
5-1359
5 Functions
xlim([0 0.3])
ylim([-0.05 0.05])
structuralProperties(structuralmodel,"YoungsModulus",210e9, ...
"PoissonsRatio",0.28, ...
"MassDensity",7700);
Apply centrifugal load due to spinning of the disk. Assume that the disk is spinning at 104.7 rad/s.
structuralBodyLoad(structuralmodel,"AngularVelocity",104.7);
structuralBC(structuralmodel,"Edge",4,"RDisplacement",50e-6);
Fix axial displacement of a point on the hub to prevent rigid body motion.
structuralBC(structuralmodel,"Vertex",1,"ZDisplacement",0);
Generate a mesh.
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel);
5-1360
structuralBC
figure
pdeplot(structuralmodel, ...
"XYData",structuralresults.Displacement.ur, ...
"ColorMap","jet")
axis equal
xlim([0 0.3])
ylim([-0.05 0.05])
figure
pdeplot(structuralmodel, ...
"XYData",structuralresults.Stress.sh, ...
"ColorMap","jet")
axis equal
xlim([0 0.3])
ylim([-0.05 0.05])
5-1361
5 Functions
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-1362
structuralBC
Specify Young's modulus, Poisson's ratio, and the 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 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);
structuralmodel = createpde("structural","transient-solid");
5-1363
5 Functions
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 the 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 to the fixed end of the
beam.
structuralBC(structuralmodel,"Face",3, ...
"YDisplacement",1E-4, ...
"Frequency",50);
5-1364
structuralBC
Fix one corner of a rectangular plate to restrain all rigid body motions of the model.
model = createpde("structural","static-planestress");
length = 1;
width = 0.5;
radius = 0.1;
R1 = [3 4 -length length length -length ...
-width -width width width]';
C1 = [1 0 0 radius 0 0 0 0 0 0]';
gdm = [R1 C1];
ns = char('R1','C1');
g = decsg(gdm,'R1- C1',ns');
geometryFromEdges(model,g);
figure
pdegplot(model,"EdgeLabels","on");
axis([-1.2*length 1.2*length ...
-1.2*width 1.2*width])
5-1365
5 Functions
figure
pdegplot(model,"VertexLabels","on");
axis([-1.2*length 1.2*length ...
-1.2*width 1.2*width])
structuralProperties(model,"YoungsModulus",210E9,"PoissonsRatio",0.3);
Set the x-component of displacement on the left edge of the plate to zero to resist the applied load.
structuralBC(model,"Edge",3,"XDisplacement",0);
Apply the surface traction with a nonzero x-component on the right edge of the plate.
structuralBoundaryLoad(model,"Edge",1,"SurfaceTraction",[100000 0]);
Set the y-component of displacement at the bottom-left corner (vertex 3) to zero to restraint the rigid
body motion.
structuralBC(model,"Vertex",3,"YDisplacement",0);
Generate the mesh, using Hmax to control the mesh size. A fine mesh lets you capture the gradation
in the solution accurately.
generateMesh(model,"Hmax",radius/6);
5-1366
structuralBC
R = solve(model);
pdeplot(model,"XYData",R.Stress.sxx);
axis equal
colormap jet
title("Normal Stress Along x-Direction")
Set Multipoint Constraint and Obtain ROM Results Compatible with Simscape Multibody™
structuralmodel = createpde("structural","transient-solid");
gm = multicuboid(0.1,0.01,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,"EdgeLabels","on","FaceAlpha",0.5)
5-1367
5 Functions
Specify Young's modulus, Poisson's ratio, and the mass density of the material.
structuralProperties(structuralmodel,"YoungsModulus",70E9, ...
"PoissonsRatio",0.3, ...
"MassDensity",2700);
Generate a mesh.
generateMesh(structuralmodel);
Set the multipoint constraint on the right side of the beam. For better performance, set the constraint
on the set of edges bounding the right side of the beam instead of setting it on the entire face.
structuralBC(structuralmodel,"Edge",[4,6,9,10], ...
"Constraint","multipoint")
ans =
StructuralBC with properties:
RegionType: 'Edge'
RegionID: [4 6 9 10]
Vectorized: 'off'
5-1368
structuralBC
Constraint: "multipoint"
Radius: []
Reference: []
Label: []
Boundary Loads
Force: []
SurfaceTraction: []
Pressure: []
TranslationalStiffness: []
Label: []
Using the same approach, set the multipoint constraint on the left side of the beam.
structuralBC(structuralmodel,"Edge",[2,8,11,12], ...
"Constraint","multipoint")
ans =
StructuralBC with properties:
RegionType: 'Edge'
RegionID: [2 8 11 12]
Vectorized: 'off'
Boundary Loads
Force: []
SurfaceTraction: []
Pressure: []
TranslationalStiffness: []
Label: []
5-1369
5 Functions
Reduce the model to all modes in the frequency range [-Inf,500000] and the interface degrees of
freedom.
R = reduce(structuralmodel,"FrequencyRange",[-Inf,500000]);
Input Arguments
structuralmodel — Structural model
StructuralModel object
Structural model, specified as a StructuralModel object. The model contains the geometry, mesh,
structural properties of the material, body loads, boundary loads, and boundary conditions.
Example: structuralmodel = createpde("structural","transient-solid")
Geometric region type, specified as "Vertex", "Edge", or, for a 3-D model, "Face".
You cannot use the following geometric region types if you specify the "roller" or "symmetric"
value for the boundary constraint Cval:
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 by using
pdegplot.
Example: structuralBC(structuralmodel,"Face",[2,5],"XDisplacement",0.01)
Data Types: double
Displacement
Enforced displacement, specified as a numeric vector or function handle. A numeric vector must
contain two elements for a 2-D model (including axisymmetric models) 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 an enforced displacement vector at the
boundary coordinates provided by the solver. In case of a transient or frequency response analysis,
5-1370
structuralBC
Dval also can be a function of time or frequency, respectively. For details, see “More About” on page
5-1375.
Note that when you specify Dval for an axisymmetric model, the radial displacement on the axis of
rotation must always be zero.
Example: structuralBC(structuralmodel,"Face",[2,5],"Displacement",[0;0;0.01])
Data Types: double | function_handle
x-component of enforced displacement, specified as a number or function handle. The function must
return a row vector. Each element of this vector corresponds to the x-component value of the
enforced displacement at the boundary coordinates provided by the solver. In case of a transient or
frequency response analysis, XDval also can be a function of time or frequency, respectively. For
details, see “More About” on page 5-1375.
Example: structuralBC(structuralmodel,"Face",[2,5],"XDisplacement",0.01)
Data Types: double | function_handle
y-component of enforced displacement, specified as a number or function handle. The function must
return a row vector. Each element of this vector corresponds to the y-component value of the
enforced displacement at the boundary coordinates provided by the solver. In case of a transient or
frequency response analysis, YDval also can be a function of time or frequency, respectively. For
details, see “More About” on page 5-1375.
Example: structuralBC(structuralmodel,"Face",[2,5],"YDisplacement",0.01)
Data Types: double | function_handle
z-component of enforced displacement, specified as a number or function handle. The function must
return a row vector. Each element of this vector corresponds to the z-component value of the
enforced displacement at the boundary coordinates provided by the solver. For a transient or
frequency response analysis, ZDval also can be a function of time or frequency, respectively. For
details, see “More About” on page 5-1375.
r-component of enforced displacement, specified as a number or function handle. The function must
return a row vector. Each element of this vector corresponds to the r-component value of the
enforced displacement at the boundary coordinates provided by the solver. For a transient or
5-1371
5 Functions
frequency response analysis, RDval also can be a function of time or frequency, respectively. For
details, see “More About” on page 5-1375.
You can specify RDval only for an axisymmetric model. RDval must be zero on the axis of rotation.
Example: structuralBC(structuralmodel,"Face",[2,5],"RDisplacement",0.01)
Data Types: double | function_handle
You cannot use the "roller" and "symmetric" values with the following geometric region types:
Example: structuralBC(structuralmodel,"Face",[2,5],"Constraint","fixed")
Data Types: char | string
Reference point location for the multipoint constraint, specified as a 2-by-1 (for a 2-D geometry) or 3-
by-1 (for a 3-D geometry) numeric vector.
Example: structuralBC(structuralmodel,"Vertex",
[1,3,5:10],"Constraint","multipoint","Reference",[0;0;1])
Data Types: double
R — Radius of circle (for 2-D geometry) or sphere (for 3-D geometry) around reference
point location for multipoint constraint
positive number
Radius of a circle (for a 2-D geometry) or a sphere (for a 3-D geometry) around the reference point
location for the multipoint constraint, specified as a positive number.
Example: structuralBC(structuralmodel,"Vertex",
[1,3,5:10],"Constraint","multipoint","Reference",[0;0;1],"Radius",0.2)
Data Types: double
Label for the structural boundary condition, specified as a character vector or a string.
Data Types: char | string
Use one or more name-value pair arguments to specify the form and duration of the time-varying
value of a component of displacement. Specify the displacement value using one of the following
5-1372
structuralBC
arguments: XDval, YDval, ZDval, or RDval. You cannot use these name-value pair arguments to
specify more than one time-varying component or to specify the Dval value.
You can model rectangular, triangular, and trapezoidal displacement pulses. If the start time is 0, you
do not need to specify it.
You can model a harmonic displacement by specifying its frequency and initial phase. If the initial
phase is 0, you do not need to specify it.
5-1373
5 Functions
Example: structuralBC(structuralmodel,"Face",
[2,5],"XDisplacement",0.01,"RiseTime",0.5,"FallTime",0.5,"EndTime",3)
Start time for the displacement component, specified as 0 or a positive number. Specify this argument
only for transient structural models.
Example: 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.
Example: 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.
Example: structuralBC(structuralmodel,"Face",
[2,5],"XDisplacement",0.01,"RiseTime",0.5,"FallTime",0.5,"EndTime",3)
5-1374
structuralBC
Fall time for the displacement component, specified as a positive number. Specify this argument only
for transient structural models.
Example: structuralBC(structuralmodel,"Face",
[2,5],"XDisplacement",0.01,"RiseTime",0.5,"FallTime",0.5,"EndTime",3)
Data Types: double
Harmonic Displacement
Output Arguments
bc — Handle to boundary condition
StructuralBC object
Handle to the boundary condition, returned as a StructuralBC object. See StructuralBC Properties.
More About
Degrees of Freedom (DoFs)
In Partial Differential Equation Toolbox, each node of a 2-D or 3-D geometry has two or three degrees
of freedom (DoFs), respectively. DoFs correspond to translational displacements. If the number of
mesh points in a model is NumNodes, then the toolbox assigns the IDs to the degrees of freedom as
follows:
5-1375
5 Functions
Use a function handle to specify the following structural parameters when they depend on space and,
depending of the type of structural analysis, either time or frequency:
For example, use function handles to specify the pressure load, x-component of the enforced
displacement, and the initial displacement for this model.
structuralBoundaryLoad(model,"Face",12, ...
"Pressure",@myfunPressure)
structuralBC(model,"Face",2, ...
"XDisplacement",@myfunBC)
structuralIC(model,"Face",12, ...
"Displacement",@myfunIC)
For all parameters, except the initial displacement and velocity, the function must be of the form:
function structuralVal = myfun(location,state)
For the initial displacement and velocity the function must be of the form:
function structuralVal = myfun(location)
The solver computes and populates the data in the location and state structure arrays and passes
this data to your function. You can define your function so that its output depends on this data. You
can use any names instead of location and state, but the function must have exactly two
arguments (or one argument if the function specifies the initial displacement or initial velocity).
Furthermore, for boundary conditions, the solver passes these data in the location structure:
5-1376
structuralBC
Boundary constraints and loads get these data from the solver:
If a parameter represents a vector value, such as surface traction, spring stiffness, force, or
displacement, your 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 parameter value (a vector) at the
boundary coordinates provided by the solver.
To use additional arguments in your function, wrap your function (that takes additional arguments)
with an anonymous function that takes only the location and state arguments. For example:
structuralVal = ...
@(location,state) myfunWithAdditionalArgs(location,state,arg1,arg2...)
structuralBC(model,"Face",2,"XDisplacement",structuralVal)
structuralVal = ...
@(location) myfunWithAdditionalArgs(location,arg1,arg2...)
structuralIC(model,"Face",2,"Displacement",structuralVal)
Tips
• Restrain all rigid body motions by specifying as many boundary conditions as needed. If you do
not restrain all rigid body motions, 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.
5-1377
5 Functions
Version History
Introduced in R2017b
R2021b: Label to extract sparse linear models for use with Control System Toolbox
Now you can add a label for structural boundary conditions to be used by the linearizeInput
function. This function lets you pass structural boundary conditions to the linearize function that
extracts sparse linear models for use with Control System Toolbox.
You can now specify an enforced displacement for a structural axisymmetric model.
You can now use addVertex to create new vertices at any points on boundaries of a 2-D or 3-D
geometry represented by a DiscreteGeometry object. Then set concentrated boundary constraints
at these vertices.
You can now set a multipoint constraint, which ensures that all nodes and all degrees of freedom have
a rigid constraint with the geometric center of all specified geometric regions together as the
reference point. The reference location has six degrees of freedom.
You can now specify an enforced displacement and the 'free' and 'fixed' boundary constraints
on vertices and edges for both 2-D and 3-D models. The previous versions of this function let you
specify the displacement and boundary constraints values only on edges for 2-D models and faces on
3-D models.
You can now specify time-dependent boundary conditions by using function handles or specify the
form and duration of x-, y-, or z-component of the enforced displacement and the frequency and phase
of sinusoidal displacement.
See Also
StructuralModel | structuralProperties | structuralDamping | structuralBodyLoad |
structuralBoundaryLoad | structuralSEInterface | reduce | solve |
reconstructSolution
5-1378
StructuralBC Properties
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, specified as 'Face' for a 3-D geometry or 'Edge' for a 2-D geometry.
Data Types: char | string
Geometric region ID, specified as a vector of positive integers. Find the region IDs by using
pdegplot with 'FaceLabels' (3-D) or 'EdgeLabels' (2-D) set to 'on'.
Data Types: double
Vectorized function evaluation, specified as 'off' or 'on'. This evaluation applies when you pass a
function handle as an argument. To save time in the function handle evaluation, specify 'on',
assuming that your function handle computes in a vectorized fashion. See “Vectorization”. For details
on this evaluation, see “Nonconstant Boundary Conditions” on page 2-131.
Data Types: char | string
Enforced displacement, specified 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 enforced displacement vector at the boundary coordinates provided by the
solver.
5-1379
5 Functions
x-component of the enforced displacement, specified as a number or function handle. The function
must return a row vector. Each column of the vector must correspond to the value of the x-component
of the enforced displacement at the boundary coordinates provided by the solver.
For axisymmetric models, this property contains the radial component (r-component) of the enforced
displacement.
Data Types: double | function_handle
y-component of the enforced displacement, specified as a number or function handle. The function
must return a row vector. Each column of the vector must correspond to the value of the y-component
of the enforced displacement at the boundary coordinates provided by the solver.
For axisymmetric models, this property contains the axial component (z-component) of the enforced
displacement.
Data Types: double | function_handle
z-component of the enforced displacement, specified as a number or function handle. The function
must return a row vector. Each column of the vector must correspond to the value of the z-component
of the enforced displacement at the boundary coordinates provided by the solver.
Data Types: double | function_handle
Radius — Radius of circle (for 2-D geometry) or sphere (for 3-D geometry) around
reference point location for multipoint constraint
positive number
Radius of a circle (for a 2-D geometry) or a sphere (for a 3-D geometry) around the reference point
location for the multipoint constraint, specified as a positive number.
Data Types: double
Reference point location for the multipoint constraint, specified as a 2-by-1 (for a 2-D geometry) or 3-
by-1 (for a 3-D geometry) numeric vector.
5-1380
StructuralBC Properties
Normal and tangential distributed forces on the boundary (in the global Cartesian coordinates
system), specified 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, specified as a number or function handle. The function must return
a row vector in which each column corresponds to the 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,
specified 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 model. Each column of this matrix corresponds to the
stiffness vector at the boundary coordinates provided by the solver.
Data Types: double | function_handle
Time Variation of Force, Pressure, or Enforced Displacement
StartTime — Start time for displacement component, pressure, or concentrated force load
nonnegative number
Start time for a displacement component, the pressure, or the concentrated force load, specified as a
nonnegative number.
Data Types: double
EndTime — End time for displacement component, pressure, or concentrated force load
nonnegative number
End time for a displacement component, the pressure, or the concentrated force load, specified as a
nonnegative number.
5-1381
5 Functions
RiseTime — Rise time for displacement component, pressure, or concentrated force load
nonnegative number
Rise time for a displacement component, the pressure, or the concentrated force load, specified as a
nonnegative number.
Data Types: double
FallTime — Fall time for displacement component, pressure, or concentrated force load
nonnegative number
Fall time for a displacement component, the pressure, or the concentrated force load, specified as a
nonnegative number.
Data Types: double
Phase of a sinusoidal displacement component, the sinusoidal pressure, or the concentrated force,
specified as a nonnegative number, in radians per unit of time.
Data Types: double
Version History
Introduced in R2017b
See Also
findStructuralBC | structuralBC | structuralBoundaryLoad | structuralSEInterface |
StructuralSEIAssignment Properties
5-1382
structuralIC
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.
structuralIC( ___ RegionType,RegionID) sets initial displacement and velocity for a particular
geometry region using the arguments from the previous syntax.
struct_ic = structuralIC( ___ ) returns a handle to the structural initial conditions object.
Examples
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-1383
5 Functions
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]
structuralIC(structuralmodel,"Face",2,"Velocity",[0;60;0])
ans =
GeometricStructuralICs with properties:
RegionType: 'Face'
RegionID: 2
InitialDisplacement: []
InitialVelocity: [3x1 double]
5-1384
structuralIC
structuralmodel = createpde("structural","transient-solid");
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)
structuralIC(structuralmodel,"Displacement",[0;0;0])
ans =
GeometricStructuralICs with properties:
RegionType: 'Cell'
RegionID: 1
InitialDisplacement: [3x1 double]
5-1385
5 Functions
InitialVelocity: []
Now change the initial displacement in the z-direction on face 2 to a function of the coordinates x and
y:
0
u0 = 0
x2 + y2
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.
gm = multicuboid(0.06,0.005,0.01);
staticmodel.Geometry = gm;
pdegplot(staticmodel,"FaceLabels","on","FaceAlpha",0.5)
view(50,20)
5-1386
structuralIC
Generate a mesh.
5-1387
5 Functions
generateMesh(dynamicmodel,"Hmax",0.02);
structuralIC(dynamicmodel,Rstatic)
ans =
NodalStructuralICs with properties:
Input Arguments
structuralmodel — Transient structural model
StructuralModel object
Transient structural model, specified as a StructuralModel object. The model contains the
geometry, mesh, structural properties of the material, body loads, boundary loads, boundary
conditions, and initial conditions.
Example: structuralmodel = createpde("structural","transient-solid")
u0 — Initial displacement
numeric vector | function handle
Initial displacement, 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 displacement.
Use a function handle to specify spatially varying initial displacement. 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. For details, see
“More About” on page 5-1390.
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.
Use a function handle to specify spatially varying 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. For details, see “More
About” on page 5-1390.
Example: structuralIC(structuralmodel,"Face",[2,5],"Displacement",
[0;0;0.01],"Velocity",[0;60;0])
Data Types: double | function_handle
5-1388
structuralIC
When you apply multiple initial condition assignments, the solver uses these precedence rules for
determining the initial condition.
• 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 by using
pdegplot.
Example: structuralIC(structuralmodel,"Face",[2,5],"Displacement",
[0;0;0.01],"Velocity",[0;60;0])
Data Types: double
iT — Time index
positive integer
Output Arguments
struct_ic — Handle to initial conditions
GeometricStructuralICs object | NodalStructuralICs object
5-1389
5 Functions
structuralIC associates the structural initial condition with the geometric region in the case of a
geometric assignment, or the nodes in the case of a results-based assignment.
More About
Specifying Nonconstant Parameters of a Structural Model
Use a function handle to specify the following structural parameters when they depend on space and,
depending of the type of structural analysis, either time or frequency:
For example, use function handles to specify the pressure load, x-component of the enforced
displacement, and the initial displacement for this model.
structuralBoundaryLoad(model,"Face",12, ...
"Pressure",@myfunPressure)
structuralBC(model,"Face",2, ...
"XDisplacement",@myfunBC)
structuralIC(model,"Face",12, ...
"Displacement",@myfunIC)
For all parameters, except the initial displacement and velocity, the function must be of the form:
For the initial displacement and velocity the function must be of the form:
The solver computes and populates the data in the location and state structure arrays and passes
this data to your function. You can define your function so that its output depends on this data. You
can use any names instead of location and state, but the function must have exactly two
arguments (or one argument if the function specifies the initial displacement or initial velocity).
Furthermore, for boundary conditions, the solver passes these data in the location structure:
5-1390
structuralIC
Boundary constraints and loads get these data from the solver:
If a parameter represents a vector value, such as surface traction, spring stiffness, force, or
displacement, your 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 parameter value (a vector) at the
boundary coordinates provided by the solver.
To use additional arguments in your function, wrap your function (that takes additional arguments)
with an anonymous function that takes only the location and state arguments. For example:
structuralVal = ...
@(location,state) myfunWithAdditionalArgs(location,state,arg1,arg2...)
structuralBC(model,"Face",2,"XDisplacement",structuralVal)
structuralVal = ...
@(location) myfunWithAdditionalArgs(location,arg1,arg2...)
structuralIC(model,"Face",2,"Displacement",structuralVal)
Version History
Introduced in R2018a
5-1391
5 Functions
See Also
StructuralModel | structuralProperties | structuralDamping | structuralBodyLoad |
structuralBoundaryLoad | structuralBC | structuralSEInterface | solve | reduce |
findStructuralIC | GeometricStructuralICs Properties | NodalStructuralICs Properties
5-1392
structuralDamping
structuralDamping
Specify damping parameters for transient or frequency response structural model
Syntax
structuralDamping(structuralmodel,"Alpha",a,"Beta",b)
structuralDamping(structuralmodel,"Zeta",z)
Description
structuralDamping(structuralmodel,"Alpha",a,"Beta",b) specifies proportional
(Rayleigh) damping parameters a and b for a structuralmodel object.
For a frequency response model with damping, the results are complex. Use the abs and angle
functions to obtain real-valued magnitude and phase, respectively.
damping = structuralDamping( ___ ) returns the damping parameters object, using any of the
previous input syntaxes.
Examples
structuralModel = createpde("structural","transient-solid");
gm = importGeometry(structuralModel,"SquareBeam.stl");
pdegplot(structuralModel,"FaceAlpha",0.5)
5-1393
5 Functions
structuralProperties(structuralModel,"YoungsModulus",210E9,...
"PoissonsRatio",0.3,...
"MassDensity",7800);
structuralDamping(structuralModel,"Alpha",10,"Beta",2)
ans =
StructuralDampingAssignment with properties:
RegionType: 'Cell'
RegionID: 1
DampingModel: "proportional"
Alpha: 10
Beta: 2
Zeta: []
5-1394
structuralDamping
Solve a frequency response problem with damping. The resulting displacement values are complex.
To obtain the magnitude and phase of displacement, use the abs and angle functions, respectively.
To speed up computations, solve the model using the results of modal analysis.
Modal Analysis
modelM = createpde("structural","modal-solid");
gm = multicuboid(10,10,0.025);
modelM.Geometry = gm;
Generate a mesh.
msh = generateMesh(modelM);
Specify Young's modulus, Poisson's ratio, and the mass density of the material.
structuralProperties(modelM,"YoungsModulus",2E11, ...
"PoissonsRatio",0.3, ...
"MassDensity",8000);
Identify faces for applying boundary constraints and loads by plotting the geometry with the face and
edge labels.
pdegplot(gm,"FaceLabels","on","FaceAlpha",0.5)
5-1395
5 Functions
figure
pdegplot(gm,"EdgeLabels","on","FaceAlpha",0.5)
5-1396
structuralDamping
Specify constraints on the sides of the plate (faces 3, 4, 5, and 6) to prevent rigid body motions.
structuralBC(modelM,"Face",[3,4,5,6],"Constraint","fixed");
Solve the problem for the frequency range from -Inf to 12*pi.
Rm = solve(modelM,"FrequencyRange",[-Inf,12*pi]);
modelFR = createpde("structural","frequency-solid");
Use the same geometry and mesh as you used for the modal analysis.
modelFR.Geometry = gm;
modelFR.Mesh = msh;
Specify the same values for Young's modulus, Poisson's ratio, and the mass density of the material.
structuralProperties(modelFR,"YoungsModulus",2E11, ...
"PoissonsRatio",0.3, ...
"MassDensity",8000);
Specify the same constraints on the sides of the plate to prevent rigid body modes.
structuralBC(modelFR,"Face",[3,4,5,6],"Constraint","fixed");
5-1397
5 Functions
Specify the pressure loading on top of the plate (face 2) to model an ideal impulse excitation. In the
frequency domain, this pressure pulse is uniformly distributed across all frequencies.
structuralBoundaryLoad(modelFR,"Face",2,"Pressure",1E2);
flist = [0,1,1.5,linspace(2,3,100),3.5,4,5,6]*2*pi;
RfrModalU = solve(modelFR,flist,"ModalResults",Rm);
Now, solve the model with damping equal to 2% of critical damping for all modes.
structuralDamping(modelFR,"Zeta",0.02);
RfrModalAll = solve(modelFR,flist,"ModalResults",Rm);
Solve the same model with frequency-dependent damping. In this example, use the solution
frequencies from flist and damping values between 1% and 10% of critical damping.
omega = flist;
zeta = linspace(0.01,0.1,length(omega));
zetaW = @(omegaMode) interp1(omega,zeta,omegaMode);
structuralDamping(modelFR,"Zeta",zetaW);
RfrModalFD = solve(modelFR,flist,"ModalResults",Rm);
Interpolate the displacement at the center of the top surface of the plate for all three cases.
iDispU = interpolateDisplacement(RfrModalU,[0;0;0.025]);
iDispAll = interpolateDisplacement(RfrModalAll,[0;0;0.025]);
iDispFD = interpolateDisplacement(RfrModalFD,[0;0;0.025]);
Plot the magnitude of the displacement. Zoom in on the frequencies around the first mode.
figure
hold on
plot(RfrModalU.SolutionFrequencies,abs(iDispU.Magnitude));
plot(RfrModalAll.SolutionFrequencies,abs(iDispAll.Magnitude));
plot(RfrModalFD.SolutionFrequencies,abs(iDispFD.Magnitude));
title("Magnitude")
xlim([10 25])
ylim([0 0.5])
5-1398
structuralDamping
figure
hold on
plot(RfrModalU.SolutionFrequencies,angle(iDispU.Magnitude));
plot(RfrModalAll.SolutionFrequencies,angle(iDispAll.Magnitude));
plot(RfrModalFD.SolutionFrequencies,angle(iDispFD.Magnitude));
title("Phase")
5-1399
5 Functions
Input Arguments
structuralmodel — Transient or frequency response structural model
StructuralModel object
5-1400
structuralDamping
Modal damping ratio, specified as a nonnegative number or a function handle. Use a function handle
when each mode has its own damping ratio. The function must accept a vector of natural frequencies
as an input argument and return a vector of corresponding damping ratios. It must cover the full
frequency range for all modes used for modal solution. For details, see “Modal Damping Depending
on Frequency” on page 5-1401.
Data Types: double | function_handle
Output Arguments
damping — Handle to damping parameters
StructuralDampingAssignment object
More About
Modal Damping Depending on Frequency
To use the individual value of modal damping for each mode, specify z as a function of frequency.
function z = dampingFcn(omega)
Typically, the damping ratio function is a linear interpolation of frequency versus the modal damping
parameter:
structuralDamping(modelD,"Zeta",@(omegaMode) ...
interp1(omega,zeta,omegaMode))
Here, omega is a vector of frequencies, and zeta is a vector of corresponding damping ratio values.
Version History
Introduced in R2018a
For modal transient and modal frequency response models, specify damping as a percentage of
critical damping for a selected vibration frequency.
See Also
StructuralModel | structuralProperties | structuralBodyLoad |
structuralBoundaryLoad | structuralBC | solve | findStructuralDamping |
StructuralDampingAssignment Properties
5-1401
5 Functions
findStructuralDamping
Package: pde
Syntax
dma = findStructuralDamping(dampingModels)
Description
dma = findStructuralDamping(dampingModels) returns the damping model and its
parameters assigned to the entire structural dynamics model. The toolbox supports the proportional
(Rayleigh) damping model and the modal damping model. The parameters of the proportional
damping model are the mass and stiffness proportional damping parameters. The parameter of the
modal damping model is the modal damping ratio.
Use this function to find which damping model and parameters are currently active if you made
multiple damping assignments.
Examples
structuralModel = createpde("structural","transient-solid");
importGeometry(structuralModel,"Block.stl");
pdegplot(structuralModel,"CellLabels","on")
5-1402
findStructuralDamping
structuralDamping(structuralModel,"Beta",40);
structuralDamping(structuralModel,"Alpha",10);
Check the damping parameter assignment for structuralModel. Notice that the Beta parameter
is empty.
findStructuralDamping(structuralModel.DampingModels)
ans =
StructuralDampingAssignment with properties:
RegionType: 'Cell'
RegionID: 1
DampingModel: "proportional"
Alpha: 10
Beta: []
Zeta: []
When you specify damping parameters by calling the structuralDamping function several times,
the toolbox uses the last assignment. Specify both the mass and stiffness parameters.
structuralDamping(structuralModel,"Alpha",10,"Beta",40);
5-1403
5 Functions
findStructuralDamping(structuralModel.DampingModels)
ans =
StructuralDampingAssignment with properties:
RegionType: 'Cell'
RegionID: 1
DampingModel: "proportional"
Alpha: 10
Beta: 40
Zeta: []
Input Arguments
dampingModels — Damping model
DampingModels property of StructuralModel object
Output Arguments
dma — Damping model assignment
StructuralDampingAssignment object
Version History
Introduced in R2018a
See Also
structuralDamping | StructuralDampingAssignment Properties
5-1404
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
Region type, specified as 'Face' for a 2-D region, or 'Cell' for a 3-D region.
Data Types: char
RegionID — Region ID
positive integer
5-1405
5 Functions
Modal damping ratio, specified as a nonnegative number or a function handle. Use a function handle
when each mode has its own damping ratio. The function must accept a vector of natural frequencies
as an input argument and return a vector of corresponding damping ratios. It must cover the full
frequency range for all modes used for modal solution.
Data Types: double | function_handle
Version History
Introduced in R2018a
See Also
structuralDamping | findStructuralDamping
5-1406
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, specified as 'Face' for a 2-D region, or 'Cell' for a 3-D region.
Data Types: char | string
RegionID — Region ID
vector of positive integers
Region ID, specified as a vector of positive integers. To determine which ID corresponds to which
portion of the geometry, use the pdegplot function, setting the 'FaceLabels' name-value pair to
'on'.
Data Types: double
Mass density of the material, specified as a positive number. This property is required when modeling
gravitational effects.
5-1407
5 Functions
Coefficient of thermal expansion, specified as a real number. This argument is required for thermal
stress analysis. Thermal stress analysis requires the structural model to be static.
Data Types: double
Hysteretic damping parameter, specified as a nonnegative number. This type of damping is also called
structural damping.
Data Types: double
Version History
Introduced in R2017b
See Also
findStructuralProperties | structuralProperties
5-1408
structuralBodyLoad
structuralBodyLoad
Package: pde
Syntax
structuralBodyLoad(structuralmodel,"GravitationalAcceleration",GAval)
structuralBodyLoad(structuralmodel,"AngularVelocity",omega)
structuralBodyLoad(structuralmodel,"Temperature",Tval)
structuralBodyLoad(structuralmodel,"Temperature",Tresults)
structuralBodyLoad(structuralmodel,"Temperature",Tresults,"TimeStep",iT)
structuralBodyLoad(structuralmodel, ___ )
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.
Tip If Tval is the temperature itself, and not a change in temperature, you must specify a reference
temperature using structuralmodel.ReferenceTemperature. Otherwise, the toolbox uses the
default value (zero) for the reference temperature. For details, see StructuralModel.
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.
5-1409
5 Functions
structuralBodyLoad(structuralmodel,"GravitationalAcceleration",
[0;0;-9.8],"Temperature",300). Do not use subsequent function calls when assigning several
body loads because the toolbox uses only the last assignment.
structuralBodyLoad( ___ ,"Label",labeltext) adds a label for the structural body load to be
used by the linearizeInput function. This function lets you pass body loads to the linearize
function that extracts sparse linear models for use with Control System Toolbox.
Examples
Specify Young's modulus, Poisson's ratio, and the mass density. The mass density value is required for
modeling gravitational effects.
5-1410
structuralBodyLoad
structuralProperties(structuralModel,"YoungsModulus",210E3, ...
"PoissonsRatio",0.3, ...
"MassDensity",2.7E-6);
structuralBodyLoad(structuralModel, ...
"GravitationalAcceleration",[0;0;-9.8])
ans =
BodyLoadAssignment with properties:
RegionType: 'Cell'
RegionID: 1
GravitationalAcceleration: [3x1 double]
AngularVelocity: []
Temperature: []
TimeStep: []
Label: []
Analyze a spinning disk with radial compression at the hub due to press-fit. The inner radius of the
disk is 0.05, and the outer radius is 0.2. The thickness of the disk is 0.05 with an interference fit of
50E-6. For this analysis, simplify the 3-D axisymmetric model to a 2-D model.
structuralmodel = createpde("structural","static-axisymmetric");
The 2-D model is a rectangular strip whose x-dimension extends from the hub to the outer surface,
and whose y-dimension extends over the height of the disk. Create the geometry by specifying the
coordinates of the strip's four corners. For axisymmetric models, the toolbox assumes that the axis of
rotation is the vertical axis passing through r = 0, which is equivalent to x = 0.
geometryFromEdges(structuralmodel,g);
figure
pdegplot(structuralmodel,"EdgeLabels","on","VertexLabels","on")
xlim([0 0.3])
ylim([-0.05 0.05])
5-1411
5 Functions
structuralProperties(structuralmodel,"YoungsModulus",210e9, ...
"PoissonsRatio",0.28, ...
"MassDensity",7700);
Apply centrifugal load due to spinning of the disk. Assume that the disk is spinning at 104.7 rad/s.
structuralBodyLoad(structuralmodel,"AngularVelocity",104.7);
structuralBC(structuralmodel,"Edge",4,"RDisplacement",50e-6);
Fix axial displacement of a point on the hub to prevent rigid body motion.
structuralBC(structuralmodel,"Vertex",1,"ZDisplacement",0);
Generate a mesh.
generateMesh(structuralmodel);
structuralresults = solve(structuralmodel);
5-1412
structuralBodyLoad
figure
pdeplot(structuralmodel, ...
"XYData",structuralresults.Displacement.ur, ...
"ColorMap","jet")
axis equal
xlim([0 0.3])
ylim([-0.05 0.05])
figure
pdeplot(structuralmodel, ...
"XYData",structuralresults.Stress.sh, ...
"ColorMap","jet")
axis equal
xlim([0 0.3])
ylim([-0.05 0.05])
5-1413
5 Functions
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-1414
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
SuperelementInterfaces: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
ans =
BodyLoadAssignment with properties:
RegionType: 'Cell'
RegionID: [1 2]
5-1415
5 Functions
GravitationalAcceleration: []
AngularVelocity: []
Temperature: 300
TimeStep: []
Label: []
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)
Generate a mesh.
5-1416
structuralBodyLoad
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);
internalHeatSource(thermalmodel,10);
thermalresults = solve(thermalmodel)
thermalresults =
SteadyStateThermalResults with properties:
pdeplot3D(thermalmodel,"ColorMapData",thermalresults.Temperature)
5-1417
5 Functions
structuralmodel = createpde("structural","static-solid");
structuralmodel.Geometry = gm;
Apply the solution of the thermal model analysis as a body load for the structural model.
structuralBodyLoad(structuralmodel,"Temperature",thermalresults)
ans =
BodyLoadAssignment with properties:
RegionType: 'Cell'
RegionID: 1
GravitationalAcceleration: []
AngularVelocity: []
Temperature: [1x1 pde.SteadyStateThermalResults]
TimeStep: []
Label: []
5-1418
structuralBodyLoad
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)
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.
5-1419
5 Functions
thermalBC(thermalmodel,"Face",3,"Temperature",100);
thermalBC(thermalmodel,"Face",5,"Temperature",0);
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))])
end
5-1420
structuralBodyLoad
5-1421
5 Functions
5-1422
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);
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
5-1423
5 Functions
Static or transient structural model, specified as a StructuralModel object. The model contains the
geometry, mesh, structural properties of the material, body loads, boundary loads, and boundary
conditions.
Example: structuralmodel = createpde("structural","transient-solid")
Acceleration due to gravity, specified as a numeric vector. GAval must be specified in units consistent
with those of the geometry and material properties.
Example: structuralBodyLoad(structuralmodel,"GravitationalAcceleration",
[0;0;-9.8])
Data Types: double
Angular velocity for an axisymmetric model, specified as a positive number. omega must be specified
in units consistent with those of the geometry and material properties.
For axisymmetric models, the toolbox assumes that the axis of rotation is the vertical axis passing
through r = 0, which is equivalent to x = 0.
Example: structuralBodyLoad(structuralmodel,"AngularVelocity",2.3)
Data Types: double
Constant thermal load on a static structural model, specified as a real number. Tval must be
specified in units consistent with those of the geometry and material properties.
Example: structuralBodyLoad(structuralmodel,"Temperature",300)
Data Types: double
Thermal model solution applied as a body load on a static structural model, specified as a
SteadyStateThermalResults or TransientThermalResults object. Create Tresults by using
solve.
Example: Tresults = solve(thermalmodel);
structuralBodyLoad(structuralmodel,"Temperature",Tresults)
iT — Time index
positive integer
5-1424
structuralBodyLoad
Label for the structural body load, specified as a character vector or a string.
Data Types: char | string
Output Arguments
bodyLoad — Handle to body load
BodyLoadAssignment object
Version History
Introduced in R2017b
R2021b: Label to extract sparse linear models for use with Control System Toolbox
Now you can add a label for structural body loads to be used by the linearizeInput function. This
function lets you pass structural body loads to the linearize function that extracts sparse linear
models for use with Control System Toolbox.
You can now model the effect of a spinning axisymmetric structure by specifying a centrifugal load.
See Also
StructuralModel | structuralProperties | structuralDamping |
structuralBoundaryLoad | structuralBC | BodyLoadAssignment Properties
5-1425
5 Functions
structuralBoundaryLoad
Package: pde
Syntax
structuralBoundaryLoad(structuralmodel,RegionType,RegionID,"SurfaceTraction",
STval,"Pressure",Pval,"TranslationalStiffness",TSval)
structuralBoundaryLoad(structuralmodel,"Vertex",VertexID,"Force",Fval)
Description
structuralBoundaryLoad(structuralmodel,RegionType,RegionID,"SurfaceTraction",
STval,"Pressure",Pval,"TranslationalStiffness",TSval) specifies the surface traction,
pressure, and translational stiffness on the boundary of type RegionType with RegionID ID
numbers.
• Surface traction is determined as distributed normal and tangential forces acting on a boundary,
resolved along the global Cartesian coordinate system.
• Pressure must be specified in the direction that is normal to the boundary. A positive pressure
value acts into the boundary (for example, compression). A negative pressure value acts away
from the boundary (for example, suction).
• Translational stiffness is a distributed spring stiffness for each translational direction.
Translational stiffness is used to model an elastic foundation.
structuralBoundaryLoad does not require you to specify all three boundary loads. Depending on
your structural analysis problem, you can specify one or more boundary loads by picking the
corresponding arguments and omitting others. You can specify translational stiffness for any
structural model. To specify pressure or surface traction, structuralmodel must be a static,
transient, or frequency response model. Structural models for modal analysis cannot have pressure or
surface traction.
structuralBoundaryLoad(structuralmodel,"Vertex",VertexID,"Force",Fval) specifies
concentrated force at a vertex with the VertexID number. You can specify force only if
structuralmodel is a static, transient, or frequency response model. Structural models for modal
analysis cannot have concentrated force.
5-1426
structuralBoundaryLoad
Use this syntax with any of the input arguments from previous syntaxes.
structuralBoundaryLoad(structuralmodel,"Vertex",VertexID,"Force",Fval,
Name,Value) lets you specify the form and duration of a nonconstant concentrated force and
harmonic excitation for a transient structural model without creating a function handle.
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", ...
"FaceLabels","on", ...
"FaceAlpha",0.4)
5-1427
5 Functions
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: [1 4]
Vectorized: 'off'
5-1428
structuralBoundaryLoad
Boundary Loads
Force: []
SurfaceTraction: []
Pressure: []
TranslationalStiffness: []
Label: []
structuralBoundaryLoad(structuralModel, ...
"Face",[2,5], ...
"SurfaceTraction",[0;0;100])
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: [2 5]
Vectorized: 'off'
Boundary Loads
Force: []
SurfaceTraction: [3x1 double]
Pressure: []
TranslationalStiffness: []
Label: []
structuralModel = createpde("structural","static-solid");
gm = multicuboid(20,10,5);
Assign the geometry to the structural model and plot the geometry.
structuralModel.Geometry = gm;
pdegplot(structuralModel,"FaceLabels","on","FaceAlpha",0.5)
5-1429
5 Functions
The bottom face of the block rests 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'
5-1430
structuralBoundaryLoad
Boundary Loads
Force: []
SurfaceTraction: []
Pressure: []
TranslationalStiffness: [3x1 double]
Label: []
model = createpde("structural","static-solid");
Create the geometry, which consists of two cuboids stacked on top of each other.
model.Geometry = gm;
Plot the geometry and display the face labels. Rotate the geometry so that you can see the face labels
on the left side.
figure
pdegplot(model,"FaceLabels","on");
view([-67 5])
5-1431
5 Functions
Plot the geometry and display the vertex labels. Rotate the geometry so that you can see the vertex
labels on the right side.
figure
pdegplot(model,"VertexLabels","on","FaceAlpha",0.5)
xlim([-0.01 0.1])
zlim([-0.01 0.02])
view([60 5])
5-1432
structuralBoundaryLoad
Specify Young's modulus, Poisson's ratio, and the mass density of the material.
structuralProperties(model,"YoungsModulus",201E9,"PoissonsRatio",0.3);
structuralBC(model,"Face",[5 10],"Constraint","fixed");
structuralBoundaryLoad(model,"Vertex",6,"Force",[0;10^4;0])
ans =
StructuralBC with properties:
RegionType: 'Vertex'
RegionID: 6
Vectorized: 'off'
5-1433
5 Functions
Boundary Loads
Force: [3x1 double]
SurfaceTraction: []
Pressure: []
TranslationalStiffness: []
Label: []
Use a function handle to specify a frequency-dependent pressure for a frequency response model.
Specify the pressure loading on a tine (face 11) as a short rectangular pressure pulse. In the
frequency domain, this pressure pulse is a unit load uniformly distributed across all frequencies.
5-1434
structuralBoundaryLoad
structuralBoundaryLoad(fmodel,"Face",11,"Pressure",1);
2
Now specify a frequency-dependent pressure load, for example, p = e− ω − 1000 /100000.
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 with a small plate at 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)
Zoom in to see the face labels on the small plate at the center.
5-1435
5 Functions
figure
pdegplot(structuralmodel,"FaceLabels","on","FaceAlpha",0.25)
axis([-0.2 0.2 -0.2 0.2 -0.1 0.1])
Specify Young's modulus, Poisson's ratio, and the 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)
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 12
Vectorized: 'off'
5-1436
structuralBoundaryLoad
XDisplacement: []
YDisplacement: []
ZDisplacement: []
Constraint: []
Radius: []
Reference: []
Label: []
Boundary Loads
Force: []
SurfaceTraction: []
Pressure: @(location,state)5E7.*sin(25.*state.time)
TranslationalStiffness: []
Label: []
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 with a small plate at 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-1437
5 Functions
Zoom in to see the face labels on the small plate at the center.
figure
pdegplot(structuralmodel,"FaceLabels","on","FaceAlpha",0.25)
axis([-0.2 0.2 -0.2 0.2 -0.1 0.1])
5-1438
structuralBoundaryLoad
Specify Young's modulus, Poisson's ratio, and the 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)
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 12
Vectorized: 'off'
5-1439
5 Functions
Constraint: []
Radius: []
Reference: []
Label: []
Boundary Loads
Force: []
SurfaceTraction: []
Pressure: 50000000
TranslationalStiffness: []
Label: []
structuralModel = createpde("structural","transient-solid");
importGeometry(structuralModel,"BracketWithHole.stl");
pdegplot(structuralModel,"FaceLabels","on")
view(-20,10)
5-1440
structuralBoundaryLoad
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)
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 7
Vectorized: 'off'
5-1441
5 Functions
Radius: []
Reference: []
Label: []
Boundary Loads
Force: []
SurfaceTraction: []
Pressure: 100000
TranslationalStiffness: []
Label: []
structuralmodel = createpde("structural","transient-solid");
Create the geometry, which consists of two cuboids stacked on top of each other.
structuralmodel.Geometry = gm;
Plot the geometry and display the face labels. Rotate the geometry so that you can see the face labels
on the left side.
figure
pdegplot(structuralmodel,"FaceLabels","on");
view([-67 5])
5-1442
structuralBoundaryLoad
Plot the geometry and display the vertex labels. Rotate the geometry so that you can see the vertex
labels on the right side.
figure
pdegplot(structuralmodel,"VertexLabels","on","FaceAlpha",0.5)
xlim([-0.01 0.1])
zlim([-0.01 0.02])
view([60 5])
5-1443
5 Functions
Specify Young's modulus, Poisson's ratio, and the mass density of the material.
structuralProperties(structuralmodel,"YoungsModulus",201E9, ...
"PoissonsRatio",0.3, ...
"MassDensity",7800);
structuralBC(structuralmodel,"Face",[5 10],"Constraint","fixed");
structuralBoundaryLoad(structuralmodel,"Vertex",6, ...
"Force",[0;1000;0], ...
"StartTime",1, ...
"EndTime",1.05)
ans =
StructuralBC with properties:
RegionType: 'Vertex'
RegionID: 6
Vectorized: 'off'
5-1444
structuralBoundaryLoad
ZDisplacement: []
Constraint: []
Radius: []
Reference: []
Label: []
Boundary Loads
Force: [3×1 double]
SurfaceTraction: []
Pressure: []
TranslationalStiffness: []
Label: []
structuralIC(structuralmodel,"Displacement",[0;0;0],"Velocity",[0;0;0])
ans =
GeometricStructuralICs with properties:
RegionType: 'Cell'
RegionID: [1 2]
InitialDisplacement: [3×1 double]
InitialVelocity: [3×1 double]
generateMesh(structuralmodel,"Hmax",0.02);
Because the load is zero for the initial time span and is applied for only a short time, solve the model
for two time spans. Use the first time span to find the solution before the force pulse.
structuralresults1 = solve(structuralmodel,0:1E-2:1);
Use the second time span to find the solution during and after the force pulse.
structuralIC(structuralmodel,structuralresults1)
ans =
NodalStructuralICs with properties:
5-1445
5 Functions
Plot the displacement value at the node corresponding to vertex 6, where you applied the
concentrated force pulse.
loadedNd = findNodes(structuralmodel.Mesh,"region","Vertex",6);
plot(structuralresults2.SolutionTimes, ...
structuralresults2.Displacement.uy(loadedNd,:))
Input Arguments
structuralmodel — Structural model
StructuralModel object
Structural model, specified as a StructuralModel object. The model contains the geometry, mesh,
structural properties of the material, body loads, boundary loads, and boundary conditions.
Example: structuralmodel = createpde("structural","transient-solid")
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
5-1446
structuralBoundaryLoad
Geometric region ID, specified as a positive integer or vector of positive integers. Find the region IDs
by using pdegplot.
Example: structuralBoundaryLoad(structuralmodel,"Face",[2,5],"SurfaceTraction",
[0,0,100])
Data Types: double
VertexID — Vertex ID
positive integer | vector of positive integers
Vertex ID, specified as a positive integer or vector of positive integers. Find the vertex IDs using
pdegplot.
Example: structuralBoundaryLoad(structuralmodel,"Vertex",6,"Force",[0;10^4;0])
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 or frequency response analysis, STval also
can be a function of time or frequency, respectively. For details, see “More About” on page 5-1451.
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. A positive-value pressure
acts into the boundary (for example, compression), while a negative-value pressure acts away from
the boundary (for example, suction).
If you specify Pval as a function handle, the function must return a row vector where each column
corresponds to the value of pressure at the boundary coordinates provided by the solver. In case of a
transient structural model, Pval also can be a function of time. In case of a frequency response
structural model, Pval can be a function of frequency (when specified as a function handle) or a
constant pressure with the same magnitude for a broad frequency spectrum. For details, see “More
About” on page 5-1451.
Example: structuralBoundaryLoad(structuralmodel,"Face",[2,5],"Pressure",10^5)
Data Types: double | function_handle
5-1447
5 Functions
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 or frequency
response analysis, TSval also can be a function of time or frequency, respectively. For details, see
“More About” on page 5-1451.
Example: structuralBoundaryLoad(structuralmodel,"Edge",
[2,5],"TranslationalStiffness",[0;5500])
Data Types: double | function_handle
Concentrated force at a vertex, specified as a numeric vector or function handle. Use a function
handle to specify concentrated force that depends time or frequency. For details, see “More About”
on page 5-1451.
Example: structuralBoundaryLoad(structuralmodel,"Vertex",5,"Force",[0;0;10])
Data Types: double | function_handle
Label for the structural boundary load, specified as a character vector or a string.
Data Types: char | string
Use one or more of the name-value pair arguments to specify the form and duration of the pressure
or concentrated force pulse and harmonic excitation for a transient structural model only. Specify
the pressure or force value using the Pval or Fval argument, respectively.
You can model rectangular, triangular, and trapezoidal pressure or concentrated force pulses. If the
start time is 0, you can omit specifying it.
5-1448
structuralBoundaryLoad
You can model a harmonic pressure or concentrated force load by specifying its frequency and initial
phase. If the initial phase is 0, you can omit specifying it.
Example: structuralBoundaryLoad(structuralmodel,"Face",
[2,5],"Pressure",10^5,"RiseTime",0.5,"FallTime",0.5,"EndTime",3)
5-1449
5 Functions
Start time for pressure or concentrated force load, specified as a nonnegative number. Specify this
argument only for transient structural models.
Example: structuralBoundaryLoad(structuralmodel,"Face",
[2,5],"Pressure",10^5,"StartTime",1,"EndTime",3)
Data Types: double
End time for pressure or concentrated force load, specified as a nonnegative number equal or greater
than the start time value. Specify this argument only for transient structural models.
Example: structuralBoundaryLoad(structuralmodel,"Face",
[2,5],"Pressure",10^5,"StartTime",1,"EndTime",3)
Data Types: double
Rise time for pressure or concentrated force load, specified as a nonnegative number. Specify this
argument only for transient structural models.
Example: structuralBoundaryLoad(structuralmodel,"Face",
[2,5],"Pressure",10^5,"RiseTime",0.5,"FallTime",0.5,"EndTime",3)
Data Types: double
Fall time for pressure or concentrated force load, specified as a nonnegative number. Specify this
argument only for transient structural models.
Example: structuralBoundaryLoad(structuralmodel,"Face",
[2,5],"Pressure",10^5,"RiseTime",0.5,"FallTime",0.5,"EndTime",3)
Data Types: double
Frequency of sinusoidal pressure or concentrated force, specified as a positive number, in radians per
unit of time. Specify this argument only for transient structural models.
Example: structuralBoundaryLoad(structuralmodel,"Face",
[2,5],"Pressure",10^5,"Frequency",25)
Data Types: double
5-1450
structuralBoundaryLoad
Output Arguments
boundaryLoad — Handle to boundary load
StructuralBC object
More About
Specifying Nonconstant Parameters of a Structural Model
Use a function handle to specify the following structural parameters when they depend on space and,
depending of the type of structural analysis, either time or frequency:
For example, use function handles to specify the pressure load, x-component of the enforced
displacement, and the initial displacement for this model.
structuralBoundaryLoad(model,"Face",12, ...
"Pressure",@myfunPressure)
structuralBC(model,"Face",2, ...
"XDisplacement",@myfunBC)
structuralIC(model,"Face",12, ...
"Displacement",@myfunIC)
For all parameters, except the initial displacement and velocity, the function must be of the form:
function structuralVal = myfun(location,state)
For the initial displacement and velocity the function must be of the form:
function structuralVal = myfun(location)
The solver computes and populates the data in the location and state structure arrays and passes
this data to your function. You can define your function so that its output depends on this data. You
can use any names instead of location and state, but the function must have exactly two
arguments (or one argument if the function specifies the initial displacement or initial velocity).
5-1451
5 Functions
Furthermore, for boundary conditions, the solver passes these data in the location structure:
Boundary constraints and loads get these data from the solver:
If a parameter represents a vector value, such as surface traction, spring stiffness, force, or
displacement, your 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 parameter value (a vector) at the
boundary coordinates provided by the solver.
To use additional arguments in your function, wrap your function (that takes additional arguments)
with an anonymous function that takes only the location and state arguments. For example:
5-1452
structuralBoundaryLoad
structuralVal = ...
@(location,state) myfunWithAdditionalArgs(location,state,arg1,arg2...)
structuralBC(model,"Face",2,"XDisplacement",structuralVal)
structuralVal = ...
@(location) myfunWithAdditionalArgs(location,arg1,arg2...)
structuralIC(model,"Face",2,"Displacement",structuralVal)
Version History
Introduced in R2017b
R2021b: Label to extract sparse linear models for use with Control System Toolbox
Now you can add a label for structural boundary loads to be used by the linearizeInput function.
This function lets you pass structural boundary loads to the linearize function that extracts sparse
linear models for use with Control System Toolbox.
You can now use addVertex to create new vertices at any points on boundaries of a 2-D or 3-D
geometry represented by a DiscreteGeometry object. Then set concentrated boundary loads at
these vertices.
You can now specify time-dependent boundary loads by using function handles or specify the form
and duration of the pressure pulse and the frequency and phase of sinusoidal pressure.
See Also
StructuralModel | structuralProperties | structuralDamping | structuralBodyLoad |
structuralBC | StructuralBC Properties
5-1453
5 Functions
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,
superelement interfaces, initial displacement and velocity, and mesh.
Creation
To create a StructuralModel object, use createpde and specify 'structural' as its first
argument.
Properties
AnalysisType — Type of structural analysis
'static-solid' | 'static-planestress' | 'static-planestrain' | 'static-
axisymmetric' | 'transient-solid' | 'transient-planestress' | 'transient-
planestrain' | 'transient-axisymmetric' | 'modal-solid' | 'modal-planestress' |
'modal-planestrain' | 'modal-axisymmetric' | 'frequency-solid' | 'frequency-
planestress' | 'frequency-planestrain' | 'frequency-axisymmetric'
Static analysis:
Transient analysis:
Modal analysis:
5-1454
StructuralModel
To change a structural analysis type, assign a new type to model.AnalysisType. Ensure that all
other properties of the model are consistent with the new analysis type. Note that you cannot change
the spatial dimensionality. For example, you can change the analysis type from 'static-solid' to
'modal-solid', but cannot change it to 'static-planestress'.
Example: model = createpde('structural','static-solid')
Data Types: char
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.
Structural loads and boundary conditions applied to the geometry, specified as a StructuralBC
object containing the boundary condition assignments. For details, see StructuralBC Properties.
To specify boundary conditions for your model, use the structuralBC function. To specify boundary
loads, use structuralBoundaryLoad.
5-1455
5 Functions
To set damping parameters for your structural model, use the structuralDamping function.
Reference temperature for a thermal load, specified as a number. The reference temperature
corresponds to state of zero thermal stress of the model. The default value 0 implies that the thermal
load is specified in terms of the temperature change and its derivatives.
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
To set initial conditions for your transient structural model, use the structuralIC function.
To specify superelement interfaces for your frequency response structural model, use the
structuralSEInterface function.
Mesh for solution, specified as a FEMesh object. For property details, see FEMesh.
Inputs for a linearized model, specified as a structure array. The inputs are used by the linearize
that extracts mechss model from a structural model.
Inputs for a linearized model, specified as a structure array. The outputs are used by the linearize
that extracts mechss model from a structural model.
5-1456
StructuralModel
Algorithm options for the PDE solvers, specified 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
geometryFromEdges Create 2-D geometry from decomposed geometry matrix
geometryFromMesh Create 2-D or 3-D geometry from mesh
importGeometry Import geometry from STL or STEP file
structuralBC Specify boundary conditions for structural model
structuralSEInterface Specify structural superelement interface for component mode synthesis
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 structural analysis, heat transfer, or electromagnetic analysis
problem
reduce Reduce structural or thermal model
Examples
structuralModel = createpde("structural","static-solid")
structuralModel =
StructuralModel with properties:
AnalysisType: "static-solid"
Geometry: []
MaterialProperties: []
BodyLoads: []
BoundaryConditions: []
ReferenceTemperature: []
SuperelementInterfaces: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
gm = multicuboid(0.5,0.1,0.1);
structuralModel.Geometry = gm;
pdegplot(structuralModel,"FaceAlpha",0.5)
5-1457
5 Functions
structuralProperties(structuralModel,"Cell",1,"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
CTE: []
HystereticDamping: []
structuralBodyLoad(structuralModel, ...
"GravitationalAcceleration",[0;0;-9.8])
ans =
BodyLoadAssignment with properties:
RegionType: 'Cell'
RegionID: 1
5-1458
StructuralModel
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 6
Vectorized: 'off'
Boundary Loads
Force: []
SurfaceTraction: []
Pressure: []
TranslationalStiffness: []
Label: []
ans =
StructuralBC with properties:
RegionType: 'Face'
RegionID: 5
Vectorized: 'off'
5-1459
5 Functions
Boundary Loads
Force: []
SurfaceTraction: [3x1 double]
Pressure: []
TranslationalStiffness: []
Label: []
Generate a mesh.
generateMesh(structuralModel)
ans =
FEMesh with properties:
structuralModel =
StructuralModel with properties:
AnalysisType: "static-solid"
Geometry: [1x1 DiscreteGeometry]
MaterialProperties: [1x1 StructuralMaterialAssignmentRecords]
BodyLoads: [1x1 BodyLoadAssignmentRecords]
BoundaryConditions: [1x1 StructuralBCRecords]
ReferenceTemperature: []
SuperelementInterfaces: []
Mesh: [1x1 FEMesh]
SolverOptions: [1x1 pde.PDESolverOptions]
Version History
Introduced in R2017b
You can now specify hysteretic damping of a material for direct and modal frequency response
models.
R2021b: Sparse linear models for use with Control System Toolbox
5-1460
StructuralModel
You can now specify AnalysisType for axisymmetric models. Axisymmetric analysis simplifies 3-D
structural problems to 2-D using their symmetry around the axis of rotation.
The toolbox now supports the frequency response analysis for structural models.
You can now specify AnalysisType for frequency response analysis, including 'frequency-
solid', 'frequency-planestress', 'frequency-planestrain', and 'frequency-
axisymmetric'.
The programmatic workflow for static structural analysis problems now enables you to account for
thermal loading. When setting up a static structural problem, you can specify a reference
temperature as a property of StructuralModel. This temperature corresponds to the state of the
model at which both thermal stress and strain are zeros.
The programmatic workflow for modal analysis problems now enables you to find natural frequencies
and mode shapes of a structure. When solving a modal analysis model, the solver requires a
frequency range parameter and returns the modal solution in that frequency range. The
AnalysisType values for modal analysis are 'modal-solid', 'modal-planestress', 'modal-
planestrain', and 'modal-axisymmetric'.
The programmatic workflow for structural analysis problems now enables you to set up, solve, and
analyze dynamic linear elasticity problems. The AnalysisType values for transient analysis are
'transient-solid', 'transient-planestress', 'transient-planestrain', and
'transient-axisymmetric'.
See Also
assembleFEMatrices | createpde | generateMesh | geometryFromEdges |
geometryFromMesh | importGeometry | pdegplot | pdeplot | pdeplot3D | solve |
structuralBC | structuralBodyLoad | structuralBoundaryLoad | structuralProperties |
structuralSEInterface | reduce
5-1461
5 Functions
structuralProperties
Package: pde
Syntax
structuralProperties(structuralmodel,"YoungsModulus",YMval,"PoissonsRatio",
PRval)
structuralProperties( ___ ,"MassDensity",MDval)
structuralProperties( ___ ,"CTE",CTEval)
structuralProperties( ___ ,"HystereticDamping",g)
structuralProperties( ___ ,RegionType,RegionID)
mtl = structuralProperties( ___ )
Description
structuralProperties(structuralmodel,"YoungsModulus",YMval,"PoissonsRatio",
PRval) assigns 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.
Examples
5-1462
structuralProperties
ans =
StructuralMaterialAssignment with properties:
RegionType: 'Cell'
RegionID: 1
YoungsModulus: 2.0000e+11
PoissonsRatio: 0.3000
MassDensity: 7800
CTE: []
HystereticDamping: []
5-1463
5 Functions
structuralModel = createpde("structural","modal-solid");
gm = multicuboid(0.5,0.1,0.1);
structuralModel.Geometry = gm;
pdegplot(structuralModel,"FaceAlpha",0.5)
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
CTE: []
HystereticDamping: []
5-1464
structuralProperties
Specify the coefficients of thermal expansion for a bimetallic cantilever beam. The bottom layer is
steel. The top layer is copper.
Specify Young's modulus, Poisson's ratio, and the 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
5-1465
5 Functions
YoungsModulus: 2.1000e+11
PoissonsRatio: 0.2800
MassDensity: []
CTE: 1.3000e-05
HystereticDamping: []
Specify Young's modulus, Poisson's ratio, and the 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
HystereticDamping: []
Hysteretic Damping
structuralmodel = createpde("structural","frequency-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-1466
structuralProperties
Specify Young's modulus, Poisson's ratio, mass density, and hysteretic damping for both cylinders.
structuralProperties(structuralmodel,"YoungsModulus",110E9, ...
"PoissonsRatio",0.28, ...
"MassDensity",7800, ...
"HystereticDamping",0.2, ...
"Cell",1)
ans =
StructuralMaterialAssignment with properties:
RegionType: 'Cell'
RegionID: 1
YoungsModulus: 1.1000e+11
PoissonsRatio: 0.2800
MassDensity: 7800
CTE: []
HystereticDamping: 0.2000
structuralProperties(structuralmodel,"YoungsModulus",210E9, ...
"PoissonsRatio",0.3, ...
"MassDensity",7800, ...
"HystereticDamping",0.1, ...
"Cell",2)
ans =
StructuralMaterialAssignment with properties:
5-1467
5 Functions
RegionType: 'Cell'
RegionID: 2
YoungsModulus: 2.1000e+11
PoissonsRatio: 0.3000
MassDensity: 7800
CTE: []
HystereticDamping: 0.1000
Assign the geometry to the structural model and plot the geometry.
structuralModel.Geometry = gm;
pdegplot(structuralModel,"CellLabels","on","FaceAlpha",0.4)
5-1468
structuralProperties
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: []
CTE: []
HystereticDamping: []
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: []
HystereticDamping: []
Input Arguments
structuralmodel — Structural model
StructuralModel object
Structural model, specified as a StructuralModel object. The model contains the geometry, mesh,
structural properties of the material, body loads, boundary loads, and boundary conditions.
Example: structuralmodel = createpde("structural","transient-solid")
Poisson's ratio of the material, specified as a number greater than 0 and less than 0.5.
5-1469
5 Functions
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
Coefficient of thermal expansion, specified as a real number. This argument is required for thermal
stress analysis. Thermal stress analysis requires the structural model to be static.
Example:
structuralProperties(structuralmodel,"YoungsModulus",210e3,"PoissonsRatio",0.
3,"MassDensity",2.7e-6,"CTE",11.7e-6)
Data Types: double
g — Hysteretic damping
nonnegative number
Hysteretic damping, specified as a nonnegative number. This type of damping is also called structural
damping.
Example:
structuralProperties(structuralmodel,"YoungsModulus",210E9,"PoissonsRatio",0.
3,"MassDensity",7800,"HystereticDamping",0.1)
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,"Poissons
Ratio",0.3)
Data Types: char | string
Cell or face ID, specified as a vector of positive integers. Find the region IDs using pdegplot with
the "CellLabels" (3-D) or "FaceLabels" (2-D) value set to "on".
5-1470
structuralProperties
Example:
structuralProperties(structuralmodel,"Cell",1:3,"YoungsModulus",110E9,"Poisso
nsRatio",0.3)
Data Types: double
Output Arguments
mtl — Handle to material properties
StructuralMaterialAssignment object
Version History
Introduced in R2017b
You can now specify hysteretic damping of a material for direct and modal frequency response
models.
See Also
StructuralModel | createpde | structuralBodyLoad | structuralDamping |
structuralBoundaryLoad | structuralBC | StructuralMaterialAssignment Properties
5-1471
5 Functions
structuralSEInterface
Package: pde
Syntax
structuralSEInterface(structuralmodel,RegionType,RegionID)
sei = structuralSEInterface( ___ )
Description
structuralSEInterface(structuralmodel,RegionType,RegionID) defines the specified
geometric region RegionType, RegionID as a superelement interface for component mode
synthesis. For better performance, specify geometric regions with a minimal number of nodes. For
example, use a set of edges instead of a face, or a set of vertices instead of an edge.
If you intend to use a reduced-order model in Simscape Multibody, use structuralBC instead of
structuralSEInterface.
Examples
Define the two ends of the beam as structural superelement interfaces. The reduced-order modeling
technique retains the degrees of freedom on these boundaries while condensing all other degrees of
freedom.
structuralmodel = createpde("structural","modal-solid");
gm = multicuboid(0.1,0.01,0.01);
structuralmodel.Geometry = gm;
pdegplot(structuralmodel,"EdgeLabels","on","FaceAlpha",0.5)
5-1472
structuralSEInterface
Specify Young's modulus, Poisson's ratio, and the mass density of the material.
structuralProperties(structuralmodel,"YoungsModulus",70E9, ...
"PoissonsRatio",0.3, ...
"MassDensity",2700);
Generate a mesh.
generateMesh(structuralmodel);
Specify the ends of the beam as structural superelement interfaces. For better performance, use the
set of edges bounding each side of the beam instead of using the entire face.
structuralSEInterface(structuralmodel,"Edge",[4,6,9,10]);
structuralSEInterface(structuralmodel,"Edge",[2,8,11,12]);
Reduce the model to all modes in the frequency range [-Inf,500000] and the interface degrees of
freedom.
R = reduce(structuralmodel,"FrequencyRange",[-Inf,500000])
R =
ReducedStructuralModel with properties:
K: [166x166 double]
M: [166x166 double]
NumModes: 22
RetainedDoF: [144x1 double]
5-1473
5 Functions
ReferenceLocations: []
Mesh: [1x1 FEMesh]
Input Arguments
structuralmodel — Structural model
StructuralModel object
Structural model, specified as a StructuralModel object. The model contains the geometry, mesh,
structural properties of the material, body loads, boundary loads, and boundary conditions.
Example: structuralmodel = createpde("structural","transient-solid")
Geometric region type, specified as "Vertex", "Edge", or, for a 3-D model, "Face".
Example: structuralSEInterface(structuralmodel,"Face",[2,5])
Data Types: char | string
Geometric region ID, specified as a vector of positive integers. Find the region IDs by using
pdegplot.
Example: structuralSEInterface(structuralmodel,"Face",[2,5])
Data Types: double
Output Arguments
sei — Handle to superelement interface
StructuralSEIAssignment object
Version History
Introduced in R2019b
See Also
StructuralModel | structuralBC | reduce | reconstructSolution | solve |
ReducedStructuralModel | StructuralSEIAssignment Properties
5-1474
StructuralSEIAssignment Properties
StructuralSEIAssignment Properties
Superelement interface assignment for structural model
Description
A StructuralSEIAssignment object contains a description of the superelement interfaces for a
structural analysis model. A StructuralModel container has a vector of
StructuralSEIAssignment objects in its
SuperelementInterfaces.StructuralSEIAssignments property.
Properties
Properties of StructuralSEIAssignment
Region type, specified as 'Vertex', 'Edge', or, for a 3-D model, 'Face'.
Data Types: char | string
RegionID — Region ID
positive integer
Geometric region ID, specified as a positive integer. Find the region IDs by using pdegplot.
Data Types: double
Version History
Introduced in R2019b
See Also
structuralSEInterface | structuralBC | reduce | reconstructSolution | solve |
ReducedStructuralModel | StructuralModel | StructuralBC Properties
5-1475
5 Functions
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.
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-429.
5-1476
StationaryResults
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-429.
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-429.
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-429.
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
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-1477
5 Functions
figure
pdegplot(model,"FaceLabels","on")
view(-134,-32)
title("Bracket with Face Labels, Rear View")
5-1478
StationaryResults
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 “Linear Elasticity Equations” on
page 3-194.
E = 200e9;
nu = 0.3;
specifyCoefficients(model,"m",0,...
"d",0,...
"c",elasticityC3D(E,nu),...
"a",0,...
"f",[0;0;0]);
Create a mesh.
generateMesh(model,"Hmax",1e-2);
results = solvepde(model)
results =
StationaryResults with properties:
5-1479
5 Functions
u = results.NodalSolution;
pdeplot3D(model,"ColorMapData",u(:,3))
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-1480
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-1481
5 Functions
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 “Linear
Elasticity Equations” on page 3-194.
E = 200e9;
nu = 0.3;
c = elasticityC3D(E,nu);
a = 0;
f = [0;0;0];
Create a mesh.
generateMesh(model,"Hmax",1e-2);
u = assempde(model,c,a,f);
results = createPDEResults(model,u)
results =
StationaryResults with properties:
5-1482
StationaryResults
u = results.NodalSolution;
pdeplot3D(model,"ColorMapData",u(:,3))
Version History
Introduced in R2016a
You can now evaluate flux of PDE solution as a tensor product of c-coefficient and gradient of PDE
solution.
5-1483
5 Functions
See Also
solvepde | interpolateSolution | evaluateGradient | evaluateCGradient |
EigenResults | TimeDependentResults
Topics
“Poisson's Equation on Unit Disk” on page 3-263
“Minimal Surface Problem” on page 3-286
“Solve Problems Using PDEModel Objects” on page 2-3
5-1484
SteadyStateThermalResults
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 a 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
All Steady-State Thermal Models
5-1485
5 Functions
Object Functions
evaluateHeatFlux Evaluate heat flux of thermal solution at nodal or arbitrary spatial
locations
evaluateHeatRate Evaluate integrated heat flow rate normal to specified boundary
evaluateTemperatureGradient Evaluate temperature gradient of thermal solution at arbitrary
spatial locations
interpolateTemperature Interpolate temperature in thermal result at arbitrary spatial
locations
Examples
5-1486
SteadyStateThermalResults
thermalmodel = createpde(thermal="steadystate");
importGeometry(thermalmodel,"Block.stl");
pdegplot(thermalmodel,FaceLabels="on",FaceAlpha=0.5)
axis equal
thermalProperties(thermalmodel,ThermalConductivity=80);
Apply a constant temperature of 100 °C to the left side of the block (face 1) and a constant
temperature of 300 °C 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)
5-1487
5 Functions
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 the nodal locations.
pdeplot3D(thermalresults.Mesh,ColorMapData=thermalresults.Temperature)
Analyze heat transfer in a rod with a circular cross-section and internal heat generation by
simplifying a 3-D axisymmetric model to a 2-D model.
thermalmodel = createpde("thermal","steadystate-axisymmetric");
5-1488
SteadyStateThermalResults
The 2-D model is a rectangular strip whose x-dimension extends from the axis of symmetry to the
outer surface and whose y-dimension extends over the actual length of the rod (from -1.5 m to 1.5
m). Create the geometry by specifying the coordinates of its four corners. For axisymmetric models,
the toolbox assumes that the axis of rotation is the vertical axis passing through r = 0.
geometryFromEdges(thermalmodel,g);
figure
pdegplot(thermalmodel,"EdgeLabels","on")
axis equal
thermalProperties(thermalmodel,"ThermalConductivity",k);
5-1489
5 Functions
internalHeatSource(thermalmodel,q);
Define the boundary conditions. There is no heat transferred in the direction normal to the axis of
symmetry (edge 1). You do not need to change the default boundary condition for this edge. Edge 2 is
kept at a constant temperature T = 100 °C.
thermalBC(thermalmodel,"Edge",2,"Temperature",100);
Specify the convection boundary condition on the outer boundary (edge 3). The surrounding
temperature at the outer boundary is 100 °C, and the heat transfer coefficient is 50 W/ m ⋅∘ C .
thermalBC(thermalmodel,"Edge",3,...
"ConvectionCoefficient",50,...
"AmbientTemperature",100);
The heat flux at the bottom of the rod (edge 4) is 5000 W/m2.
thermalBC(thermalmodel,"Edge",4,"HeatFlux",5000);
msh = generateMesh(thermalmodel);
figure
pdeplot(thermalmodel)
axis equal
5-1490
SteadyStateThermalResults
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.RGradients, and
thermalresults.ZGradients. For example, plot temperatures at the nodal locations.
T = thermalresults.Temperature;
figure
pdeplot(thermalmodel,"XYData",T,"Contour","on")
axis equal
title("Steady-State Temperature")
Version History
Introduced in R2017a
5-1491
5 Functions
See Also
Functions
solve | evaluateHeatFlux | evaluateHeatRate | evaluateTemperatureGradient |
interpolateTemperature
Objects
femodel | ThermalModel | TransientThermalResults | ModalThermalResults
5-1492
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, specified as 'Face' for 3-D geometry or 'Edge' for 2-D geometry.
Data Types: char | string
Geometric region ID, specified as a vector of positive integers. Find the region IDs by using
pdegplot with the 'FaceLabels' (3-D) or 'EdgeLabels' (2-D) value set to 'on'.
Data Types: double
Temperature boundary condition, specified as a number or a function handle. Use a function handle
to specify spatially or temporally varying temperature.
Data Types: double | function_handle
Heat flux boundary condition, specified 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
Convection to ambient boundary condition, specified as a number or a function handle. Use a function
handle to specify a spatially or temporally varying convection coefficient or a nonlinear convection
coefficient. Specify ambient temperature using the AmbientTemperature argument.
5-1493
5 Functions
Radiation emissivity coefficient, specified 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
Ambient temperature, specified as a number. The ambient temperature value is required for
specifying convection and radiation boundary conditions.
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”. For details of this
evaluation, see “Nonconstant Boundary Conditions” on page 2-131.
Data Types: char | string
Version History
Introduced in R2017a
See Also
thermalBC | findThermalBC | ThermalModel
5-1494
ThermalMaterialAssignment Properties
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, specified as 'Face' for a 2-D region, or 'Cell' for a 3-D region.
Data Types: char | string
RegionID — Region ID
vector of positive integers
Region ID, specified as a vector of positive integers. To determine which ID corresponds to which
portion of the geometry, use the pdegplot function. Set the 'FaceLabels' name-value pair to
'on'.
Data Types: double
5-1495
5 Functions
Tips
• When there are multiple assignments to the same geometric region, the toolbox uses the last
applied setting.
• To avoid assigning material properties to a wrong region, ensure that you are using the correct
geometric region IDs by plotting and visually inspecting the geometry.
Version History
Introduced in R2017a
See Also
findThermalProperties | thermalProperties
5-1496
ThermalModel
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" | "modal" | "steadystate-axisymmetric" | "transient-
axisymmetric" | "modal-axisymmetric"
To change a thermal analysis type, assign a new type to model.AnalysisType. Ensure that all other
properties of the model are consistent with the new analysis type.
Material properties within the domain, specified as an object containing the material property
assignments.
Heat source within the domain or subdomain, specified as an object containing heat source
assignments.
Boundary conditions applied to the geometry, specified as an object containing the boundary
condition assignments.
5-1497
5 Functions
Initial temperature or initial guess, specified as an object containing the initial temperature
assignments within the geometric domain.
Finite element mesh, specified as an FEMesh object. For details, see FEMesh. You create the mesh by
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)
Inputs for a linearized model, specified as a structure array. The inputs are used by the linearize
that extracts a sparss model from a thermal model.
Inputs for a linearized model, specified as a structure array. The outputs are used by the linearize
that extracts a sparss model from a thermal model.
Algorithm options for the PDE solvers, specified 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
geometryFromEdges Create 2-D geometry from decomposed geometry matrix
geometryFromMesh Create 2-D or 3-D geometry from mesh
importGeometry Import geometry from STL or STEP file
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 structural analysis, heat transfer, or electromagnetic analysis problem
5-1498
ThermalModel
Examples
thermalmodel = createpde("thermal","transient")
thermalmodel =
ThermalModel with properties:
AnalysisType: "transient"
Geometry: []
MaterialProperties: []
HeatSources: []
StefanBoltzmannConstant: []
BoundaryConditions: []
InitialConditions: []
Mesh: []
SolverOptions: [1x1 pde.PDESolverOptions]
g = @squareg;
geometryFromEdges(thermalmodel,g)
ans =
AnalyticGeometry with properties:
NumCells: 0
NumFaces: 1
NumEdges: 4
NumVertices: 4
Vertices: [4x2 double]
thermalProperties(thermalmodel,"ThermalConductivity",79.5,...
"MassDensity",7850,...
"SpecificHeat",450,...
"Face",1)
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 of 25.
internalHeatSource(thermalmodel,25)
5-1499
5 Functions
ans =
HeatSourceAssignment with properties:
RegionType: 'face'
RegionID: 1
HeatSource: 25
Label: []
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:
RegionType: 'Edge'
RegionID: 2
Temperature: []
HeatFlux: []
ConvectionCoefficient: 5000
Emissivity: []
AmbientTemperature: 25
Vectorized: 'off'
Label: []
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
ans =
FEMesh with properties:
5-1500
ThermalModel
MinElementSize: 0.0566
MeshGradation: 1.5000
GeometricOrder: 'quadratic'
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 pde.PDESolverOptions]
Version History
Introduced in R2017a
You can now approximate the dynamics of the original system with a smaller system while retaining
most of the dynamic characteristics. See reduce for details.
R2021b: Sparse linear models for use with Control System Toolbox
You can now specify AnalysisType for axisymmetric models. Axisymmetric analysis simplifies 3-D
thermal problems to 2-D using their symmetry around the axis of rotation.
See Also
createpde | generateMesh | geometryFromEdges | geometryFromMesh | importGeometry |
internalHeatSource | thermalProperties | pdegplot | pdeplot | pdeplot3D | thermalBC |
thermalIC
5-1501
5 Functions
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
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: []
5-1502
thermalProperties
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");
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)
5-1503
5 Functions
thermalProperties(thermalModel,"Cell",1,"ThermalConductivity",0.4)
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: []
5-1504
thermalProperties
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");
k = @(location,state)40 + 0.003*state.u;
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-1505
5 Functions
Geometric region ID, specified as a vector of positive integers. Find the region IDs by using
pdegplot.
Example: thermalProperties(thermalmodel,"Cell",1:3,"ThermalConductivity",100)
Data Types: double
Thermal conductivity of the material, specified as a positive number, a matrix, or a function handle.
You can specify thermal conductivity for a steady-state or transient model. In case of orthotropic
thermal conductivity, use a thermal conductivity matrix.
Use a function handle to specify the thermal conductivity that depends on space, time, or
temperature. For details, see “More About” on page 5-1507.
Example: thermalProperties(thermalmodel,"Cell",1,"ThermalConductivity",100) or
thermalProperties(thermalmodel,"ThermalConductivity",[80;10;80]) for orthotropic
thermal conductivity
Data Types: double | function_handle
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. For
details, see “More About” on page 5-1507.
Example:
thermalProperties(thermalmodel,"Cell",1,"ThermalConductivity",100,"MassDensit
y",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. For
details, see “More About” on page 5-1507.
Example:
thermalProperties(thermalmodel,"Cell",1,"ThermalConductivity",100,"MassDensit
y",2730e-9,"SpecificHeat",910)
Data Types: double | function_handle
5-1506
thermalProperties
Output Arguments
mtl — Handle to material properties
ThermalMaterialAssignment object
More About
Specifying Nonconstant Parameters of a Thermal Model
Use a function handle to specify these thermal parameters when they depend on space, temperature,
and time:
For example, use function handles to specify the thermal conductivity, internal heat source,
convection coefficient, and initial temperature for this model.
thermalProperties(model,"ThermalConductivity", ...
@myfunConductivity)
internalHeatSource(model,"Face",2,@myfunHeatSource)
thermalBC(model,"Edge",[3,4], ...
"ConvectionCoefficient",@myfunBC, ...
"AmbientTemperature",27)
thermalIC(model,@myfunIC)
For all parameters, except the initial temperature, the function must be of the form:
The solver computes and populates the data in the location and state structure arrays and passes
this data to your function. You can define your function so that its output depends on this data. You
can use any names instead of location and state, but the function must have exactly two
arguments (or one argument if the function specifies the initial temperature).
5-1507
5 Functions
Furthermore, for boundary conditions, the solver passes these data in the location structure:
Thermal material properties (thermal conductivity, mass density, and specific heat) and internal heat
source get these data from the solver:
Boundary conditions (temperature on the boundary, heat flux, convection coefficient, and radiation
emissivity coefficient) get these data from the solver:
For all thermal parameters, except for thermal conductivity, your function must return a row vector
thermalVal with the number of columns equal to the number of evaluation points, for example, M =
length(location.y).
5-1508
thermalProperties
For thermal conductivity, your function must return a matrix thermalVal 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, for example, M =
length(location.y). For details about dimensions of the matrix, see “c Coefficient for
specifyCoefficients” on page 2-91.
If properties depend on the time or temperature, ensure that your function returns a matrix of NaN of
the correct size when state.u or state.time are NaN. Solvers check whether a problem is time
dependent by passing NaN state values and looking for returned NaN values.
To use additional arguments in your function, wrap your function (that takes additional arguments)
with an anonymous function that takes only the location and state arguments. For example:
thermalVal = ...
@(location,state) myfunWithAdditionalArgs(location,state,arg1,arg2...)
thermalBC(model,"Edge",3,"Temperature",thermalVal)
Version History
Introduced in R2017a
See Also
internalHeatSource | specifyCoefficients | ThermalMaterialAssignment Properties
Topics
“Heat Conduction in Multidomain Geometry with Nonuniform Heat Flux” on page 3-318
5-1509
5 Functions
translate
Package: pde
Translate geometry
Syntax
h = translate(g,s)
Description
h = translate(g,s) translates the geometry g by the distance s.
Examples
Create a model.
model = createpde;
g = importGeometry(model,"PlateHolePlanar.stl");
pdegplot(g)
5-1510
translate
generateMesh(model);
figure
pdemesh(model)
5-1511
5 Functions
Translate the 2-D geometry by 1 along the x-axis and by 2 along the y-axis. Plot the result.
translate(g,[1 2]);
pdegplot(g)
5-1512
translate
Plot the geometry and mesh. The translate function modifies a geometry, but it does not modify a
mesh.
figure
pdegplot(g)
hold on
pdemesh(model)
5-1513
5 Functions
generateMesh(model);
figure
pdegplot(g)
hold on
pdemesh(model)
5-1514
translate
Input Arguments
g — Geometry
fegeometry object | DiscreteGeometry object | AnalyticGeometry object
s — Translation distance
vector of two or three nonzero real numbers
Translation distance, specified as a vector of two or three real numbers. The distance is a vector of
two elements for a 2-D geometry or three elements for a 3-D geometry. The elements specify the
distance along the x-, y-, and, for a 3-D geometry, z-axes.
Output Arguments
h — Resulting geometry
fegeometry object | handle
5-1515
5 Functions
Tips
• After modifying a geometry, regenerate the mesh to ensure a proper mesh association with the
new geometry.
• If g is an fegeometry or AnalyticGeometry object, and you want to replace it with the
modified geometry, assign the output to the original geometry, for example, g = translate(g,
[1 2]).
Version History
Introduced in R2020a
See Also
Functions
rotate | scale | pdegplot | importGeometry | geometryFromMesh | generateMesh |
mergeCells
Objects
fegeometry | DiscreteGeometry | AnalyticGeometry
5-1516
TimeDependentResults
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.
• A TimeDependentResults 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 solution times appear in the SolutionTimes 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 time indices, and for the 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 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.
Properties
Mesh — Finite element mesh
FEMesh object
5-1517
5 Functions
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-429.
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-429.
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-429.
Data Types: double
Complex Number Support: Yes
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-429.
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-1518
TimeDependentResults
model = createpde();
geometryFromEdges(model,dl);
Set boundary conditions that the upper and left edges are at temperature 10.
5-1519
5 Functions
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);
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-1520
TimeDependentResults
Version History
Introduced in R2016a
See Also
interpolateSolution | evaluateGradient | evaluateCGradient | EigenResults |
StationaryResults
Topics
“Heat Transfer in Block with Cavity” on page 3-302
“Wave Equation on Square Domain” on page 3-346
“Solve Problems Using PDEModel Objects” on page 2-3
5-1521
5 Functions
TransientThermalResults
Transient thermal solution and derived quantities
Description
A TransientThermalResults object contains the temperature and gradient 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. You can
extract solution and gradient values for specified time indices from Temperature, XGradients,
YGradients, and ZGradients.
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 a 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
All Transient Thermal Models
5-1522
TransientThermalResults
Solution times, returned as a real vector. SolutionTimes is the same as the tlist input to solve.
Data Types: double
Non-Axisymmetric Models
Axisymmetric Models
5-1523
5 Functions
Object Functions
evaluateHeatFlux Evaluate heat flux of thermal solution at nodal or arbitrary spatial
locations
evaluateHeatRate Evaluate integrated heat flow rate normal to specified boundary
evaluateTemperatureGradient Evaluate temperature gradient of thermal solution at arbitrary
spatial locations
filterByIndex Access transient results for specified time steps
interpolateTemperature Interpolate temperature in thermal result at arbitrary spatial
locations
Examples
thermalmodel = createpde(thermal="transient");
5-1524
TransientThermalResults
• Thermal conductivity is 10 W/ m ⋅∘ C
• Mass density is 2 kg/m3
• Specific heat is 0 . 1 J/ kg ⋅ ∘C
thermalProperties(thermalmodel,ThermalConductivity=10, ...
MassDensity=2, ...
SpecificHeat=0.1, ...
Face=1);
• Thermal conductivity is 2 W/ m ⋅∘ C
• Mass density is 1 kg/m3
• Specific heat is 0 . 1 J/ kg ⋅ ∘C
thermalProperties(thermalmodel,ThermalConductivity=2, ...
MassDensity=1, ...
SpecificHeat=0.1, ...
Face=2);
Assume that the diamond-shaped region is a heat source with a density of 4 W/m2.
internalHeatSource(thermalmodel,4,Face=2);
5-1525
5 Functions
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 most active 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);
T = thermalresults.Temperature;
msh = thermalresults.Mesh;
pdeplot(msh,XYData=T(:,10),Contour="on",ColorMap="hot")
5-1526
TransientThermalResults
Analyze heat transfer in a rod with a circular cross-section and internal heat generation by
simplifying a 3-D axisymmetric model to a 2-D model.
The 2-D model is a rectangular strip whose x-dimension extends from the axis of symmetry to the
outer surface and whose y-dimension extends over the actual length of the rod (from -1.5 m to 1.5
m). Create the geometry by specifying the coordinates of its four corners. For axisymmetric models,
the toolbox assumes that the axis of rotation is the vertical axis passing through r = 0.
g = decsg([3 4 0 0 .2 .2 -1.5 1.5 1.5 -1.5]');
5-1527
5 Functions
Specify the thermal conductivity, mass density, and specific heat of the material.
thermalProperties(thermalmodel,"ThermalConductivity",k,...
"MassDensity",rho,...
"SpecificHeat",cp);
internalHeatSource(thermalmodel,q);
Define the boundary conditions. There is no heat transferred in the direction normal to the axis of
symmetry (edge 1). You do not need to change the default boundary condition for this edge. Edge 2 is
kept at a constant temperature T = 100 °C.
thermalBC(thermalmodel,"Edge",2,"Temperature",100);
Specify the convection boundary condition on the outer boundary (edge 3). The surrounding
temperature at the outer boundary is 100 °C, and the heat transfer coefficient is 50 W/ m ⋅∘ C .
thermalBC(thermalmodel,"Edge",3,...
"ConvectionCoefficient",50,...
"AmbientTemperature",100);
The heat flux at the bottom of the rod (edge 4) is 5000 W/m2.
thermalBC(thermalmodel,"Edge",4,"HeatFlux",5000);
thermalIC(thermalmodel,0);
generateMesh(thermalmodel);
Compute the transient solution for solution times from t = 0 to t = 50000 seconds.
tfinal = 50000;
tlist = 0:100:tfinal;
result = solve(thermalmodel,tlist);
T = result.Temperature;
figure
pdeplot(thermalmodel,"XYData",T(:,end), ...
"Contour","on")
axis equal
title(sprintf(['Transient Temperature ' ...
'at Final Time (%g seconds)'],tfinal))
5-1528
TransientThermalResults
Version History
Introduced in R2017a
See Also
Functions
solve | evaluateHeatFlux | evaluateHeatRate | evaluateTemperatureGradient |
interpolateTemperature
Objects
femodel | ThermalModel | SteadyStateThermalResults | ModalThermalResults
5-1529
5 Functions
ModalThermalResults
Modal thermal solution
Description
A ModalThermalResults object contains the eigenvalues and eigenvector matrix of a thermal
model, and average of snapshots used for proper orthogonal decomposition (POD).
Creation
Solve a modal thermal problem using the solve function. This function returns a modal thermal
solution as a ModalThermalResults object.
Properties
DecayRates — Eigenvalues of thermal model
column vector
5-1530
ModalThermalResults
Finite element mesh, returned as an FEMesh object. For details, see FEMesh.
Examples
Solve a transient thermal problem by first obtaining mode shapes for a particular decay range and
then using the modal superposition method.
Modal Decomposition
thermalmodel = createpde("thermal","modal");
5-1531
5 Functions
• Thermal conductivity is 10 W/ m ⋅∘ C .
• Mass density is 2 kg/m3.
• Specific heat is 0 . 1 J/ kg ⋅ ∘C .
thermalProperties(thermalmodel,"ThermalConductivity",10, ...
"MassDensity",2, ...
"SpecificHeat",0.1, ...
"Face",1);
• Thermal conductivity is 2 W/ m ⋅∘ C .
• Mass density is 1 kg/m3.
• Specific heat is 0 . 1 J/ kg ⋅ ∘C .
thermalProperties(thermalmodel,"ThermalConductivity",2, ...
"MassDensity",1, ...
"SpecificHeat",0.1, ...
"Face",2);
Assume that the diamond-shaped region is a heat source with a density of 4 W/m2.
internalHeatSource(thermalmodel,4,"Face",2);
5-1532
ModalThermalResults
thermalBC(thermalmodel,"Temperature",0,"Edge",[1 2 7 8]);
thermalIC(thermalmodel,0);
generateMesh(thermalmodel);
Compute eigenmodes of the thermal model in the decay range [100,10000] s−1.
RModal = solve(thermalmodel,"DecayRange",[100,10000])
RModal =
ModalThermalResults with properties:
Transient Analysis
Knowing the mode shapes, you can now use the modal superposition method to solve the transient
thermal problem. First, switch the thermal model analysis type to transient.
thermalmodel.AnalysisType = "transient";
The dynamics for this problem are very fast. The temperature reaches a steady state in about 0.1
second. To capture the most active part of the dynamics, set the solution time to
logspace(-2,-1,100). This command returns 100 logarithmically spaced solution times between
0.01 and 0.1.
tlist = logspace(-2,-1,10);
Rtransient = solve(thermalmodel,tlist,"ModalResults",RModal);
T = Rtransient.Temperature;
pdeplot(thermalmodel,"XYData",T(:,end), ...
"Contour","on", ...
"ColorMap","hot")
5-1533
5 Functions
Obtain POD modes of a linear thermal model using several instances of the transient solution
(snapshots).
thermalmodel = createpde("thermal","transient");
geometryFromEdges(thermalmodel,@squareg);
pdegplot(thermalmodel,"EdgeLabels","on")
xlim([-1.1 1.1])
ylim([-1.1 1.1])
5-1534
ModalThermalResults
Specify the thermal conductivity, mass density, and specific heat of the material.
thermalProperties(thermalmodel,"ThermalConductivity",400, ...
"MassDensity",1300, ...
"SpecificHeat",600);
thermalBC(thermalmodel,"Edge",2,"Temperature",100);
thermalIC(thermalmodel,0);
Generate a mesh.
generateMesh(thermalmodel);
Solve the model for three different values of heat source and collect snapshots.
tlist = 0:10:600;
snapShotIDs = [1:10 59 60 61];
Tmatrix = [];
5-1535
5 Functions
Tmatrix = [Tmatrix,results.Temperature(:,snapShotIDs)];
end
thermalmodel.AnalysisType = "modal";
RModal = solve(thermalmodel,"Snapshots",Tmatrix)
RModal =
ModalThermalResults with properties:
Version History
Introduced in R2022a
See Also
Functions
solve
Objects
femodel | ThermalModel | SteadyStateThermalResults | TransientThermalResults |
ModalStructuralResults
5-1536
thermalBC
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( ___ ,"Label",labeltext)
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.
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.
thermalBC( ___ ,"Label",labeltext) adds a label for the thermal boundary condition to be
used by the linearizeInput function. This function lets you pass thermal boundary conditions to
the linearize function that extracts sparse linear models for use with Control System Toolbox.
Examples
5-1537
5 Functions
thermalmodel = createpde("thermal");
geometryFromEdges(thermalmodel,@squareg);
thermalBC(thermalmodel,"Edge",[1,3],"Temperature",100)
ans =
ThermalBC with properties:
RegionType: 'Edge'
RegionID: [1 3]
Temperature: 100
HeatFlux: []
ConvectionCoefficient: []
Emissivity: []
AmbientTemperature: []
Vectorized: 'off'
Label: []
thermalmodel = createpde("thermal","transient");
gm = importGeometry(thermalmodel,"Block.stl");
thermalBC(thermalmodel,"Face",[1,3],"HeatFlux",20)
ans =
ThermalBC with properties:
RegionType: 'Face'
RegionID: [1 3]
Temperature: []
HeatFlux: 20
ConvectionCoefficient: []
Emissivity: []
AmbientTemperature: []
Vectorized: 'off'
Label: []
thermalModel = createpde("thermal","transient");
gm = importGeometry(thermalModel,"Block.stl");
thermalBC(thermalModel,"Face",[2 4 5 6], ...
"ConvectionCoefficient",5, ...
"AmbientTemperature",27)
5-1538
thermalBC
ans =
ThermalBC with properties:
RegionType: 'Face'
RegionID: [2 4 5 6]
Temperature: []
HeatFlux: []
ConvectionCoefficient: 5
Emissivity: []
AmbientTemperature: 27
Vectorized: 'off'
Label: []
thermalmodel = createpde("thermal","transient");
gm = importGeometry(thermalmodel,"Block.stl");
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'
Label: []
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);
5-1539
5 Functions
figure
pdegplot(thermalmodel,"EdgeLabels","on");
xlim([-2 2]);
ylim([-2 2]);
title 'Rod Section Geometry with Edge Labels'
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)
ans =
ThermalBC with properties:
RegionType: 'Edge'
RegionID: 2
Temperature: 100
HeatFlux: []
ConvectionCoefficient: []
Emissivity: []
5-1540
thermalBC
AmbientTemperature: []
Vectorized: 'off'
Label: []
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'
Label: []
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.
leftHF = @(location,~) 5000*location.y;
thermalBC(thermalmodel,"Edge",4,"HeatFlux",leftHF)
ans =
ThermalBC with properties:
RegionType: 'Edge'
RegionID: 4
Temperature: []
HeatFlux: @(location,~)5000*location.y
ConvectionCoefficient: []
Emissivity: []
AmbientTemperature: []
Vectorized: 'off'
Label: []
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-1541
5 Functions
Geometric region ID, specified as a vector of positive integers. Find the region IDs by 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
Temperature boundary condition, specified as a number or a function handle. Use a function handle
to specify the temperature that depends on space and time. For details, see “More About” on page 5-
1543.
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 and time. For details, see “More About” on page 5-1543.
Example: thermalBC(thermalmodel,"Face",[1,3],"HeatFlux",20)
Data Types: double | function_handle
Convection to ambient boundary condition, specified as a number or a function handle. Use a function
handle to specify the convection coefficient that depends on space and time. For details, see “More
About” on page 5-1543.
5-1542
thermalBC
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 and time. For details, see “More About” on
page 5-1543.
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
Ambient temperature, specified as a number. The ambient temperature value is required for
specifying convection and radiation boundary conditions.
Example: thermalBC(thermalmodel,"Edge",
[2,4],"ConvectionCoefficient",5,"AmbientTemperature",60)
Data Types: double
Label for the thermal boundary condition, specified as a character vector or a string.
Data Types: char | string
Output Arguments
thermalBC — Handle to thermal boundary condition
ThermalBC object
Handle to thermal boundary condition, returned as a ThermalBC object. See ThermalBC Properties.
thermalBC associates the thermal boundary condition with the geometric region.
More About
Specifying Nonconstant Parameters of a Thermal Model
Use a function handle to specify these thermal parameters when they depend on space, temperature,
and time:
5-1543
5 Functions
For example, use function handles to specify the thermal conductivity, internal heat source,
convection coefficient, and initial temperature for this model.
thermalProperties(model,"ThermalConductivity", ...
@myfunConductivity)
internalHeatSource(model,"Face",2,@myfunHeatSource)
thermalBC(model,"Edge",[3,4], ...
"ConvectionCoefficient",@myfunBC, ...
"AmbientTemperature",27)
thermalIC(model,@myfunIC)
For all parameters, except the initial temperature, the function must be of the form:
The solver computes and populates the data in the location and state structure arrays and passes
this data to your function. You can define your function so that its output depends on this data. You
can use any names instead of location and state, but the function must have exactly two
arguments (or one argument if the function specifies the initial temperature).
Furthermore, for boundary conditions, the solver passes these data in the location structure:
5-1544
thermalBC
Thermal material properties (thermal conductivity, mass density, and specific heat) and internal heat
source get these data from the solver:
Boundary conditions (temperature on the boundary, heat flux, convection coefficient, and radiation
emissivity coefficient) get these data from the solver:
For all thermal parameters, except for thermal conductivity, your function must return a row vector
thermalVal with the number of columns equal to the number of evaluation points, for example, M =
length(location.y).
For thermal conductivity, your function must return a matrix thermalVal 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, for example, M =
length(location.y). For details about dimensions of the matrix, see “c Coefficient for
specifyCoefficients” on page 2-91.
If properties depend on the time or temperature, ensure that your function returns a matrix of NaN of
the correct size when state.u or state.time are NaN. Solvers check whether a problem is time
dependent by passing NaN state values and looking for returned NaN values.
To use additional arguments in your function, wrap your function (that takes additional arguments)
with an anonymous function that takes only the location and state arguments. For example:
thermalVal = ...
@(location,state) myfunWithAdditionalArgs(location,state,arg1,arg2...)
thermalBC(model,"Edge",3,"Temperature",thermalVal)
5-1545
5 Functions
Version History
Introduced in R2017a
R2021b: Label to extract sparse linear models for use with Control System Toolbox
Now you can add a label for thermal boundary conditions to be used by the linearizeInput
function. This function lets you pass thermal boundary conditions to the linearize function that
extracts sparse linear models for use with Control System Toolbox.
See Also
thermalProperties | internalHeatSource | thermalIC | applyBoundaryCondition |
ThermalBC Properties
Topics
“Heat Conduction in Multidomain Geometry with Nonuniform Heat Flux” on page 3-318
5-1546
thermalIC
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
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
5-1547
5 Functions
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])
thermalIC(thermalModel,0,"Face",1)
ans =
GeometricThermalICs with properties:
RegionType: 'face'
RegionID: 1
InitialTemperature: 0
thermalIC(thermalModel,10,"Face",2)
5-1548
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,
3
10 0 . 2 − y2 .
T0 = @(location)10^3*(0.2 - location.y.^2);
thermalIC(thermalmodel,T0)
ans =
GeometricThermalICs with properties:
RegionType: 'face'
RegionID: 1
InitialTemperature: @(location)10^3*(0.2-location.y.^2)
5-1549
5 Functions
Specify material properties and internal heat source, and set boundary conditions and initial
conditions.
thermalProperties(thermalmodel, ...
"ThermalConductivity",40,...
"MassDensity",7800,...
"SpecificHeat",500);
internalHeatSource(thermalmodel,2);
thermalBC(thermalmodel,"Edge",[1,3], ...
"Temperature",100);
thermalIC(thermalmodel,0);
generateMesh(thermalmodel);
tlist = 0:10:100;
result1 = solve(thermalmodel,tlist);
pdeplot(thermalmodel,"XYData",result1.Temperature(:,end))
5-1550
thermalIC
Now, resume the analysis and solve the problem for times from 100 to 1000 seconds. Use the
previously obtained solution for 100 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);
result2 = solve(thermalmodel,100:100:1000);
pdeplot(thermalmodel,"XYData",result2.Temperature(:,end))
5-1551
5 Functions
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 50
seconds, which is the 6th element in tlist.
tlist(6)
ans = 50
thermalIC(thermalmodel,result1,6);
result2 = solve(thermalmodel,50:100:1000);
pdeplot(thermalmodel,"XYData",result2.Temperature(:,end))
5-1552
thermalIC
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")
Initial temperature or initial guess for temperature, specified as a number or a function handle. Use a
function handle to specify spatially varying initial temperature. For details, see “More About” on page
5-1554.
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)
5-1553
5 Functions
Geometric region ID, specified as a vector of positive integers. Find the region IDs by using
pdegplot.
Example: thermalIC(thermalmodel,10,"Edge",2:5)
Data Types: double
iT — Time index
positive integer
Output Arguments
thermalIC — Handle to initial condition
GeometricThermalICs object | NodalThermalICs object
thermalIC associates the thermal initial condition with the geometric region in the case of a
geometric assignment, or the nodes in the case of a results-based assignment.
More About
Specifying Nonconstant Parameters of a Thermal Model
Use a function handle to specify these thermal parameters when they depend on space, temperature,
and time:
5-1554
thermalIC
For example, use function handles to specify the thermal conductivity, internal heat source,
convection coefficient, and initial temperature for this model.
thermalProperties(model,"ThermalConductivity", ...
@myfunConductivity)
internalHeatSource(model,"Face",2,@myfunHeatSource)
thermalBC(model,"Edge",[3,4], ...
"ConvectionCoefficient",@myfunBC, ...
"AmbientTemperature",27)
thermalIC(model,@myfunIC)
For all parameters, except the initial temperature, the function must be of the form:
The solver computes and populates the data in the location and state structure arrays and passes
this data to your function. You can define your function so that its output depends on this data. You
can use any names instead of location and state, but the function must have exactly two
arguments (or one argument if the function specifies the initial temperature).
Furthermore, for boundary conditions, the solver passes these data in the location structure:
5-1555
5 Functions
Thermal material properties (thermal conductivity, mass density, and specific heat) and internal heat
source get these data from the solver:
Boundary conditions (temperature on the boundary, heat flux, convection coefficient, and radiation
emissivity coefficient) get these data from the solver:
For all thermal parameters, except for thermal conductivity, your function must return a row vector
thermalVal with the number of columns equal to the number of evaluation points, for example, M =
length(location.y).
For thermal conductivity, your function must return a matrix thermalVal 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, for example, M =
length(location.y). For details about dimensions of the matrix, see “c Coefficient for
specifyCoefficients” on page 2-91.
If properties depend on the time or temperature, ensure that your function returns a matrix of NaN of
the correct size when state.u or state.time are NaN. Solvers check whether a problem is time
dependent by passing NaN state values and looking for returned NaN values.
To use additional arguments in your function, wrap your function (that takes additional arguments)
with an anonymous function that takes only the location and state arguments. For example:
thermalVal = ...
@(location,state) myfunWithAdditionalArgs(location,state,arg1,arg2...)
thermalBC(model,"Edge",3,"Temperature",thermalVal)
Version History
Introduced in R2017a
5-1556
thermalIC
See Also
thermalProperties | internalHeatSource | thermalBC | setInitialConditions |
GeometricThermalICs Properties | NodalThermalICs Properties
5-1557
5 Functions
tri2grid
(Not recommended) Interpolate from PDE triangular mesh to rectangular grid
Note tri2grid is not recommended. Use interpolateSolution instead. For more information,
see “Compatibility Considerations”.
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 interpolated function values uxy over the grid defined
by the vectors x and y using the function values u on the triangular mesh defined by p and t.
tri2grid uses linear interpolation in the triangle containing the grid point.
uxy = tri2grid(p,t,u,tn,a2,a3) uses the values tn, a2, and a3 returned by prior tri2grid
call using the previous syntax to interpolate u to the same grid as in the prior call. This syntax is
efficient for interpolating several functions to the same grid, such as interpolating hyperbolic or
parabolic solutions at multiple times.
Examples
Generate a triangular mesh of the L-shaped membrane. The geometry of the L-shaped membrane is
described in the file lshapeg.
[p,e,t] = initmesh('lshapeg');
u = assempde('lshapeb',p,e,t,1,0,1);
pdeplot(p,e,t,'XYData',u,'Mesh','on')
5-1558
tri2grid
Interpolate the solution to the rectangular grid defined by the vectors x and y.
x = -1:0.1:1;
y = x;
uxy = tri2grid(p,t,u,x,y);
surface(x,y,uxy)
5-1559
5 Functions
For comparison, plot the original solution and the rectangular grid.
[~,tn,a2,a3] = tri2grid(p,t,u,x,y);
pdeplot(p,e,t,'XYGrid','on','GridParam',[tn;a2;a3], ...
'XYData',u,'Mesh','on')
5-1560
tri2grid
Input Arguments
p — Mesh points
matrix
Mesh points, specified as a 2-by-Np matrix of points (nodes), where Np is the number of nodes in the
mesh. For details on mesh data representation, see initmesh.
Data Types: double
t — Mesh elements
4-by-Nt matrix
Mesh elements, specified as a 4-by-Nt matrix of triangles, where Nt is the number of triangles in the
mesh. For details on mesh data representation, see initmesh.
Data Types: double
u — PDE solution
vector
PDE solution, specified as a vector. For systems of equations, tri2grid interpolates only the first
component. For solutions returned by hyperbolic or parabolic, pass u as a vector of values at one
time, u(:,k).
5-1561
5 Functions
Output Arguments
uxy — Interpolated values
ny-by-nx matrix
Interpolated values, returned as an ny-by-nx matrix, where nx and ny are the lengths of the vectors x
and y, respectively.
tri2grid uses linear interpolation in the triangle containing the grid point. At grid points outside of
the triangular mesh, interpolated values are NaN.
Indices of triangles containing each grid point, returned as an ny-by-nx matrix, where nx and ny are
the lengths of the vectors x and y, respectively. At grid points outside of the triangular mesh, indices
of triangles are NaN.
a2 — Interpolation coefficient
ny-by-nx matrix
Interpolation coefficient, returned as an ny-by-nx matrix, where nx and ny are the lengths of the
vectors x and y, respectively. At grid points outside of the triangular mesh, values of the interpolation
coefficients are NaN.
a3 — Interpolation coefficient
ny-by-nx matrix
Interpolation coefficient, returned as an ny-by-nx matrix, where nx and ny are the lengths of the
vectors x and y, respectively. At grid points outside of the triangular mesh, values of the interpolation
coefficients are NaN.
Version History
Introduced before R2006a
tri2grid is not recommended. Use interpolateSolution instead. There are no plans to remove
tri2grid.
5-1562
tri2grid
See Also
solvepde | interpolateSolution
5-1563
5 Functions
triangulation
Create triangulation object from fegeometry
Syntax
TR = triangulation(gm)
Description
TR = triangulation(gm) creates a triangulation object from the specified fegeometry
object. The geometry must have one cell in 3-D or one face in 2-D.
Examples
2-D Triangulation
gm =
fegeometry with properties:
NumFaces: 1
NumEdges: 4
NumVertices: 4
NumCells: 0
Vertices: [4x2 double]
Mesh: []
TR =
triangulation with properties:
3-D Triangulation
5-1564
triangulation
gm = fegeometry(multicylinder(5,2))
gm =
fegeometry with properties:
NumFaces: 3
NumEdges: 2
NumVertices: 2
NumCells: 1
Vertices: [2x3 double]
Mesh: []
TR = triangulation(gm)
TR =
triangulation with properties:
Input Arguments
gm — Single-domain geometry
fegeometry object
Single-domain geometry, specified as an fegeometry object. If you specify a 2-D geometry, it must
have one face. If you specify a 3-D geometry, it must have one cell.
Output Arguments
TR — Triangulation
triangulation object
Version History
Introduced in R2023b
See Also
femodel | fegeometry | triangulation
5-1565
5 Functions
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.
[V,VE] = volume(mesh) also returns a row vector VE containing volumes of each individual
element of the mesh.
V = volume(mesh,elements) returns the combined volume of the specified elements of the mesh.
Examples
model = createpde;
importGeometry(model,"BracketWithHole.stl");
pdegplot(model)
5-1566
volume
mesh = generateMesh(model);
figure
pdemesh(model)
5-1567
5 Functions
mv = volume(mesh)
mv = 8.0244e-04
model = createpde;
importGeometry(model,"BracketWithHole.stl");
pdegplot(model)
5-1568
volume
mesh = generateMesh(model);
figure
pdemesh(model)
5-1569
5 Functions
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 ×
model = createpde;
importGeometry(model,"BracketWithHole.stl");
pdegplot(model)
5-1570
volume
mesh = generateMesh(model);
figure
pdemesh(model)
5-1571
5 Functions
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 = volume(mesh,elemIDs)
mv05 = 7.9638e-07
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.0992
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.
5-1572
volume
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.
Version History
Introduced in R2018a
See Also
area | findElements | findNodes | meshQuality | FEMesh Properties
Topics
“Finite Element Method Basics” on page 1-11
5-1573
5 Functions
wbound
(Not recommended) Write boundary condition file
Syntax
fid = wbound(b,filename)
Description
fid = wbound(b,filename) writes a boundary function, specified by the boundary condition
matrix b, to a file with the name filename.m.
Examples
Create a 2-D geometry and specify boundary conditions in the PDE Modeler app, export them to the
MATLAB workspace, and then write the boundary conditions to a file.
Start the PDE Modeler app and draw a unit circle and a unit square.
pdecirc(0,0,1)
pderect([0 1 0 1])
Use the default Dirichlet boundary condition u = 0 for all boundaries. To verify the boundary
condition, 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.
Export the geometry and the boundary conditions to the MATLAB workspace by selecting the Export
Decomposed Geometry, Boundary Cond's option from the Boundary 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.
Write the resulting boundary condition matrix to a file. Name the file boundary.m.
fid = wbound(b,"boundary");
Input Arguments
b — Boundary conditions
boundary matrix
5-1574
wbound
Boundary conditions, specified as a boundary matrix. Typically, you export a boundary matrix from
the PDE Modeler app.
Data Types: double
Output Arguments
fid — File identifier
integer | -1
File identifier, returned as an integer. If wbound cannot write the file, fid is -1. For more information
about file identifiers, see fopen.
Version History
Introduced before R2006a
wbound is not recommended. Use applyBoundaryCondition instead. There are no plans to remove
wbound.
See Also
decsg | wgeom
5-1575
5 Functions
wgeom
Write geometry function to file
Note This page describes the legacy workflow. New features might not be compatible with the legacy
workflow.
Syntax
fid = wgeom(dl,filename)
Description
fid = wgeom(dl,filename) writes a geometry function, specified by the geometry matrix dl, to a
file with the name filename.m. For information about the geometry file format, see “Parametrized
Function for 2-D Geometry Creation” on page 2-23.
Examples
Create a 2-D geometry in the PDE Modeler app, export it to the MATLAB workspace, and then write it
to a file.
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
5-1576
wgeom
fid = wgeom(dl,"geometry");
Input 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.
Row number Circle edge segment Line edge segment Ellipse edge segment
1 1 2 4
2 starting x-coordinate starting x-coordinate starting x-coordinate
3 ending x-coordinate ending x-coordinate ending x-coordinate
4 starting y-coordinate starting y-coordinate starting y-coordinate
5 ending y-coordinate ending y-coordinate ending y-coordinate
6 left minimal region label left minimal region label left minimal region label
7 right minimal region right minimal region right minimal region
label label label
8 x-coordinate of the x-coordinate of the
center center
9 y-coordinate of the y-coordinate of the
center center
10 radius of the circle x-semiaxis before
rotation
11 y-semiaxis before
rotation
5-1577
5 Functions
Row number Circle edge segment Line edge segment Ellipse edge segment
12 Angle in radians
between x-axis and first
semiaxis
Output Arguments
fid — File identifier
integer | -1
File identifier, returned as an integer. If wgeom cannot write the file, fid is -1. For more information
about file identifiers, see fopen.
Version History
Introduced before R2006a
See Also
decsg | wbound
5-1578