Specify Nonconstant PDE Coefficients
When solving PDEs with nonconstant coefficients, specify these coefficients by using function handles. This example shows how to write functions to represent nonconstant coefficients for PDE problems.
Geometry and Mesh
Create a model.
model = createpde;
Include a unit square geometry in the model.
Generate a mesh with a maximum edge length of 0.25. Plot the mesh.
Function for Nonconstant Coefficient f
Write a function that returns the value for the nonconstant coefficient f. The function
must accept two input arguments,
state. The solvers automatically compute and populate the data in
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.
function fcoeff = fcoefffunc(location,state) fcoeff = location.x.^2.*sin(location.y); scatter(location.x,location.y,".","black"); hold on end
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.
Solve the equation and plot the solution.
results = solvepde(model); figure pdeplot(model,"XYData",results.NodalSolution)
Anonymous Function for a PDE Coefficient
If the dependency of a coefficient on coordinates, time, or solution is simple, you
can use an anonymous function to represent the nonconstant PDE coefficient. Thus, you
can implement the dependency shown earlier in this example as the
fcoefffunc function, as this anonymous function.
f = @(location,state)location.x.^2.*sin(location.y);
Specify the PDE coefficients.
specifyCoefficients(model,"m",0, ... "d",0, ... "c",1, ... "a",0, ... "f",f);
If a function that represents a nonconstant PDE coefficient requires more arguments
state, follow these
Write a function that takes the
statearguments and the additional arguments.
Wrap that function with an anonymous function that takes only the
For example, define the coefficient f as . First, write the function that takes the arguments
c in addition to
function fcoeff = fcoefffunc_abc(location,state,a,b,c) fcoeff = a*location.x.^2.*sin(b*location.y) + c; end
Because functions defining nonconstant coefficients must have exactly two arguments,
fcoefffunc_abc function with an anonymous function.
fcoefffunc_add_args = ... @(location,state) fcoefffunc_abc(location,state,1,2,3);
Now you can use
fcoefffunc_add_args to specify the coefficient
specifyCoefficients(model,"m",0, ... "d",0, ... "c",1, ... "a",0, ... "f",fcoefffunc_add_args);