Live Link Format Lab Users Guide
Live Link Format Lab Users Guide
for Matlab
Users Guide
VERSION 4.4
TM
November 2013
COMSOL 4.4
Contact Information
Visit the Contact COMSOL page at www.comsol.com/contact to submit general
inquiries, contact Technical Support, or search for an address and phone number. You can
also visit the Worldwide Sales Offices page at www.comsol.com/contact/offices for
address and contact information.
If you need to contact Support, an online request form is located at the COMSOL Access
page at www.comsol.com/support/case.
Other useful links include:
Support Center: www.comsol.com/support
Product Download: www.comsol.com/support/download
Product Updates: www.comsol.com/support/updates
COMSOL Community: www.comsol.com/community
Events: www.comsol.com/events
COMSOL Video Center: www.comsol.com/video
Support Knowledge Base: www.comsol.com/support/knowledgebase
Part number: CM020008
C o n t e n t s
Chapter 1: Introduction
About LiveLink for MATLAB
Getting Help . . . . . . . . . . . . . . . . . . . . . . . . . 9
Where Do I Access the Documentation and the Model Libraries?
. . . . 10
16
17
21
24
31
. . . . . . . . . . . . . . . . 42
52
81
91
. . . . . . . . . . . . . . . . . . 92
100
106
4 |
CHAPTER :
C h a p t e r 4 : Wo r k i n g W i t h M o d e l s
Using MATLAB Variables in Model Settings
116
119
142
. . . . . . . . . . . . . . . . . 142
145
147
160
167
170
177
179
. . . . . . . . . . . . . . . . . 181
182
183
186
6 |
CHAPTER :
Summary of Commands
196
197
Introduction
This guide introduces you to LiveLink for MATLAB, which extends your
COMSOL modeling environment with an interface between COMSOL
Multiphysics and MATLAB. The COMSOL API Reference Manual provides
additional documentation of the API.
In this chapter:
About LiveLink for MATLAB
Help and Documentation
8 |
CHAPTER 1: INTRODUCTION
He lp a nd Do c u men t at i on
In this section:
Getting Help
Where Do I Access the Documentation and the Model Libraries?
Getting Help
COMSOL Multiphysics and LiveLink for MATLAB have several sources of help and
information.
T H E I N T RO D U C T I O N T O L I VE L I N K F O R M AT L A B
To get started with LiveLink for MATLAB, it is recommended that you read the
Introduction to LiveLink for MATLAB. It contains detailed examples about how
to get you started with the product.
ONLINE DOCUMENTATION AND OTHER RESOURCES
Save models as an M-file. Use the COMSOL Desktop to get your first model
implemented using the COMSOL API.
Set up the model using the graphical user interface, then save the model as an M-file.
Next go to the File menu and select Save, in the Save window locate Save as type list
and select Model file for MATLAB (*.m). This generates an M-function that can be run
using COMSOL with MATLAB.
THE MODEL LIBRARIES WINDOW
Study the LiveLink for MATLAB model library. LiveLink for MATLAB includes
a model library with detailed example models. Use the function mphmodellibrary at
the command line to get a list of available models. The following are some models that
can help get you started.
Model Examples
Learn how to activate and deactivate domains alternatively during a transient
analysis. See the model Domain Activation and Deactivation (model name
domain_activation_llmatlab).
Homogenization in a Chemical Reactor (model name
homogenization_llmatlab) shows how to simulate a periodic homogenization
process in a space-dependent chemical reactor model. This homogenization
removes concentration gradients in the reactor at a set time interval.
Convective Heat Transfer with Pseudo-Periodicity (model name
pseudoperiodicity_llmatlab) simulates convective heat transfer in a channel
filled with water. To reduce memory requirements, the model is solved repeatedly
on a pseudo-periodic section of the channel. Each solution corresponds to a
different section, and before each solution step the temperature at the outlet
boundary from the previous solution is mapped to the inlet boundary.
Temperature Distribution in a Vacuum Flask (model name
vacuum_flask_llmatlab) shows how to use the MATLAB function callback. This
example solves for the temperature distribution inside a vacuum flask with hot
coffee.
Electrical Heating of a Busbar Solved with LiveLink for SolidWorks and
LiveLink for MATLAB (model name busbar_llsw_llmatlab) performs
geometry optimization using COMSOL Multiphysics, MATLAB, and
SolidWorks.
10 |
CHAPTER 1: INTRODUCTION
context-based) help, and the Model Libraries are all accessed through the COMSOL
Desktop.
If you are reading the documentation as a PDF file on your computer, the
blue links do not work to open a model or content referenced in a
different guide. However, if you are using the Help system in COMSOL
Multiphysics, these links work to other modules (as long as you have a
license), model examples, and documentation sets.
THE DOCUMENTATION AND ONLINE HELP
The COMSOL Multiphysics Reference Manual describes all core physics interfaces
and functionality included with the COMSOL Multiphysics license. This book also has
instructions about how to use COMSOL and how to access the electronic
Documentation and Help content.
).
) button.
11
).
) button.
Each model includes documentation that has the theoretical background and
step-by-step instructions to create the model. The models are available in COMSOL
as MPH-files that you can open for further investigation. You can use the step-by-step
instructions and the actual models as a template for your own modeling and
applications. In most models, SI units are used to describe the relevant properties,
parameters, and dimensions in most examples, but other unit systems are available.
Once the Model Libraries window is opened, you can search by model name or browse
under a module folder name. Click to highlight any model of interest and a summary
of the model and its properties is displayed, including options to open the model or a
PDF document.
12 |
CHAPTER 1: INTRODUCTION
):
) Model Libraries.
button.
COMSOL website
www.comsol.com
Contact COMSOL
www.comsol.com/contact
Support Center
www.comsol.com/support
Product Download
www.comsol.com/product/download
Product Updates
www.comsol.com/support/updates
COMSOL Community
www.comsol.com/community
Events
www.comsol.com/events
www.comsol.com/video
www.comsol.com/support/knowledgebase
13
14 |
CHAPTER 1: INTRODUCTION
Getting Started
In this chapter:
The Client-Server Architecture
Running COMSOL with MATLAB
Calling a MATLAB Function from the COMSOL Desktop
15
You provide login information the first time COMSOL is started with MATLAB. This
information is stored in the user preferences file and is not required again when using
COMSOL with MATLAB. The same login information can be used when exchanging
the model object between the COMSOL server and the COMSOL Desktop.
The communication between the COMSOL server and MATLAB is established by
default using port number 2036. If this port is in use, port number 2037 is used
instead, and so on.
You can manually specify the port number. See the COMSOL
Installation Guide for more information on the COMSOL server
start-up properties.
The links to features described outside of this user guide do not work in
the PDF, only from the online help.
16 |
The first time COMSOL with MATLAB is started, login and password
information is requested to establish the client/server connection. The
information is saved in the user preference file and is not required again.
R U N N I N G C O M S O L W I T H M AT L A B
17
To reset the login information, add the flag -login force to the icon
target path.
To be able to manipulate the model object and extract data at the MATLAB prompt,
you need to modify the Java heap size in MATLAB. See Improving Performance for
18 |
Large Models.
CON N ECT IN G MATLA B AN D TH E C OM SO L SE R VE R O N DI FF EREN T
COMPUTERS
To connect MATLAB and a COMSOL server that are running on different computers,
specify the IP address of the computer where the COMSOL server is running in the
function mphstart:
mphstart(<ipaddress>, <portnumber>)
<ipaddress> can also be defined with the server domain name.
The command above assume that the same user login information are set on the server
and client machine. In case the login information are not accessible from the client
machine, specify manually the user name and password to the COMSOL server with
the command:
mphstart(<ipaddress>, <portnumber>, <username>, <password>)
Once MATLAB and the COMSOL server are manually connected, import the
COMSOL class by entering the following command at the MATLAB prompt:
import com.comsol.model.*
import com.comsol.model.util.*
R U N N I N G C O M S O L W I T H M AT L A B
19
).
otherwise the specified MATLAB version does not start when calling external
MATLAB functions from the COMSOL model.
5 Click OK.
6 To update the preferences file, close and reopen the COMSOL Desktop.
20 |
C A L L I N G A M AT L A B F U N C T I O N F R O M T H E C O M S O L D E S K T O P
21
22 |
Building Models
This chapter gives an overview of the model object and provides an introduction
to building models using the LiveLink interface.
In this chapter:
The Model Object
Working with Geometry
Working with Meshes
Modeling Physics
Creating Selections
Computing the Solution
Analyzing the Results
23
The Model Object in the COMSOL API for use with Java Reference
Manual.
24 |
The links to features described outside of this user guide do not work in
the PDF, only from the online help.
Use the method ModelUtil.create to create a new model object in the COMSOL
server:
model = ModelUtil.create('Model');
This command creates a model object Model on the COMSOL server and a MATLAB
object model that is linked to the model object.
It is possible to have several model objects on the COMSOL server, each with a
different name. To access each model object requires different MATLAB variables
linked to them and each MATLAB variable must have a different name.
Create a MATLAB variable linked to an existing model object with the method
ModelUtil.model. For example, to create a MATLAB variable model that is linked to
the existing model object Model on the COMSOL server, enter the command:
model = ModelUtil.model('Model');
25
To remove a specific model object use the method ModelUtil.remove. For example,
to remove the model object Model from the COMSOL server enter the command:
ModelUtil.remove('Model');
Alternatively remove all the COMSOL objects stored in the COMSOL server with the
command:
ModelUtil.clear
List the names of the model objects available on the COMSOL server with the
command:
list = ModelUtil.tags
ACTIVATING THE PROGRESS BAR
26 |
The model history is automatically enabled when the model is created in the
COMSOL Desktop. It is however possible disable manually the model history
recording from the MATLAB prompt with the command:
model.hist.disable;
To clean the M-file for the model so that it contains only the settings that are part of
the current model you need to compact the model history before saving the model as
an M-file.
To compact the model history in the COMSOL Desktop, from File menu (Windows
).
users) or from the toolbar (Mac and Linux users), select Compact History (
To compact the model history at the MATLAB prompt enter the command:
model.resetHist;
To load an existing model saved as an MPH-file use the function mphload. For
example, to load the Busbar model from the COMSOL Multiphysics model library
enter:
model = mphload('busbar.mph');
This creates a model object Model on the COMSOL server that is accessible using the
MATLAB variable model. If there is already a model object Model linked to a
MATLAB variable model, load the model using a different name with the command:
model2 = mphload('busbar.mph','Model2');
When using the function mphload, the model history is automatically disabled to
prevent large history information when running a model in a loop. To turn model
history on, use the function mphload:
27
model = mphload('busbar.mph','-history');
The history recording can be useful when using the COMSOL Desktop.
All the operations are then stored in the saved M-file.
mphload does not look for lock file when loading the model.
SAVING A MODEL
Use the function mphsave to save the model object linked to the MATLAB object
model:
mphsave(model,'filename')
If the filename specified 'filename' does not provide a path, the file is saved relative
to the local MATLAB path. The file extension determines the format to use (*.mph,
*.m, or *.java).
Alternatively, use the save method:
model.save('filename');
If 'filename' does not provide a path, the file is saved relative to the local COMSOL
server path.
Any files saved in the MPH format can be loaded by the COMSOL Desktop. In
addition, the model can be saved as an M-file:
model.save('model_name','m');
mphsave does not look for lock file when saving the model.
28 |
Sharing the model between the COMSOL Desktop and the MATLAB
prompt
It is possible to connect a COMSOL Desktop to the COMSOL server that is already
connected with MATLAB and then access the model from both client (the COMSOL
Desktop and MATLAB). The change performed from either client are directly
accessible from the other one, for instance type a command at the MATLAB prompt
and see the resulting modification in the Model Builder window or extract data at the
MATLAB prompt from a model set up in the COMSOL Desktop.
Connect the COMSOL Desktop to a COMSOL server using the Connect to Server
dialog box:
1 From the File (Windows users) or Options menu (Mac and Linux users), select Client
Server>Connect to Server (
).
2 In the Connect to Server window, you specify the server configuration and the user
settings. In the Server section enter the server name (the default name is
localhost) and the Port number (the default is 2036). This number corresponds
to the port that the COMSOL server is listening to, the number is displayed at the
COMSOL server window.
3 In the User section enter a Username and a Password (if they are empty); these are
defined the first time you are connected to the COMSOL server.
4 Click OK.
29
The first time you connect the COMSOL Desktop to the COMSOL
server no model is loaded to the GUI. See Import A Model from the
COMSOL Server to the COMSOL GUI to know how connect the GUI
to a model loaded in the COMSOL server.
IMPOR T A MODEL FROM THE COMSOL SER VER TO THE COMSOL GUI
Once you have the COMSOL Desktop connected to the COMSOL server you can
import the model in the GUI:
1 From the File (Windows users) or Options menu (Mac and Linux users), select Client
Server>Import Model from Server (
).
2 In the Import Model from Server window, specify the model you want to import.
I M P O R T A M O D E L F RO M T H E C O M S O L S E R VE R T O M AT L A B
To access a model stored in the COMSOL server from the MATLAB prompt enter the
command:
model = ModelUtil.model(<ModelName>);
where model is the link in MATLAB to the model stored on the COMSOL server,
<ModelName> the name of the model stored in the COMSOL Model.
You can get the list of the model stored in the COMSOL server with the command:
ModelUtil.tags
Where <time> is the time in second to wait the server to be free again.
30 |
The links to features described outside of this user guide do not work in
the PDF, only from the online help.
where <geomtag> is a string used to refer to the geometry. The integer sdim specifies
the space dimension of the geometry and it can be either 0, 1, 2, or 3.
To add an operation to a geometry sequence, use the syntax:
WO R K I N G W I T H G E O M E T R Y
31
model.geom(<geomtag>).feature.create(<ftag>, operation);
where <geomtag> is the string defined when the geometry is created. The string
<ftag> is used to refer to the operation.
To set the feature property with different values than the default, use the set method:
model.geom(<geomtag>).feature(<ftag>).set(property, <value>);
When running mphgeom the geometry node is automatically built. Set the build
property to specify how the geometry node is supposed to be built before displaying
it. Enter:
mphgeom(model, <geomtag>, 'build', build);
where build is a string with the value: 'off', 'current', or the geometry feature tag
<ftag>, which, respectively, does not build the geometry (off), builds the geometry
up to the current feature (current), or builds the geometry up to the specified
geometry feature node (ftag).
Use the parent property to specify the axes handle where to display the plot:
mphgeom(model, <geomtag>, 'parent', <axes>);
32 |
The following properties are also available to specify the vertex, edge, or face
rendering:
edgecolor
facelabelscolor
edgelabels
facemode
edgelabelscolor
vertexlabels
edgemode
vertexlabelscolor
facealpha
vertexmode
facelabels
Use mphgeom to display a specified geometry entity. To set the geometry entity, enter
the entity property and set the geometry entity index in the selection property to:
mphgeom(model, <geomtag>, 'entity', entity, 'selection', <idx>);
where entity can be either 'point', 'edge', 'boundary', or 'domain', and <idx>
is a positive integer array that contains the list of the geometry entity indices.
CREATING A 1D GEOMETRY
WO R K I N G W I T H G E O M E T R Y
33
model = ModelUtil.create('Model');
34 |
model = ModelUtil.create('Model');
geom2 = model.geom.create('geom2',2);
Continue by creating a rectangle with side length of 2 and centered at the origin:
sq1 = geom2.feature.create('sq1','Square');
sq1.set('size',2);
sq1.set('base','center');
The property size describes the side lengths of the rectangle and the property pos
describes the positioning. The default is to position the rectangle about its lower left
corner. Use the property base to control the positioning.
Create a circular hole with a radius of 0.5 centered at (0, 0):
c1 = geom2.feature.create('c1','Circle');
c1.set('r',0.5);
c1.set('pos',[0 0]);
The property r describes the radius of the circle, and the property pos describes the
positioning.
The property pos could have been excluded because the default position
is the origin. The default is to position the circle about its center.
Drill a hole in the rectangle by subtracting the circle from it:
co1 = geom2.feature.create('co1','Compose');
co1.selection('input').set({'c1' 'sq1'});
co1.set('formula','sq1-c1');
A selection object is used to refer to the input object. The operators +, *, and correspond to the set operations union, intersection, and difference, respectively.
The Compose operation allows you to work with a formula. Alternatively use the
Difference operation instead of Compose. The following sequence of commands
starts with disabling the Compose operation:
co1.active(false)
dif1 = geom2.feature.create('dif1','Difference');
dif1.selection('input').set({'sq1'});
dif1.selection('input2').set({'c1'});
Run the geometry sequence to create the geometry and plot the result:
geom2.run;
WO R K I N G W I T H G E O M E T R Y
35
mphgeom(model,'geom2');
Trimming Solids
Continue with rounding the corners of the rectangle with the Fillet operation:
fil1 = geom2.feature.create('fil1','Fillet');
fil1.selection('point').set('dif1', [1 2 7 8]);
fil1.set('radius','0.5');
The geometry sequence is updated with rounded corners. To view the result, enter:
mphgeom(model,'geom2');
36 |
Use the following commands to create six open curve segments that together form a
closed curve:
model = ModelUtil.create('Model');
g1 = model.geom.create('g1',2);
w=1/sqrt(2);
c1 = g1.feature.create('c1','BezierPolygon');
c1.set('type','open');
c1.set('degree',2);
c1.set('p',[-0.5 -1 -1;-0.5 -0.5 0]);
c1.set('w',[1 w 1]);
c2 = g1.feature.create('c2','BezierPolygon');
c2.set('type','open');
c2.set('degree',2);
c2.set('p',[-1 -1 -0.5;0 0.5 0.5]);
c2.set('w',[1 w 1]);
c3 = g1.feature.create('c3','BezierPolygon');
c3.set('type','open');
c3.set('degree',1);
c3.set('p',[-0.5 0.5; 0.5 0.5]);
c4 = g1.feature.create('c4','BezierPolygon');
c4.set('type','open');
c4.set('degree',2);
WO R K I N G W I T H G E O M E T R Y
37
The objects c1, c2, c3, c4, c5, and c6 are all curve2 objects. The vector [1 w 1]
specifies the weights for a rational Bzier curve that is equivalent to a quarter-circle arc.
The weights can be adjusted to create elliptical or circular arcs.
Convert the curve segments to a solid with the following conversion command:
csol1 = g1.feature.create('csol1','ConvertToSolid');
csol1.selection('input').set({'c1' 'c2' 'c3' 'c4' 'c5' 'c6'});
This section shows how to create 3D solids using workplanes and Boolean operations.
Create a 3D geometry with an xy work plane at z = 0:
38 |
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 3);
wp1 = geom1.feature.create('wp1', 'WorkPlane');
wp1.set('planetype', 'quick');
wp1.set('quickplane', 'xy');
Add a rectangle to the work plane, then add fillet to its corners:
r1 = wp1.geom.feature.create('r1', 'Rectangle');
r1.set('size',[1 2]);
geom1.run
fil1 = wp1.geom.feature.create('fil1', 'Fillet');
fil1.selection('point').set('r1', [1 2 3 4]);
fil1.set('radius', '0.125');
geom1.runCurrent;
ext1 = geom1.feature.create('ext1', 'Extrude');
ext1.set('distance', '0.1');
WO R K I N G W I T H G E O M E T R Y
39
40 |
A natural choice for storing geometries in 1D, 2D, and 3D is the native file format of
COMSOLs geometry kernel (.mphtxt and .mphbin).
The .mphtxt or .mphbin file formats are only used for geometry and
mesh objects. It is not the same as a Model MPH-file (.mph).
2D CAD FORMATS
COMSOL Multiphysics supports import and export for the DXF file format, a data
interchange format of the CAD system AutoCAD . Files can also be imported using
the neutral GDS format. The ECAD geometry file format requires either the AC/DC
Module, MEMS Module, or the RF Module.
See the ECAD Import Module Users Guide or go to
http://www.comsol.com/comsol-multiphysics/ for more information
about this and other products.
3D CAD FORMATS
It is possible to import surface meshes in the STL and VRML formats. With a license
for the CAD Import Module, or one of the LiveLink for CAD products, you can
import most 3D CAD file formats: Parasolid, ACIS (SAT), STEP, IGES,
Pro/ENGINEER, Autodesk Inventor, and SolidWorks . See the specific product
documentation for detailed information.
WO R K I N G W I T H G E O M E T R Y
41
The model object contains general geometry information methods. For example, to
determine the space dimension of the geometry, enter:
geom1.getSDim
There are also methods to determine the number of geometrical entities. For example,
to inquire about the number of domains and the number of boundaries:
geom1.getNDomains
geom1.getNBoundaries
42 |
There are also methods for evaluating properties such as coordinate values and
curvatures on faces and edges. For example, to evaluate coordinates on face 1 for the
face parameters (2, 0.005), enter:
geom1.faceX(1,[2,0.005])
To get the parameters of a given face, use the method faceParamRange(N), where N
is the face number. For example:
geom1.faceParamRange(1)
To get the coordinate and the curvature data along a specified edge, enter:
geom1.edgeX(2,0.5)
geom1.edgeCurvature(2,0.5)
There are also methods for getting information about the internal representation of
the geometry. For example, the coordinates of the geometry vertices:
geom1.getVertexCoord
WO R K I N G W I T H G E O M E T R Y
43
r1 = geom1.feature.create('r1','Rectangle');
r1.set('size',[0.5 1]);
r1.set('pos',[0 0]);
r2 = geom1.feature.create('r2','Rectangle');
r2.set('size',[0.6 1]);
r2.set('pos',[0.5 0]);
c1 = geom1.feature.create('c1','Circle');
c1.set('r',0.1);
c1.set('pos',{'a','0.5'});
mphgeom(model);
44 |
Create a mesh:
model.mesh.create('mesh1', 'geom1');
WO R K I N G W I T H G E O M E T R Y
45
p1.run;
Alternatively, you can run the parametric sweep using a MATLAB for loop:
for a=0.2:0.1:0.8
model.param.set('a',a);
std1.run;
end
Use the interpolation spline feature to import a set of data points that describe a 2D
geometry. To create an interpolation spline feature, enter:
model.geom(<geomtag>).feature.create(<ftag>,'InterpolationCurve')
where type can either be 'solid' to generate a solid object, 'closed' to generate a
closed curve or 'open' to generate an open curve.
the points:
46 |
phi = 0:0.2:2*pi;
phi([1 3 6 7 10 20 21 25 28 32]) = [];
p = [cos(phi);sin(phi)];
WO R K I N G W I T H G E O M E T R Y
47
Use the function mphimage2geom to create geometry from image data. The image data
format can be M-by-N array for a grayscale image or M-by-N-by-3 array for a true
color image. This section also includes an example (see Example: Convert Image Data
to Geometry).
See the MATLAB function imread to convert an image file to image data.
If you specify the image data and the level value that represents the geometry contour
you want to extract, the function mphimage2geom returns a model object with the
desired geometry:
model = mphimage2geom(<imagedata>, <level>)
where imagedata is a C array containing the image data and level is the contour level
value used to generate the geometry contour.
Specify the type of geometry object generated:
model = mphimage2geom(<imagedata>, <level>, 'type', type)
where type is 'solid' and generates a solid object, 'closed' generates a closed
curve object, or 'open' generates an open curve geometry object.
Use the property curvetype to specify the type of curve used to generate the
geometry object:
model = mphimage2geom(<imagedata>, <level>, 'curvetype', curvetype)
where curvetype can be set to 'polygon' to use a polygon curve. The default curve
type creates a geometry with the best suited geometrical primitives. For interior curves
it uses interpolation curves, while for curves that are touching the perimeter of the
image a polygon curve is used.
To scale the geometry use the scale property where scale is a double value:
model = mphimage2geom(<imagedata>, <level>, 'scale', scale)
Set the minimum distance between coordinates in curve with the mindist property
where mindist is a double value:
model = mphimage2geom(<imagedata>, <level>, 'mindist', mindist)
Set the minimum area for interior curves where minarea is a double value:
48 |
To create a rectangle domain surrounding the object generated use the property
rectangle:
model = mphimage2geom(<imagedata>, <level>, 'rectangle', 'on')
Use the property type to create closed or open curves. For example, to create a
geometry following contour 40 with closed curves, enter:
model = mphimage2geom(p, 40, 'type', 'closed');
WO R K I N G W I T H G E O M E T R Y
49
mphgeom(model)
To scale the geometry, use the scale property. Using the current model scale the
geometry with a factor of 0.001 (1e-3):
model = mphimage2geom(p, 40, 'scale', 1e-3);
mphgeom(model)
To insert a rectangle in the geometry that has an outer domain surrounding the
created contour, set the property rectangle to on:
model = mphimage2geom(p, 40, 'rectangle', 'on');
mphgeom(model)
50 |
WO R K I N G W I T H G E O M E T R Y
51
The links to features described outside of this user guide do not work in
the PDF, only from the online help.
where <meshtag> is a string that you use to refer to the sequence. The tag geomtag
specifies the geometry to use for this mesh node.
To add an operation to a sequence, use the syntax:
model.mesh(<meshtag>).feature.create(<ftag>, operation);
where the string <ftag> is a string that you use to refer to the operation.
52 |
If there are several meshes in a model, specify the mesh to display using the command:
mphmesh(model, <meshtag>);
Use the parent property to specify the axes handle where to display the plot:
mphmesh(model, <meshtag>, 'parent', <axes>);
The following properties are also available to specify the vertex, edge, or face
rendering:
edgecolor
facelabelscolor
edgelabels
facemode
edgelabelscolor
meshcolor
edgemode
vertexlabels
facealpha
vertexlabelscolor
facelabels
vertexmode
WO R K I N G W I T H M E S H E S
53
The Size attribute provides a number of input properties that can control the mesh
element size, such as the following properties:
Maximum and minimum element size
Element growth rate
Curvature factor
Resolution of narrow regions
These properties are available both globally and locally. The following examples are
included: Example: Creating a 2D Mesh with Triangular Elements and Example:
Creating a 2D Mesh with Quadrilateral Elements. Also discussed is The Free Meshing
Method.
54 |
There are several predefined settings that can be used to set a suitable combination of
values for many properties. To select one of these settings, use the property hauto and
pass an integer from 1 to 9 as its value to describe the mesh resolution:
Extremely fine (1)
Coarse (6)
Coarser (7)
Finer (3)
Fine (4)
For details about predefined mesh size settings and mesh element size
parameters, see Size in the COMSOL API Reference Manual.
WO R K I N G W I T H M E S H E S
55
To override this behavior, set hauto to another integer. Override this by setting
specific size properties, for example, making the mesh finer than the default by
specifying a maximum element size of 0.02:
mesh1.feature('size').set('hmax','0.02');
mesh1.run;
mphmesh(model);
56 |
This value corresponds to 1/50 of the largest axis-parallel distance, whereas the default
value is 1/15.
WO R K I N G W I T H M E S H E S
57
58 |
WO R K I N G W I T H M E S H E S
59
To create a structured quadrilateral mesh in 2D, use the Map operation. This operation
uses a mapping technique to create the quadrilateral mesh.
Use the EdgeGroup attribute to group the edges (boundaries) into four edge groups,
one for each edge of the logical mesh. To control the edge element distribution use
the Distribution attribute, which determines the overall mesh density.
60 |
dif1.selection('input2').set({'c1'});
geom1.run('dif1');
mesh1 = model.mesh.create('mesh1','geom1');
map1 = mesh1.feature.create('map1','Map');
eg1 = map1.feature.create('eg1', 'EdgeGroup');
eg1.selection.set(1);
eg1.selection('edge1').set([1 3]);
eg1.selection('edge2').set(2);
eg1.selection('edge3').set(8);
eg1.selection('edge4').set(4);
eg2 = map1.feature.create('eg2', 'EdgeGroup');
eg2.selection.set(2);
eg2.selection('edge1').set(4);
eg2.selection('edge2').set([6 9 10]);
eg2.selection('edge3').set(7);
eg2.selection('edge4').set(5);
mesh1.run;
mphmesh(model);
Figure 3-6: Structured quadrilateral mesh (right) and its underlying geometry.
The left-hand side plot in Figure 3-6 is obtained with this command:
mphgeom(model, 'geom1', 'edgelabels','on')
The EdgeGroup attributes specify that the four edges enclosing domain 1 are
boundaries 1 and 3; boundary 2; boundary 8; and boundary 4. For domain 2 the four
edges are boundary 4; boundary 5; boundary 7; and boundaries 9, 10, and 6.
WO R K I N G W I T H M E S H E S
61
To build meshes in a step-by-step fashion, create selections for the parts of the
geometry that you want to mesh in each step, as in this example:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1',2);
geom1.feature.create('r1','Rectangle');
geom1.feature.create('c1','Circle');
uni1 = geom1.feature.create('uni1', 'Union');
uni1.selection('input').set({'c1' 'r1'});
geom1.runCurrent;
del1 = geom1.feature.create('del1', 'Delete');
del1.selection('input').init(1);
del1.selection('input').set('uni1', 8);
geom1.run('del1');
mesh1 = model.mesh.create('mesh1','geom1');
dis1 = mesh1.feature.create('dis1', 'Distribution');
dis1.selection.set([2 4]);
dis1.set('type', 'predefined');
dis1.set('method', 'geometric');
dis1.set('elemcount', '20');
dis1.set('reverse', 'on');
dis1.set('elemratio', '20');
dis2 = mesh1.feature.create('dis2', 'Distribution');
dis2.selection.set([1 3]);
dis2.set('type', 'predefined');
dis2.set('method', 'geometric');
dis2.set('elemcount', '20');
dis2.set('elemratio', '20');
map1 = mesh1.feature.create('map1','Map');
map1.selection.geom('geom1', 2);
map1.selection.set(2);
mesh1.feature.create('frt1','FreeTri');
mesh1.run;
mphmesh(model);
62 |
The final mesh is in Figure 3-7. Note the effect of the Distribution feature, with
which the distribution of vertex elements along geometry edges can be controlled.
To replace the structured quad mesh by an unstructured quad mesh, delete the Map
feature and replace it by a FreeQuad feature:
mesh1.feature.remove('map1');
mesh1.run('dis1');
fq1 = mesh1.feature.create('fq1', 'FreeQuad');
fq1.selection.geom('geom1', 2).set(2);
mesh1.run;
WO R K I N G W I T H M E S H E S
63
For further details on the various commands and their properties see the
COMSOL API Reference Manual.
Create 3D volume meshes by extruding and revolving face meshes with the Sweep
feature. Depending on the 2D mesh type, the 3D meshes can be hexahedral (brick)
meshes or prism meshes.
To obtain a torus, leave the angles property unspecified; the default value gives a
complete revolution.
64 |
To generate a 3D prism mesh from the same 2D mesh by extrusion and then to plot
it, enter these commands:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 3);
wp1 = geom1.feature.create('wp1', 'WorkPlane');
wp1.set('planetype', 'quick');
wp1.set('quickplane', 'xy');
c1 = wp1.geom.feature.create('c1', 'Circle');
c1.set('pos', [2, 0]);
ext1 = geom1.feature.create('ext1', 'Extrude');
ext1.selection('input').set({'wp1'});
geom1.runAll;
mesh1 = model.mesh.create('mesh1', 'geom1');
ftri1 = mesh1.feature.create('ftri1', 'FreeTri');
ftri1.selection.geom('geom1', 2);
ftri1.selection.set(3);
dis1 = mesh1.feature.create('dis1', 'Distribution');
dis1.selection.set(1);
dis1.set('type', 'predefined');
dis1.set('elemcount', '20');
dis1.set('elemratio', '100');
swe1 = mesh1.feature.create('swe1', 'Sweep');
swe1.selection('sourceface').geom('geom1', 2);
WO R K I N G W I T H M E S H E S
65
swe1.selection('targetface').geom('geom1', 2);
mesh1.run;
mphmesh(model);
The result is shown in Figure 3-9. With the properties elemcount and elemratio the
number and distribution of mesh element layers is controlled in the extruded direction.
By specifying selections for the meshing operations, swept meshing can also be
combined with free meshing. In this case, start by free meshing domain 2, then sweep
the resulting surface mesh through domain 1, as in this example:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 3);
cone1 = geom1.feature.create('cone1', 'Cone');
cone1.set('r', '0.3');
cone1.set('h', '1');
cone1.set('ang', '9');
cone1.set('pos', [ 0 0.5 0.5]);
cone1.set('axis', [-1 0 0]);
geom1.feature.create('blk1', 'Block');
66 |
For 2D and 3D geometries it is also possible to create boundary layer meshes using the
BndLayer feature. A boundary layer mesh is a mesh with dense element distribution
in the normal direction along specific boundaries. This type of mesh is typically used
for fluid flow problems to resolve the thin boundary layers along the no-slip
boundaries. In 2D, a layered quadrilateral mesh is used along the specified no-slip
boundaries. In 3D, a layered prism mesh or hexahedral mesh is used depending on
whether the corresponding boundary layer boundaries contain a triangular or a
quadrilateral mesh.
If starting with an empty mesh, the boundary-layer mesh uses free meshing to create
the initial mesh before inserting boundary layers into the mesh. This generates a mesh
WO R K I N G W I T H M E S H E S
67
with triangular and quadrilateral elements in 2D and tetrahedral and prism elements in
3D. The following example illustrates this in 2D:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 2);
r1 = geom1.feature.create('r1', 'Rectangle');
r1.set('size', [10, 5]);
c1 = geom1.feature.create('c1', 'Circle');
c1.set('pos', [3.5 2.5]);
dif1 = geom1.feature.create('dif1', 'Difference');
dif1.selection('input').set({'r1'});
dif1.selection('input2').set({'c1'});
geom1.runAll;
mesh1 = model.mesh.create('mesh1', 'geom1');
bl1 = mesh1.feature.create('bl1', 'BndLayer');
bl1.feature.create('blp1', 'BndLayerProp');
bl1.feature('blp1').selection.set([2 3 5 6 7 8]);
mesh1.run;
mphmesh(model);
68 |
fq1.selection.set([1]);
mphmesh(model)
bl1 = mesh1.feature.create('bl2', 'BndLayer');
bl1.feature.create('blp2', 'BndLayerProp');
bl1.feature('blp2').selection.set([2 3 5 6 7 8]);
mesh1.run;
mphmesh(model);
Figure 3-12: Initial unstructured quad mesh (left) and resulting boundary layer mesh
(right).
REFINING MESHES
Given a mesh consisting only of simplex elements (lines, triangles, and tetrahedra) you
can create a finer mesh using the feature Refine. Enter this command to refine the
mesh:
mesh1.feature.create('ref1', 'Refine');
By specifying the property tri, either as a row vector of element numbers or a 2-row
matrix, the elements to be refined can be controlled. In the latter case, the second row
of the matrix specifies the number of refinements for the corresponding element.
The refinement method is controlled by the property rmethod. In 2D, its default value
is regular, corresponding to regular refinement, in which each specified triangular
element is divided into four triangles of the same shape. Setting rmethod to longest
gives longest edge refinement, where the longest edge of a triangle is bisected. Some
triangles outside the specified set might also be refined in order to preserve the
triangulation and its quality.
WO R K I N G W I T H M E S H E S
69
In 3D, the default refinement method is longest, while regular refinement is only
implemented for uniform refinements. In 1D, the function always uses regular
refinement, where each element is divided into two elements of the same shape.
For stationary or eigenvalue PDE problems you can use adaptive mesh
refinement at the solver stage with the solver step adaption. See
Adaption in the COMSOL API Reference Manual.
COPYING BOUNDAR Y MESHES
Use the CopyEdge feature in 2D and the CopyFace feature in 3D to copy a mesh
between boundaries.
It is only possible to copy meshes between boundaries that have the same
shape. However, a scaling factor between the boundaries is allowed.
The following example demonstrates how to copy a mesh between two boundaries in
3D and then create a swept mesh on the domain:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 3);
wp1 = geom1.feature.create('wp1', 'WorkPlane');
wp1.set('planetype', 'quick');
wp1.set('quickplane', 'xy');
c1 = wp1.geom.feature.create('c1', 'Circle');
c1.set('r', 0.5);
c1.set('pos', [1, 0]);
rev1 = geom1.feature.create('rev1', 'Revolve');
rev1.set('angle1', '0').set('angle2', '180');
rev1.selection('input').set({'wp1'});
geom1.run('wp1');
mesh1 = model.mesh.create('mesh1', 'geom1');
size1 = mesh1.feature.create('size1', 'Size');
size1.selection.geom('geom1', 1);
size1.selection.set(18);
size1.set('hmax', '0.06');
ftri1 = mesh1.feature.create('ftri1', 'FreeTri');
ftri1.selection.geom('geom1', 2);
ftri1.selection.set(10);
70 |
The algorithm automatically determines how to orient the source mesh on the target
boundary. The result is shown in Figure 3-13.
Figure 3-13: Prism element obtained with the CopyFace and Sweep features.
To explicitly control the orientation of the copied mesh, use the EdgeMap attribute.
The command sequence:
em1 = cpf1.feature.create('em1', 'EdgeMap');
em1.selection('srcedge').set(18);
em1.selection('dstedge').set(2);
mesh1.feature.remove('sw1');
mesh1.feature.create('ftet1', 'FreeTet');
mesh1.run;
mphmesh(model);
copies the mesh between the same boundaries as in the previous example, but now the
orientation of the source mesh on the target boundary is different. The domain is then
WO R K I N G W I T H M E S H E S
71
meshed by the free mesh, resulting in the mesh in Figure 3-14. In this case it is not
possible to create a swept mesh on the domain because the boundary meshes do not
match in the sweeping direction.
Figure 3-14: Free tetrahedral mesh after the use of the CopyFace feature.
CONVERTING MESH ELEMENTS
72 |
Figure 3-15: Mesh using free quad elements (left) and converted mesh from quad to
triangle (right).
To import a mesh stored in a supported format use the Import feature. The following
commands import and plot a NASTRAN mesh for a crankshaft:
model = ModelUtil.create('Model');
model.geom.create('geom1', 3);
mesh1 = model.mesh.create('mesh1', 'geom1');
imp1 = mesh1.feature.create('imp1', 'Import');
model.modelPath('dir\COMSOL44\models\COMSOL_Multiphysics\
Structural_Mechanics')
imp1.set('filename','crankshaft.nas');
WO R K I N G W I T H M E S H E S
73
mesh1.feature('imp1').importData;
mesh1.run;
mphmesh(model);
Where dir is the path of root directory where COMSOL Multiphysics is installed. The
above command sequence results in Figure 3-16.
74 |
geom1.runAll;
mesh1 = model.mesh.create('mesh1', 'geom1');
mesh1.feature.create('ftri1', 'FreeTri');
mesh1.run;
meshdset1 = model.result.dataset.create('mesh1', 'Mesh');
meshdset1.set('mesh', 'mesh1');
pg1 = model.result.create('pg1', 2);
meshplot1 = pg1.feature.create('mesh1', 'Mesh');
meshplot1.set('data', 'mesh1');
meshplot1.set('filteractive', 'on');
meshplot1.set('elemfilter', 'quality');
meshplot1.set('tetkeep', '0.25');
mphplot(model,'pg1');
meshplot1.set('elemfilter','qualityrev');
meshplot1.run;
mphplot(model,'pg1');
These commands display the worst 25% and the best 25% elements in terms of mesh
element quality. In Figure 3-17, the triangular mesh elements in the right-hand side
plot are more regular than those in the left-hand side plot; this reflects the fact that a
quality measure of 1 corresponds to a uniform triangle, while 0 means that the triangle
has degenerated into a line.
Figure 3-17: Visualizations of the mesh quality: worst 25% (left) and best 25% (right).
WO R K I N G W I T H M E S H E S
75
stats = mphmeshstats(model);
76 |
WO R K I N G W I T H M E S H E S
77
meshdata =
vertex: [2x12 double]
elem: {[2x8 int32] [3x14 int32]
elementity: {[8x1 int32] [14x1 int32]
[0 5 7 11]}
[4x1 int32]}
1.0000
0
0.3511
0.6397
In the elem field the element information is retrieved, such as the node indices (using
a 0 based) connected to the elements:
tri = meshdata.elem{2}
tri =
Columns 1 through 5
0
3
1
0
2
2
Columns 6 through 10
6
7
2
3
4
6
Columns 11 through 14
10
10
7
6
6
8
1
4
2
1
5
4
6
3
2
6
4
8
5
9
4
9
8
4
9
11
8
11
10
8
In the above command, notice that element number 1 is connected to nodes 1, 2, and
3, and element number 2 is connected to nodes 4, 1, and 3.
Then create manually a mesh using a data distribution generated in MATLAB. Enter
the command:
[x,y] = meshgrid([0 0.5 1], [0 0.5 1]);
X = reshape(x,1,9);
Y = reshape(y,1,9);
coord=[X;Y];
78 |
The node distribution obtained with this command corresponds to the mesh in
Figure 3-18.
4
3
2
7
6
Figure 3-18: Mesh with elements (bold) and nodes (italic) indices.
Table 3-1 lists the nodes and element connectivity in the mesh.
TABLE 3-1: ELEMENT AND NODES CONNECTIVITY
ELEMENT
NODES
1, 4, 5
1, 2, 5
2, 5, 6
2, 3, 6
4, 7, 8
4, 5, 8
5, 8, 9
5, 6, 9
To create the elements and nodes connectivity information use the command:
new_tri(:,1)=[0;3;4];
new_tri(:,2)=[0;1;4];
new_tri(:,3)=[1;4;5];
new_tri(:,4)=[1;2;5];
new_tri(:,5)=[3;6;7];
new_tri(:,6)=[3;4;7];
new_tri(:,7)=[4;7;8];
new_tri(:,8)=[4;5;8];
WO R K I N G W I T H M E S H E S
79
80 |
M o de li ng P hy s i cs
This section describes how to set up physics interfaces in a model. The physics interface
defines the equations that COMSOL solves.
The Physics Interface Syntax
The Material Syntax
Modifying the Equations
Adding Global Equations
Defining Model Settings Using External Data File
Access the User-Defined Physics Interface
The links to features described outside of this user guide do not work in
the PDF, only from the online help.
where <phystag> is a string that identifies the physics interface. Once defined, you can
always refer to a physics interface, or any other feature, by its tag. The string physint
is the constructor name of the physics interface. To get the constructor name, the best
way is to create a model using the desired physics interface in the GUI and save the
model as an M-file. The string <geomtag> refers to the geometry where you want to
specify the interface.
To add a feature to a physics interface, use the syntax:
model.physics(<phystag>).feature.create(<ftag>,operation);
where the <phystag> string refers to a physics interface. <ftag> is a string that you
use to refer to the operation. To set a property to a value in a operation, enter:
MODELING PHYSICS
81
model.physics(<phystag>).feature(<ftag>).set(property, <value>);
This example shows how to add a physics interface and set the boundary conditions in
the model object.
Start to create a model object including a 3D geometry. The geometry consists in a
block with default settings. Enter the following commands at the MATLAB prompt:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 3);
geom1.feature.create('blk1', 'Block');
geom1.run;
The tag of the interface is ht. The interface constructor is HeatTransfer. The physics
is defined on geometry geom1.
The physics interface automatically creates a number of default features. To examine
these, enter:
model.physics('ht')
ans =
82 |
The physics method has the following child nodes: solid1, ins1, cib1, init1, and
os1. These are the default features that come with the Heat Transfer in Solids
interface. The first feature, solid1, consists of the heat balance equation. Confirm this
by entering:
solid = phys.feature('solid1')
ans =
Type: Heat Transfer in Solids
Tag: solid1
The settings of the solid1 feature node can be modified, for example, to manually set
the material property. To change the thermal conductivity to 400 W/(m*K) enter:
solid.set('k_mat', 1, 'userdef');
solid.set('k', '400');
The Heat Transfer in Solids interface has features you can use to specify domain or
boundary settings. For example, to add a heat source of 105 W/m3 in the study
domain, enter the commands:
hs = phys.feature.create('hs1', 'HeatSource', 3);
hs.selection.set([1]);
hs.set('Q', 1, '1e5');
Then add a mesh and a study feature and compute the solution:
model.mesh.create('mesh1', 'geom1');
std = model.study.create('std1');
std.feature.create('stat', 'Stationary');
std.run
MODELING PHYSICS
83
where <mattag> is the string identifying the material defined when creating the
material. The string <mtag> refers to the material model.
To define material properties for the model, set the property value pairs by entering:
model.material(<mattag>).materialmodel(<mtag>).set(property,
<value>);
EXAMPLE: CREATE A MATERIAL NODE
The section Example: Implement and Solve a Heat Transfer Problem shows how to
change a material property inside a physics interface. This example shows how to
84 |
define a material available globally in the model. These steps assume that the previous
example has been followed. Enter:
mat = model.material.create('mat1');
The material automatically creates a material model, def, which can be used to set up
basic properties. For example, use it to define the density and the heat capacity:
mat.materialmodel('def').set('density', {'400'});
mat.materialmodel('def').set('heatcapacity', {'2e3'});
To use the defined material in a model, set the solid1 feature to use the material node.
Enter:
solid.set('k_mat',1,'from_mat');
Use the method getInfoTable(type) to return the tables available in the Equation
View node:
infoTable = info.getInfoTable(type);
where type defines the type of table to return. It can have the value 'Weak' to return
the weak form equations, 'Constraint' to return the constraint types table, or
'Expression' to return the variable expressions table.
EXAMPLE: ACCESS AND MODIFY THE EQUATION WEAK FORM
This example continues from the Example: Implement and Solve a Heat Transfer
Problem and modifies the model equation.
To retrieve information about the physics interface create an info object:
info = model.physics('ht').feature('solid1').featureInfo('info');
MODELING PHYSICS
85
From the info object access the weak form equation by entering:
infoTable = info.getInfoTable('Weak');
This returns a string variable that contains both the name of the weak equation variable
and the equation of the physics implemented in the weak form. Enter the command:
list = infoTable(:)
The output shows that the physics is defined with the weak expression available in the
variable list(1). Enter:
list(1)
to get the weak equation as a string variable. The result of this command is:
ans =
-(ht.k_effxx*Tx+ht.k_effxy*Ty+ht.k_effxz*Tz)*test(Tx)-(ht.k_effyx
*Tx+ht.k_effyy*Ty+ht.k_effyz*Tz)*test(Ty)-(ht.k_effzx*Tx+ht.k_eff
zy*Ty+ht.k_effzz*Tz)*test(Tz)
These commands set the heat conductivity to a constant value directly within the heat
balance equation.
To define the name of the variable to be solved by the global equation, enter:
model.physics(<odetag>).set('name', <idx>, <name>);
where <idx> is the index of the global equation, and <name> a string with the name
of the variable.
86 |
where <init> and <init_t> are the initial value expression for the variable and its
time derivative respectively.
EXAMPLE: SOLVE AN ODE PROBLEM
This example illustrates how to solve the following ODE in a COMSOL model:
u
u + --- + 1 = 0
2
u0 = 0
u 0 = 20
model = ModelUtil.create('Model');
ge = model.physics.create('ge', 'GlobalEquations');
ge1 = ge.feature('ge1');
ge1.set('name', 1, 1, 'u');
ge1.set('equation', 1, 1, 'utt+0.5*ut+1');
ge1.set('initialValueU', 1, 1, 'u0');
ge1.set('initialValueUt', 1, 1, 'u0t');
model.param.set('u0', '0');
model.param.set('u0t', '20');
std1 = model.study.create('std1');
std1.feature.create('time', 'Transient');
std1.feature('time').set('tlist', 'range(0,0.1,20)');
std1.run;
model.result.create('pg1', 1);
model.result('pg1').set('data', 'dset1');
model.result('pg1').feature.create('glob1', 'Global');
model.result('pg1').feature('glob1').set('expr', {'mod1.u'});
mphplot(model,'pg1')
MODELING PHYSICS
87
The interpolation function is initially defined globally and is located in the Model
Builder on the COMSOL Desktop under the Global Definitions node. If you have
several model nodes in your model and you want to attach it to the specified model
node <model>, enter:
model.func(<functag>).model(<model>);
where <model> is the tag of the model node to attach the interpolation function.
Then you can interpolate data specified by a table inside the function (default), or
specified in an external file.
When using an interpolation table, set the interpolation data for each row of the table
with the commands:
model.func(<functag>).setIndex('table', <t_value>, <i>, 1);
model.func(<functag>).setIndex('table', <ft_value>, <i>, 2);
where <t_value> is the interpolation parameter value and <ft_value> is the function
value. <i> is the index (0-based) in the interpolation table.
88 |
To use an external file change the source for the interpolation and specify the file,
where filename is the name (including the path) of the data file:
model.func(<functag>).set('source', 'file');
model.func(<functag>).set('filename', <filename>);
Several interpolation methods are available. Choose the one to use with the command:
model.func(<functag>).set('interp', method);
MODELING PHYSICS
89
updated with the path to the new JAR-file. You can verify this by typing
javaclasspath at the MATLAB prompt.
90 |
C r e a ti ng S e le ct i on s
In this section:
The Selection Node
Coordinate-Based Selections
Selection Using Adjacent Geometry
Displaying Selections
Named Selections
The links to features described outside of this user guide do not work in
the PDF, only from the online help.
To specify the domain entity dimension to use in the selection node, enter:
CREATING SELECTIONS
91
model.selection(<seltag>).geom(sdim);
where sdim is the space dimension that represents the different geometric entities:
3 for domains,
2 for boundaries/domains,
1 for edges/boundaries, and
0 for points.
Set the domain entity indices in the selection node with the command:
model.selection(<seltag>).set(<idx>);
where <idx> is an array of integers that list the geometric entity indices to add in the
selection.
Coordinate-Based Selections
DEFINING A BALL SELECTION NODE
The Ball selection node is defined by a center point and a radius. The selection can
include geometric entities that are completely or partially inside the ball. The selection
can be set up by using either the COMSOL API directly or the mphselectcoords
function. There are different ways to define the ball selections: Ball Selection Using the
COMSOL API or Ball Selection Using mphselectcoords.
To set the coordinates (<x0>, <y0>, <z0>) of the selection center point, enter:
model.selection(<seltag>).set('posx', <x0>);
model.selection(<seltag>).set('posy', <y0>);
model.selection(<seltag>).set('posz', <z0>);
92 |
where edim is an integer defining the space dimension value (3 for domains, 2 for
boundaries/domains, 1 for edges/boundaries, and 0 for points).
The selection also specifies the condition for geometric entities to be selected:
model.selection(<seltag>).set('condition', condition);
where <geomtag> is the tag of geometry where the selection, and entitytype, can be
one of 'point', 'edge', 'boundary', or 'domain'.
The above function returns the entity indices list. Use it to specify a feature selection
or to create an explicit selection as described in Setting an Explicit Selection.
By default the function searches for the geometric entity vertices near these
coordinates using the tolerance radius. It returns only the geometric entities that have
all vertices inside the search ball. To include any geometric entities in the selection that
have at least one vertex inside the search ball, set the property include to 'any':
idx = mphselectcoords(model, <geomtag>, [<x0>,<y0>,<z0>], ...
entitytype,'radius',<r0>,'include','any');
In case the model geometry is finalized as an assembly, you have distinct geometric
entities for each part of the assembly (pair). Specify the adjacent domain index to avoid
selection of any overlapping geometric entities. Set the adjnumber property with the
domain index:
idx = mphselectcoords(model, <geomtag>, [<x0>,<y0>,<z0>], ...
entitytype,'radius',<r0>,'adjnumber',<idx>);
where <idx> is the domain index adjacent to the desired geometric entities.
CREATING SELECTIONS
93
The Box selection node is defined by two diagonally opposite points of a box (in 3D)
or rectangle (in 2D). There are different ways to define the box selections: Box
Selection Using the COMSOL API or Box Selection Using mphselectbox
To specify the points (<x0>, <y0>, <z0>) and (<x1>, <y1>, <z1>), enter:
model.selection(<seltag>).set('xmin',
model.selection(<seltag>).set('ymin',
model.selection(<seltag>).set('zmin',
model.selection(<seltag>).set('xmax',
model.selection(<seltag>).set('ymax',
model.selection(<seltag>).set('zmax',
<x0>);
<y0>);
<z0>);
<x1>);
<y1>);
<z1>);
where <x0>, <y0>, <z0>, <x1>, <y1>, <z1> are double values.
To specify the geometric entities levels use the command:
model.selection(<seltag>).set('entitydim', edim);
where edim is an integer defining the space dimension value (3 for domains, 2 for
boundaries/domains, 1 for edges/boundaries, and 0 for points).
The selection also specifies the condition for geometric entities to be selected:
model.selection(<seltag>).set('condition', condition);
94 |
where <geomtag> is the geometry tag where the selection is applied, and entitytype
can be one of 'point', 'edge', 'boundary', or 'domain'.
The above function returns the entity indices list. Use it to specify a feature selection
or to create an explicit selection as described in Setting an Explicit Selection.
By default the function searches for the geometric entity vertices near these
coordinates using the tolerance radius. It returns only the geometric entities that have
all vertices inside the box or rectangle. To include any geometric entities in the
selection that have at least one vertex inside the search ball, set the property include
to 'any':
idx = mphselectbox(model,<geomtag>,...
[<x0> <x1>;<y0> <y1>;<z0> <z1>], entitytype,'include','any');
In case the model geometry is finalized as an assembly (pair), you have distinct
geometric entities for each part of the assembly. Specify the adjacent domain index to
avoid selection of overlapping geometric entities. Set the adjnumber property with the
domain index:
idx = mphselectbox(model,<geomtag>,...
[<x0> <x1>;<y0> <y1>;<z0> <z1>], entitytype, 'adjnumber', <idx>);
where <idx> is the domain index adjacent to the desired geometric entities.
RETRIEVING POINT COORDINATES USING A SELECTION
where <geomtag> is the geometry tag where the selection is applied, entitytype can
be one of 'point', 'edge', 'boundary', or 'domain' and <idx> is a integer array
containing the geometric entity indices. c is a Nx2 double array containing the point
coordinates where N is the number of points.
CREATING SELECTIONS
95
where edim is an integer defining the space dimension value (3 for domains, 2 for
boundaries/domains, 1 for edges/boundaries, and 0 for points).
The Adjacent selection node only supports the Selection node as an input:
model.selection(<seltag>).set( 'Adjacent');
where edim is an integer defining the space dimension value (3 for domains, 2 for
boundaries/domains, 1 for edges/boundaries, and 0 for points).
If there are multiple domains in the geometry to include in the interior and exterior
selected geometric entities, then enter:
model.selection(<seltag>).set('interior', 'on');
model.selection(<seltag>).set('exterior', 'on');
To exclude the interior/exterior, select geometric entities and set the respective
property to 'off'.
where <geomtag> is the tag of geometry where the selection applies. The string
variables entitytype and adjtype can be one of 'point', 'edge', 'boundary', or
'domain'.
96 |
The list returned by the function can be used to specify the selection for a model
feature or to create an explicit selection as described in Setting an Explicit Selection.
Displaying Selections
Use the function mphviewselection to display the selected geometric entities in a
MATLAB figure. This section also includes sections to Specify What to Display with
the Selection and Change Display Color and Transparency.
You can either specify the geometry entity index and its entity type or specify the tag
of a selection node available in the model.
To display the entity of type entitytype with the index <idx> enter:
mphviewselection(model, <geomtag>, <idx>, entitytype)
where <geomtag> is the geometry node tag, and <idx> is a positive integer array that
contains the entity indices. The string entitytype can be one of 'point', 'edge',
'boundary', or 'domain'.
If the model contains a selection node with the tag <seltag>, this selection can be
displayed with the command:
mphviewselection(model, <seltag>)
To plot the selection in an existing axis, set the property 'parent' with the axis output
value. For instance, the command below displays the selection in the current axis:
mphviewselection(model, <seltag>,'parent',gca)
Specify the render to display the figure with the property 'renderer' you can use
Open GL or Z buffer with the value 'opengl' or 'zbuffer' respectively.
SPECIFY WHAT TO DISPLAY WITH THE SELECTION
If the selected selection node is a Ball or Box selection, the ball or box selector is
display by default, to not show the selector, set the property 'showselector' to
'off'.
mphviewselection(model, <seltag>, 'showselector', 'off')
CREATING SELECTIONS
97
To include vertex, edge and face number, set the property 'vertexlabels',
'facelabels' and 'edgelabels' respectively to 'on'.
Change the marker used to represent the vertex with the property 'facemode'. In
the example command below the vertex are represented in the figure with a '+'
marker instead of the default '.':
mphviewselection(model, <seltag>, 'marker', '+')
Specify the size of the marker with the property 'edgelabels', you can specify an
integer value corresponding to the number of pixels.
C H A N G E D I S P L AY C O L O R A N D TR A N S P A RE N C Y
To change the color of the edge and the face use the property 'edgecolor' and
'facecolor' respectively. Specify the color of the vertex with the property
'markercolor'. Set the property with a character or using a RGB array. In this
example the edges are displayed in blue while the faces are displayed in the color
defined by the RGB array (0.5,0.5,0.5):
mphviewselection(model, <seltag>, 'edgecolor', 'b', ...
'facecolor', [0.5 0.5 0.5])
Specify the color for the selected edge and face with the properties
'edgecolorselected' and 'facecolorselected' respectively. Specify the color
of the selected vertex with the property 'markercolorselected'. Use a character
or specify the color by its RGB array. These commands show how to set the edge to
a blue color and the face with the color defined by the RGB array (0.5, 0.5,0.5):
mphviewselection(model, <seltag>, 'edgecolorselected', 'b', ...
'facecolorselected', [0.5 0.5 0.5])
Specify the color for the vertex, edge, and face labels with the properties
'vertexlabelscolor', 'edgelabelscolor' and 'facelabelscolor' respectively.
You can use a character or the RGB array to specify the color.
Control the transparency of the geometry representation with the property
'facealpha'. Set the property with a double included between 0 and 1. Using this
command the geometry is displayed with a transparency of 50%:
mphviewselection(model, <seltag>, 'facealpha', 0.5)
98 |
CREATING SELECTIONS
99
The links to features described outside of this user guide do not work in
the PDF, only from the online help.
100 |
where <studytag> is the string identifying the study node. The string <ftag> is a
string that is defined to refer to the study step. The string operation is one of the basic
study types, such as Stationary, Transient, or Eigenfrequency, and more.
To specify a property value pair for a study step, enter:
model.study(<studytag>).feature(<ftag>).set(property, <value>);
where <soltag> is a string used to refer to the solver sequence associated to a solution
object.
A solver sequence has to be connected to a study node, which is done with the
command:
model.sol(<soltag>).study(<studytag>);
101
where <studytag> is the tag of the study you want to associate the solver sequence
defined with the tag <soltag>.
A solver sequence also requires the definition of these nodes:
Study Step, where the study and study step is specified for compiling the equations
and computing the current solver sequence;
Dependent Variables, this node handles settings for the computation of dependent
variables, such as initial value and scaling settings but also the dependent variables
not solved for; and
Solver node, where the type of solver to use is specified to compute the solution.
Add the nodes to the solver sequence with the command:
model.sol(<soltag>).feature.create(<ftag>, operation);
where <soltag> is the string defined when creating the solver sequence. The string
ftag is a string that is defined to refer to the node, for example, a study step.
operation can be 'StudyStep', 'Variables', or 'Stationary'.
To specify a property value pair for a solver feature, enter:
model.sol(<soltag>).feature(<ftag>).set(property, <value>);
102 |
You can also use the method run(<ftag>) to run the solver sequence up to the solver
feature with the tag <ftag>:
model.sol(<soltag>).run(<ftag>);
When you want to continue solving a sequence, use the method runFrom(<ftag>) to
run the solver configuration from the solver feature with the tag <ftag>:
model.sol(<soltag>).runFrom(<ftag>)
where <studytag> is the tag of the study node where to include the parametric sweep
defined with the tag <ftag>.
To add one or several parameters to the sweep, enter the command:
model.study(<studytag>).feature(<ftag>).setIndex('pname',
<pname>, <idx>);
where <pname> is the name of the parameter to use in the parametric sweep and <idx>
the index number of the parameter. Set the <idx> to 0 to define the first parameter, 1
to define the second parameter, and so on.
Set the list of the parameter values with the command:
model.study(<studytag>).feature(<ftag>).setIndex('plistarr',
<pvalue>, <idx>);
where <pvalue> contains the list of parameter values defined with either a string or
with a double array, and <idx> is the index number of the parameter and uses the same
value as for the parameter name.
If there are several parameters listed in the parametric sweep node, select the type of
sweep by entering:
model.study(<studytag>).feature(<ftag>).set('sweeptype', type);
103
where the sweep type,type, can be either 'filled' or 'sparse', referring to all
combinations or specified combinations of the parameter values, respectively.
where <batchtag> is the tag of the job sequence and type is the type of job to define.
It can be either Parametric, Batch, or Cluster.
For a solver sequence you need to attach the job sequence to an existing study node.
Enter the command:
model.batch(<batchtag>).atached(<studytag>);
You can get the list of the properties in model.batch() in the COMSOL
API Reference Manual.
To run the batch sequence use the run method:
model.batch(<batchtag>).run;
104 |
where <studytag> and <studysteptag> refer to the study node and study step,
respectively.
Specify the plot group to plot by setting the plot group tag:
model.study(<studytag>).feature(<studysteptag>).set('plotgroup',
<ptag>);
Only one plot group can be plotted during a computation. Use the probe feature
instead if you need to monitor several variables.
To activate Plot While Solving for a probe plot, enter the command:
model.study(<studytag>).feature(<studysteptag>).set('probesel',
seltype);
where seltype is the type of probe selection, that can be 'none', 'all', or
'manual'.
In case the probe selection is set to manual you have to specify the list of the probe
variable to display. Enter the command:
model.study(<studytag>).feature(<studysteptag>).set('probes',
<list>);
where <list> is the a cell array containing the list of the probe to use.
105
The links to features described outside of this user guide do not work in
the PDF, only from the online help.
Select the string <pgtag> to identify the plot group and the integer sdim to set the
space dimension (1, 2, or 3) of the group.
To add a plot to a plot group, use the syntax:
model.result(<pgtag>).feature.create(<ftag>, plottype);
where the string <ftag> identifies the plot, and the string plottype defines its type.
Plots can have different attributes that modify the display. For example, the
Deformation attribute deforms the plot according to a vector quantity, the Height
Expression attribute introduces 3D height on a 2D table surface plot, and the Filter
attribute filters the plot using a logical expression. The type of plot determines which
attributes are available. Add an attribute to a plot with the command:
106 |
model.result(<pgtag>).feature(<ftag>).feature.create(<attrtag>,
attrtype);
For a list of available plot types and corresponding attribute types, see
Results and model.result() in the COMSOL API Reference Manual.
Use the command mphplot to display a plot group available from the model object.
For example, to display the plot group <pgtag> enter:
mphplot(model, <pgtag>);
This renders the graphics in a MATLAB figure window. In addition you can plot
results in a COMSOL Multiphysics Graphics window if you start COMSOL with
MATLAB using a graphics server. To do this for a plot group <pgtag> enter:
mphplot(model, <pgtag>, 'server', 'on');
The default settings for plotting in a MATLAB figure do not display the color legend.
To include the color legend in a figure, use the property rangenum:
107
where the integer <idx> identifies the plot for which the color legend should be
displayed.
EXTRACT PLOT DATA
In some situation it can be useful to extract data from a plot, for example, if you need
to manually edit the plot as it is allowed in MATLAB. To get a cell array, dat, which
contains the data for each plot feature available in the plot group <pgtag> enter:
dat = mphplot(model, <pgtag>);
PLOT EXTERNAL DATA
Using the function mphplot you can also plot data that is specified directly as an input
argument. The supported data format is according to the structure provided by the
function mpheval. This allows you to plot data that has first been extracted from the
model then modified in MATLAB, on the model geometry. To plot the structure
<data>, run the command:
mphplot(<data>);
If the data structure contains the value of several expressions, set the one to display in
the plot with the index property:
mphplot(<data>, 'index', <idx>);
mphplot supports only plotting of data structures that are of the type
Obtain a list of alternatives for colorname from the on-line help by entering:
help colortable
To disable the mesh displayed together with the data results, set the property mesh to
off as in this command:
mphplot(<data>, 'mesh', 'off');
108 |
This example extracts COMSOL data at the MATLAB prompt, modifies it and plots
the data in a MATLAB figure.
First load the Busbar model from the COMSOL Multiphysics model library. Enter:
model = mphload('busbar');
To extract the temperature and the electric potential field, use the command mpheval:
dat = mpheval(model,{'T','V'},'selection',1);
Do a simple scaling of the electric potential then plot it using the default color table:
dat.d2 = dat.d2*1e-3;
109
To emphasize the geometry use the function mphgeom to display line plot on the dsame
figure:
hold on;
mphgeom(model, 'geom1', 'facemode', 'off')
110 |
Sets are self defined, Visualization Data Sets always refer to an existing Solution Data
Set.
All plots refer to data sets; the solutions are always available as the default
data set.
To create a data set at the MATLAB prompt, use the command:
model.result.dataset.create(<dsettag>, dsettype);
For a list of the syntax of the numerical results type available, see About
Results Commands in the COMSOL API Reference Manual.
To store the data needed to create a table and associate the table to the numerical node:
model.result.table.create(<tabletag>,'Table');
111
model.result.numerical(<numtag>).set('table',<tabletag>);
where <tabletag> is the tag of the table where you want to store the data evaluated
with the numerical operations defined with the tag <numtag>.
To extract the data stored in MATLAB into a table, use the methods getRealRow and
getImagRow, such as:
realRow = model.result.table(<tabletag>).getRealRow(<idx>);
imagRow = model.result.table(<tabletag>).getImagRow(<idx>);
Extracting Results
Exporting Data
Use the export node to generate an animation or to export data to an external file
(ASCII format). This section includes information about Animation Export, Data
Export, and the Animation Player.
ANIMATION EXPORT
Animations can be defined as two different types: a movie or an image sequence. The
movie generates file formats such as GIF (.gif), AVI (.avi), or flash (.swf); the
image sequence generates a sequence of images. Make sure COMSOL with MATLAB
using a graphics server to enable plot on server.
To change the animation type use the 'type' property according to:
model.result.export(<animtag>).set('type', type);
112 |
where, the positive integers <width_px> and <height_px> are the width and height
size (in pixels), respectively, to use for the animation.
DATA EXPORT
In order to save data to an ASCII file, create a Data node to the export method:
model.result.export.create(<datatag>, 'Data');
Set the expression expr and the file name filenname, and run the export:
model.result.export.(<datatag>).setIndex('expr', <expr>, 0);
model.result.export.(<datatag>).set('filename', <filenname>);
See Data Formats in the COMSOL API Reference Manual for details
about the data formats used in the exported data files.
To export the data in the specified file, run the export node:
113
model.result.export.(<datatag>).run;
ANIMATION PLAYER
For transient and parametric studies, an animation player can be generated to create
interactive animations.
The player displays the figure on a COMSOL Graphics window. Make sure COMSOL
with MATLAB is started using a graphics server.
Then associate the player with an existing plot group by setting the plotgroup
property:
model.result.export(<playtag>).set('plotgroup', <pgtag>);
where <pgtag> refers to the plot group, which is animated in the player.
The default frame number used to generate the animation is 25, you can also specify
the number of frame with the command:
model.result.export(<playtag>).set('maxframe', <maxnum>);
where <maxnum> is a positive integer value that corresponds to the maximum number
of frames to generate with the player.
Use the run method to generate the player:
model.result.export(<playtag>).run;
114 |
115
Use the set method to assign parameter and/or property values. All assignments
return the parameter object, which means that assignment methods can be appended
to each other.
The basic method for assignment is:
something.set(name, <value>);
The name argument is a string with the name of the parameter/property. The
<value> argument can for example be a MATLAB integer or double array variable.
When using a MATLAB variable, make sure that the value corresponds to the model
unit system. COMSOL can also take care of the unit conversation automatically; in this
case convert the MATLAB integer/double variable to a string variable and use the set
method as:
something.set(property, [num2str(<value>)'[unit]']);
116 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
Use the setIndex method to assign values to specific indices (0-based) in an array or
matrix property. All assignment methods return the parameter object, which means
that assignment methods can be appended to each other:
something.setIndex(name, <value>, <index>);
The name argument is a string with the name of the property, <value> is the value to
set the property, which can be a MATLAB variable value, and <index> is the index in
the property table.
When using a MATLAB variable make sure that the value corresponds to the model
unit system. COMSOL can automatically take care of the unit conversation; in this case
converting the MATLAB integer/double variable to a string variable and using the
set method as:
something.setIndex(name, [num2str(<value>)'[unit]'], <index>);
where [unit] is the unit you want to set the value property.
LiveLink for MATLAB enables you to declare a MATLAB M-function directly from
within the COMSOL Multiphysics model object. This is typically the case if you want
to call a MATLAB M-function from the COMSOL Desktop. The function being
declared within the model object accepts any parameter, variable, or expression
arguments defined in the COMSOL model object. However, to use a variable defined
at the MATLAB prompt, the variable has to be transferred first in the COMSOL
model as a parameter, for example (see how to set a MATLAB variable in the
COMSOL model in The Set and SetIndex Methods).
The function is evaluated any time the model needs to be updated. The model object
cannot be called as an input argument of the M-function.
U S I N G M AT L A B V A R I A B L E S I N M O D E L S E T T I N G S
117
C A L L I N G M AT L A B F U N C T I O N S A T T H E M AT L A B P RO M P T
Use a MATLAB function to define a model property with the set method:
something.set(property, myfun(<arg>));
118 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
Extracting Results
Use LiveLink for MATLAB to extract at the MATLAB prompt the data computed
in the COMSOL Multiphysics model. A suite of wrapper functions is available to
perform evaluation operations at the MATLAB prompt.
In this section:
Extracting Data From Tables
Extracting Data at Node Points
Extracting Data at Arbitrary Points
Evaluating an Expression at Geometry Vertices
Evaluating an Integral
Evaluating a Global Expression
Evaluating a Global Matrix
Evaluating a Maximum of Expression
Evaluating an Expression Average
Evaluating a Minimum of Expression
Evaluating Expressions on Particle Trajectories
EXTRACTING RESULTS
119
where <expr> is a string cell array that lists the COMSOL Multiphysics expression to
evaluate. The expression has to be defined in a COMSOL model object in order to be
evaluated.
pd is a structure with the following fields:
expr contains the list of names of the expressions evaluated with mpheval;
d1 contains the value of the expression evaluated. The columns in the data value
fields correspond to node point coordinates in columns in the field p. In case of
several expressions are evaluated in mpheval, additional field d2, d3,... are available;
p contains the node point coordinates information. The number of rows in p is the
number of space dimensions;
t contains the indices to columns in pd.p of a simplex mesh; each column in pd.t
represents a simplex;
ve contains the indices to mesh elements for each node points; and
unit contains the list of the unit for each evaluated expressions.
The rest of this section has additional information for the function mpheval:
Specify the Evaluation Data
Output Format
Specify the Evaluation Quality
Display the Expression in Figures
SPECIFY THE EVALUATION DATA
The function mpheval supports the following properties to set the data of the
evaluation to perform:
dataset, specify the solution data set to use in the evaluation:
120 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
data set of the model. Selection data set such as Cut point, Cut line, Edge, Surface,
and so forth, are not supported.
selection, specify the domain selection for evaluation:
pd = mpheval(model, <expr>, 'selection', <seltag>);
where <seltag> is the tag of a selection node to use for the data evaluation.
<seltag> can also be a positive integer array that corresponds to the domain index
list. The default selection is all domains where the expression is defined. If the
evaluation point does not belong to the specified domain selection, the output value
is NaN.
edim, specify the element dimension for evaluation:
pd = mpheval(model, <expr>, 'edim', edim);
where edim is either a string or a positive integer such as: 'point' (0), 'edge' (1),
'boundary' (2), or 'domain' (3). The default settings correspond to the model
geometry space dimension. When using a lower space dimension value, make sure
that the evaluation point coordinates dimension has the same size.
EXTRACTING RESULTS
121
expression for all or the last outer solution respectively. The default setting uses the
first outer solution for the data evaluation.
To evaluate the expression data at a specific time use the property t:
pd = mpheval(model, <expr>, 't', <time>);
where <time> is a double array. The default value corresponds to all the stored time
steps.
phase, specify the phase in degrees:
pd = mpheval(model, <expr>, 'phase', <phase>);
The function mpheval returns a structure in the MATLAB workspace. You can specify
other output data formats.
To only obtain the data evaluation as a double array, set the property dataonly to on:
pd = mpheval(model, <expr>, 'dataonly', 'on');
Include the imaginary part in the data evaluation with the property complexout:
pd = mpheval(model, <expr>, 'complexout', 'on');
SPECIFY THE EVALUATION QUALITY
Define mpheval function settings to specify the evaluation quality using these
properties:
refine, specify the element refinement for evaluation:
pd = mpheval(model, <expr>, 'refine', <refine>);
where <refine> is a positive integer. The default value is 1 which set the simplex
mesh identical to the geometric mesh.
smooth, specify the smoothing method to enforce continuity on discontinuous data
evaluation:
pd = mpheval(model, <expr>, 'smooth', smooth);
122 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
everywhere to apply the smoothing to the entire geometry, and set to internal
to smooth the quantity inside the geometry (but no smoothing takes place across
borders between domains with different settings). The output with the same data
and same coordinates are automatically merged, which means that the output size
can differ depending on the smoothing method.
recover, specify the accurate derivative recovery:
pd = mpheval(model, <expr>, 'recover', recover);
where recover is either 'ppr', 'pprint', or 'off' (default). Set the property to
ppr to perform recovery inside domains or set to pprint to perform recovery inside
domains. Because the accurate derivative processing takes time, the property is
disabled by default.
OTHER EVALUATION PROPERTIES
To not use complex-value functions with real inputs, use the property complexfun:
pd = mpheval(model, <expr>, 'complexfun','off');
You can display an expression evaluated with mpheval in an external figure with the
function mphplot (see Displaying The Results). The function mphplot only supports
a MATLAB structure provided by mpheval as input.
EXTRACTING RESULTS
123
where <dsettag> is a selection data set tag defined in the model, for example, Cut
point, Cut Plane, Revolve, and so forth.
The rest of this section has additional information for the function mphinterp:
Specify the Evaluation Data
Output Format
Specify the Evaluation Quality
Other Evaluation Properties
SPECIFY THE EVALUATION DATA
The function mphinterp supports the following properties to set the data of the
evaluation to perform:
dataset, specify the solution data set to use in the evaluation:
data =
mphinterp(model,<expr>,'coord',<coord>,'dataset',<dsettag>);
<dsettag> is the tag of a solution data set. The default value is the current solution
where <seltag> is the tag of a selection node to use for the data evaluation.
<seltag> can also be a positive integer array that corresponds to the domain index
list. The default selection is All domains where the expression is defined. If the
evaluation point does not belong to the specified domain selection the output value
is NaN.
edim, specify the element dimension for evaluation:
data = mphinterp(model,<expr>,'coord',<coord>,'edim',edim);
where edim is either a string or a positive integer such as 'point' (0), 'edge' (1),
'boundary' (2), or 'domain' (3). The default settings correspond to the model
geometry space dimension. When using a lower space dimension value, make sure
that the evaluation point coordinates dimension has the same size.
ext, specify extrapolation control value. This ensures you return data for points that
are outside the geometry:
124 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
data = mphinterp(model,<expr>,'coord',<coord>,'ext',<ext>);
where <time> is a double array. The default value corresponds to all the stored time
steps.
phase, specify the phase in degrees:
data = mphinterp(model,<expr>,'coord',<coord>,'phase',<phase>);
The function mphinterp returns in the MATLAB workspace a double array. It also
supports other output formats.
To evaluate several expressions at once, make sure that the same number of output
variables are defined as there are expressions specified:
[d1, ..., dn] = mphinterp(model,{'e1', ..., 'en'},'coord',<coord>);
To extract the unit of the evaluated expression, define an extra output variable:
[data, unit] = mphinterp(model,<expr>,'coord',<coord>);
EXTRACTING RESULTS
125
with unit is a 1xN cell array where N is the number of expressions to evaluate.
Include the imaginary part in the data evaluation with the property complexout:
data = mphinterp(model,<expr>,'coord',<coord>,'complexout','on');
To return an error if all evaluation points are outside the geometry, set the property
coorderr to on:
data = mphinterp(model,<expr>,'coord',<coord>,'coorderr','on');
With the property recover, you can specify the accurate derivative recovery:
data = mphinterp(model,<expr>,'coord',<coord>,'recover', recover);
where recover is either 'ppr', 'pprint', or 'off' (the default). Set the property to
ppr to perform recovery inside domains or set to pprint to apply recovery to all
domain boundaries. Because the accurate derivative processing takes time, the
property is disabled by default.
OTHER EVALUATION PROPERTIES
126 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
where e1,...,en are the COMSOL expressions to evaluate. The output d1, ..., dn
is a NxP double array, where N is the number of evaluation points and P the length of
the inner solution.
The rest of this section has additional information for the function mphevalpoint:
Specify the Evaluation Data
Output Format
SPECIFY THE EVALUATION DATA
The function mphevalpoint supports the following properties to set the data of the
evaluation to perform:
dataset, specify the solution data set to use in the evaluation:
data = mphevalpoint(model,<expr>,'dataset',<dsettag>);
<dsettag> is the tag of a solution data set. The default value is the current solution
where <seltag> is the tag of a selection node to use for the data evaluation.
<seltag> can also be a positive integer array that corresponds to the domain index
list. The default selection is all domains where the expression is defined. If the
evaluation point does not belong to the specified domain selection, the output value
is NaN.
solnum, specify the inner solution number for data evaluation. Inner solutions are
generated for the following analysis types: time domain, frequency domain,
eigenvalue, or stationary with continuation parameters:
data = mphevalpoint(model,<expr>,'solnum',<solnum>);
EXTRACTING RESULTS
127
expression for all or the last outer solution respectively. The default settings use the
first outer solution for the data evaluation.
To evaluate the expression data at a specific time use the property t:
data = mphevalpoint(model,<expr>,'t', <time>);
where <time> is a double array. The default value corresponds to all the stored time
steps.
Perform a data series operation with the dataseries property:
data = mphevalpoint(model,<expr>,'dataseries', dataseries);
where dataseries is either 'mean', 'int', 'max', 'min', 'rms', 'std', or 'var'.
Depending on the property value, mphevalpoint performs the following
operationsmean, integral, maximum, minimum, root mean square, standard
deviation, or variance, respectively.
When performing a minimum or maximum operation on the data series, you can
specify to perform the operation using the real or the absolute value. Set the property
minmaxobj to 'real' or 'abs', respectively:
data = mphevalpoint(model,<expr>,'dataseries', dataseries,...
'minmaxobj', valuetype);
with unit is a 1xN cell array where N is the number of expressions to evaluate.
By default, mphevalpoint returns the results as a squeezed singleton. To get the full
singleton set the squeeze property to off:
data = mphevalpoint(model,<expr>,'squeeze','off');
Set the property matrix to off to return the data as a cell array instead of a double
array:
data = mphevalpoint(model,<expr>,'matrix','off');
128 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
Evaluating an Integral
Evaluate an integral of expression with the function mphint2.
The function mphint is now obsolete and will be removed in a future
version of the software. If you are using this function in your code, you
can now replace it by mphint2.
To evaluate the integral of the expression over the domain with the highest space
domain dimension call the function mphint2 as in this command:
[d1,...,dn] = mphint2(model,'e1',...,'en'},edim);
where e1,...,en are the COMSOL Multiphysics expressions to integrate. The values
d1,...,dn are returned as a 1xP double array, with P the length of inner parameters.
edim is the integration dimension, which can be 'line', 'surface', 'volume', or
an integer value that specifies the space dimension (1, 2, or 3).
The rest of this section has additional information for the function mphint2:
Specify the Integration Data
Output Format
Specify the Integration Settings
SPECIFY THE INTEGRATION DATA
The function mphint2 supports the following properties to set the data of the
evaluation to perform:
dataset, specify the solution data set to use in the integration:
data = mphint2(model,<expr>,edim,'dataset',<dsettag>);
<dsettag> is the tag of a solution data set. The default value is the current solution
where <seltag> is the tag of a selection node to use for the data evaluation.
<seltag> can also be a positive integer array that corresponds to the domain index
list. The default selection is all domains where the expression is defined. If the
evaluation point does not belong to the specified domain selection the output value
is NaN.
EXTRACTING RESULTS
129
solnum, specify the inner solution number for data evaluation. Inner solutions are
generated for the following analysis types: time domain, frequency domain,
eigenvalue, or stationary with continuation parameters:
data = mphint2(model,<expr>,edim,'solnum',<solnum>);
where <time> is a double array. The default value corresponds to all the stored time
steps.
OUTPUT FORMAT
with unit is a 1xN cell array where N is the number of expressions to evaluate.
By default mphint2 returns the results as a squeezed singleton. To get the full
singleton, set the squeeze property to off:
data = mphint2(model,<expr>,edim,'squeeze','off');
Set the property matrix to off to return the data as a cell array instead of a double
array:
data = mphint2(model,<expr>,edim,'matrix','off');
130 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
where e1,...,en are the COMSOL Multiphysics global expressions to evaluate. The
output values d1,...,dn are returned as a Px1 double array, with P the length of
inner parameters.
The rest of this section has additional information for the function mphglobal:
Specify the Evaluation Data
Output Format
Other Evaluation Properties
SPECIFY THE EVALUATION DATA
The function mphglobal supports the following properties to set the data of the
evaluation to perform:
dataset, specify the solution data set to use in the evaluation:
EXTRACTING RESULTS
131
data = mphglobal(model,<expr>,'dataset',<dsettag>);
<dsettag> is the tag of a solution data set. The default value is the current solution
where <time> is a double array. The default value corresponds to all the stored time
steps.
phase, specify the phase in degrees:
data = mphglobal(model,<expr>,'phase',<phase>);
with unit is a 1xN cell array where N is the number of expressions to evaluate.
Include the imaginary part in the data evaluation with the property complexout:
data = mphglobal(model,<expr>,'complexout','on');
132 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
The output data M is a NxN double array, where N is the number of port boundary
condition set in the model.
SPECIFY THE EVALUATION DATA
Set the solution data set for evaluation with the property dataset:
data = mphevalglobalmatrix(model,<expr>,'dataset',<dsettag>);
EXTRACTING RESULTS
133
where edim is a string to define the element entity dimension: 'volume', 'surface',
or 'line'. edim can also be set as a positive integer value (3, 2, or 1 respectively). The
output variables d1,...,dn are an NxP array where N is the number of inner solutions
and P the number of outer solutions.
The rest of this section has additional information for the function mphmax:
Specify the Evaluation Data
Output Format
SPECIFY THE EVALUATION DATA
The function mphmax supports the following properties to set the data of the
evaluation to perform:
dataset, specify the solution data set to use in the evaluation:
data = mphmax(model,<expr>,edim,'dataset',<dsettag>);
<dsettag> is the tag of a solution data set. The default value is the current solution
where <seltag> is the tag of a selection node to use for the data evaluation.
<seltag> can also be a positive integer array that corresponds to the domain index
list. The default selection is all domains where the expression is defined. If the
evaluation point does not belong to the specified domain selection the output value
is NaN.
solnum, specify the inner solution number for data evaluation. Inner solutions are
generated for the following analysis types: time domain, frequency domain,
eigenvalue, or stationary with continuation parameters:
data = mphmax(model,<expr>,edim,'solnum',<solnum>);
134 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
data = mphmax(model,<expr>,edim,'outersolnum',<outersolnum>);
where <time> is a double array. The default value corresponds to all the stored time
steps.
OUTPUT FORMAT
where unit is a 1xN cell array and N is the number of expressions to evaluate.
By default mphmax returns the results as a squeezed singleton. To get the full singleton
set the squeeze property to off:
data = mphmax(model,<expr>,edim,'squeeze','off');
Set the property matrix to off to return the data as a cell array instead of a double
array:
data = mphmax(model,<expr>,edim,'matrix','off');
where edim is a string to define the element entity dimension: 'volume', 'surface',
or 'line'. edim can also be set as a positive integer value (3, 2, or 1 respectively). The
output variables d1,...,dn are an NxP array where N is the number of inner solutions
and P the number of outer solutions.
EXTRACTING RESULTS
135
The rest of this section has additional information for the function mphmean:
Specify the Evaluation Data
Output Format
Specify the Integration Settings
SPECIFY THE EVALUATION DATA
The function mphmean supports the following properties to set the data of the
evaluation to perform:
dataset, specify the solution data set to use in the evaluation:
data = mphmean(model,<expr>,edim,'dataset',<dsettag>);
<dsettag> is the tag of a solution data set. The default value is the current solution
where <seltag> is the tag of a selection node to use for the data evaluation.
<seltag> can also be a positive integer array that corresponds to the domain index
list. The default selection is all domains where the expression is defined. If the
evaluation point does not belong to the specified domain selection the output value
is NaN.
solnum, specify the inner solution number for data evaluation. Inner solutions are
generated for the following analysis types: time domain, frequency domain,
eigenvalue, or stationary with continuation parameters:
data = mphmean(model,<expr>,edim,'solnum',<solnum>);
136 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
where <time> is a double array. The default value corresponds to all the stored time
steps.
OUTPUT FORMAT
where unit is a 1xN cell array and N is the number of expressions to evaluate.
By default mphmean returns the results as a squeezed singleton. To get the full
singleton set the squeeze property to off:
data = mphmean(model,<expr>,edim,'squeeze','off');
Set the property matrix to off to return the data as a cell array instead of a double
array:
data = mphmean(model,<expr>,edim,'matrix','off');
SPECIFY THE INTEGRATION SETTINGS
You can specify integration settings such as an integration method or integration order
to perform the mean operation. The available integration properties are:
method, specify the integration method, which can be either integration or
summation:
data = mphmean(model,<expr>,edim,'method',method);
EXTRACTING RESULTS
137
To evaluate the minimum of the COMSOL expressions e1,...,en use the command
mphmin:
[d1,...,dn] = mphmin(model,{'e1',...,'en'},edim);
where edim is a string to define the element entity dimension: 'volume', 'surface',
or 'line'. edim can also be set as a positive integer value (3, 2, or 1 respectively). The
output variables d1,...,dn are an NxP array where N is the number of inner solutions
and P the number of outer solutions.
The rest of this section has additional information for the function mphmin:
Specify the Evaluation Data
Output Format
SPECIFY THE EVALUATION DATA
The function mphmin supports the following properties to set the data of the
evaluation to perform:
dataset, specify the solution data set to use in the evaluation:
data = mphmin(model,<expr>,edim,'dataset',<dsettag>);
<dsettag> is the tag of a solution data set. The default value is the current solution
where <seltag> is the tag of a selection node to use for the data evaluation.
<seltag> can also be a positive integer array that corresponds to the domain index
list. The default selection is all domains where the expression is defined. If the
evaluation point does not belong to the specified domain selection the output value
is NaN.
solnum, specify the inner solution number for data evaluation. Inner solutions are
generated for the following analysis types: time domain, frequency domain,
eigenvalue, or stationary with continuation parameters:
data = mphmin(model,<expr>,edim,'solnum',<solnum>);
138 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
outersolnum, specify the outer solution number for data evaluation. Outer
solutions are generated with parametric sweeps:
data = mphmin(model,<expr>,edim,'outersolnum',<outersolnum>);
where <time> is a double array. The default value corresponds to all the stored time
steps.
OUTPUT FORMAT
where unit is a 1xN cell array and N is the number of expressions to evaluate.
By default mphmin returns the results as a squeezed singleton. To get the full singleton
set the squeeze property to off:
data = mphmin(model,<expr>,edim,'squeeze','off');
Set the property matrix to off to return the data as a cell array instead of a double
array:
data = mphmin(model,<expr>,edim,'matrix','off');
EXTRACTING RESULTS
139
velocity at every time step. The information is stored in the following fields:
p contains the coordinates of the particle position along the trajectories. The data
are stored in a NxMxL array where N is the number of time steps, M the number of
evaluation point along the particle trajectories, and L the evaluation space
dimension.
v contains the value of the particle velocity along the trajectories. The data are
stored in a NxMxL array where N is the number of time steps, M the number of
evaluation points along the particle trajectories, and L the evaluation space
dimension.
t contains the list of evaluation time.
You can also specify expressions to evaluate along the particle trajectories. Run the
function mphparticle as in this command:
pd = mphparticle(model,'expr','e1');
where 'e1' is the expression to evaluate along the particle trajectories. The output
structure pd contains the fields p, v, and t (described above) with the following ones:
unit contains the unit of the evaluated expression;
d1 contains the value of the expression. The data are stored in a NxM array where
N is the number of time steps and M the number of evaluation points along the
particle trajectories; and
expr contains the list of the evaluated expression.
Use a string cell array to evaluate several expressions at once. The result of the
evaluation is then stored in the field d1, d2, ..., dn corresponding to each evaluated
expression.
SPECIFY THE EVALUATION DATA
The function mphparticle supports the following properties to set the data of the
evaluation to perform:
dataset, specify the solution data set to use in the evaluation:
pd = mphparticle(model,'expr',<expr>,'dataset',<dsettag>);
<dsettag> is the tag of a particle solution data set. The default value is the current
140 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
pd = mphparticle(model,'expr',<expr>,'t',<time>);
where <time> is a double array. The default value corresponds to all the stored time
steps.
OUTPUT FORMAT
The output structure pd only contains the field unit, d#, expr, and t (described
above).
EXTRACTING RESULTS
141
R unni ng M o de l s i n a Loop
A common use of LiveLink for MATLAB is to run models in a loop. MATLAB
provides several functionalities to run loops, including conditional statements and
error handling, and this section shows how to use that functionality together with the
COMSOL API syntax to run COMSOL Multiphysics models in loops.
In this section:
The Parametric Sweep Node
Running Model in a Loop Using the MATLAB Tools
142 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
You can run an M-file for a model from scratch if required, for example, to generate
the geometry in loop.
The model run inside a MATLAB loop is not automatically saved. Make
sure to save the model at each iteration using the command mphsave to
save the model object.
If you are not interested in saving the entire model object at each
iteration, you can extract data and store it in the MATLAB workspace.
See Extracting Results to find the most suitable function to your model.
When running loops in MATLAB, the iteration progress is taken care of by MATLAB;
only the COMSOL commands are executed in the COMSOL server.
You can generate as many nested loops as required and combine the loop with other
MATLAB conditional statements such as if and switch or error handling statements
such as try/catch. Or break the loop with break, or jump to the next loop iteration
with continue.
See the MATLAB help for more information about the MATLAB
commands for, while, if, switch, try/catch, break, and continue.
143
144 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
where myscript is the M-script, saved as myscript.m, that contains the operation to
run at the MATLAB prompt.
COMSOL Multiphysics does not automatically save the model. You need
to make sure that the model is saved before the end of the execution of
the script. See Loading and Saving a Model.
You can also run the script in batch without the MATLAB desktop and the MATLAB
splash screen. Enter this command:
comsol server matlab myscript -nodesktop -mlnosplash
145
2 In the same terminal window change the path to the COMSOL installation
directory:
cd COMSOL_path/mli
3 From that location, start MATLAB without display and run the mphstart function
For more information about how to connect MATLAB to a COMSOL server see
Starting COMSOL with MATLAB on Windows / Mac OSX / Linux.
146 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
where <soltag> is the solver node tag used to assemble the system matrices and out
is a cell array containing the list of the matrices to evaluate. The output data str
returned by mphmatrix is a MATLAB structure, and the fields correspond to the
assembled system matrices.
The system matrices that can be extracted with mphmatrix are listed in the table:
EXPRESSION
DESCRIPTION
Stiffness matrix
Load vector
Constraint vector
Constraint Jacobian
Damping matrix
Mass matrix
NF
NP
MP
MLB
MUB
Kc
Lc
WO R K I N G W I T H M A T R I C E S
147
EXPRESSION
DESCRIPTION
Dc
Ec
Null
Nullf
ud
Particular solution ud
uscale
Scale vector
The default selection of linearization points for the system matrix assembly is the
current solution of the solver node associated to the assembly.
If the linearization point is not specified when calling mphmatrix,
COMSOL automatically runs the entire solver configuration before
assembling and extracting the matrices.
Save time during the evaluation by manually setting the linearization point. Use the
initmethod property as in this command:
str = mphmatrix(model, <soltag>, 'out', out, 'initmethod', method);
where <initsoltag> is the solver tag to use for linearization points. You can also set
the initsol property to 'zero', which corresponds to using a null solution vector as a
linearization point. The default is the current solver node where the assemble node is
associated.
For continuation, time-dependent, or eigenvalue analyses you can set the solution
number to use as a linearization point. Use the solnum property:
str = mphmatrix(model, <soltag>, 'out', out, 'solnum', <solnum>);
where <solnum> is an integer value corresponding to the solution number. The default
value is the last solution number available with the current solver configuration.
148 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
The following illustrates how to use the mphmatrix command to extract eliminated
system matrices of a stationary analysis and linear matrix system at the MATLAB
prompt.
The model consists of a linear heat transfer problem solved on a unit square with a 1e5
W/m^2 surface heat source and temperature constraint. Only one quarter of the
geometry is represented in the model. For simplification reasons, the mesh is made of
four quad elements.
These commands set the COMSOL model object:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 2);
geom1.feature.create('sq1', 'Square');
geom1.run;
mat1 = model.material.create('mat1');
def = mat1.materialModel('def');
def.set('thermalconductivity',{'4e2'});
ht = model.physics.create('ht', 'HeatTransfer', 'geom1');
hs1 = ht.feature.create('hs1','HeatSource',2);
hs1.selection.set(1);
hs1.set('Q',1,'1e5');
temp1 = ht.feature.create('temp1','TemperatureBoundary',1);
temp1.selection.set([1 2]);
mesh1 = model.mesh.create('mesh1','geom1');
dis1 = mesh1.feature.create('dis1','Distribution');
dis1.selection.set([1 2]);
dis1.set('numelem','2');
mesh1.feature.create('map1','Map');
std1 = model.study.create('std1');
std1.feature.create('stat','Stationary');
std1.run;
WO R K I N G W I T H M A T R I C E S
149
To extract the solution vector of the computed solution, run the function mphgetu as
in this command:
U = mphgetu(model);
To assemble and extract the eliminated stiffness matrix and the eliminated load vector,
set the linearization point to the initial value expression by entering:
MA = mphmatrix(model ,'sol1', ...
'Out', {'Kc','Lc','Null','ud','uscale'},...
'initmethod','sol','initsol','zero');
Solve for the eliminated solution vector using the extracted eliminated system:
Uc = MA.Null*(MA.Kc\MA.Lc);
Now compare both solution vector U and U1 computed by COMSOL and by the
matrix operation, respectively.
This command set the matrices of a linear system stored in the MATLAB structure
<str> into the model. The linear system is associated to the solver sequence <soltag>
and is to be solved by the solver <soltypetag>.
mphinputmatrix only supports the solver types Stationary, Eigenvalue, and Time.
A valid structure <str> for a stationary solver includes the following fields:
150 |
FIELD
DESCRIPTION
Stiffness matrix
Load vector
Constraint vector
Constraint Jacobian
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
DESCRIPTION
Stiffness matrix
Load vector
Constraint vector
Constraint Jacobian
Damping matrix
Mass matrix
You can also include the Constraint force Jacobian vector, defined in the field NF.
Once the linear system is loaded in the model, you can directly run the solver.
The system matrices are not stored in the model once it is saved in the
MPH-format or loaded to the COMSOL Desktop.
This example deals with heat transfer in solids physics. The geometry and physics
settings are already set in the model and saved in the MPH-format. The Model
MPH-file comes with the COMSOL installation.
At the MATLAB prompt you load the model and add an additional line heat source to
the model directly in the system matrix by manually changing the load vector. Then
compute the solution of the modified system in COMSOL.
Load the base Model MPH-file and display the geometry:
model = mphload('model_tutorial_llmatlab.mph');
mphgeom(model)
WO R K I N G W I T H M A T R I C E S
151
Draw the line to be used as a line heat source in the model and plot the modified
geometry:
b1 = model.geom('geom1').feature.create('b1', 'BezierPolygon');
b1.set('p', {'1e-2' '5e-2'; '1e-2' '5e-2'; '1e-2' '1e-2'});
mphgeom(model,'geom1','edgelabels','on','facealpha',0.5);
In the figure below you can see that the added line as the index 21:
152 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
The heat transfer physics interface automatically compute for internal DOFs in order
to evaluate fluxes accurately at the boundaries. Deactivate the internal DOFs with the
command:
Shape.set('boundaryFlux_temperature', 1, '0');
Now extract the matrices of the linear system associated to the solver sequence sol1:
ME = mphmatrix(model,'sol1','Out',{'K' 'L' 'M' 'N'},...
'initmethod','sol','initsol','zero');
To retrieve the degrees of freedom that belong to edge 21, you need to get the
geometric mesh data:
[stats,data] = mphmeshstats(model);
With the mesh data structure data, you can get the element indices that belong to
edge 2. Use the MATLAB find function to list all the indices:
WO R K I N G W I T H M A T R I C E S
153
elem_idx = find(data.elementity{1}==21)'
With the function mphxmeshinfo, retrieve the finite element mesh information
associated to solver sequence sol1:
info = mphxmeshinfo(model,'soltag','sol1','studysteptag','v1');
In the info structure you can get the DOFs indices that belong to the edge element
defined with the indices elem_idx:
edgdofs_idx = [];
for i = 1:length(elem_idx)
edgdofs_idx = [edgdofs_idx;
info.elements.edg.dofs(:,elem_idx(i))];
end
edgdofs_idx might contain duplicate DOFs indices. This is because the information
is from the element level; the duplicate indices correspond to the connecting node
between two adjacent elements.
= unique(edgdofs_idx);
Edit the load vector for the DOF that belong to edge 21, the total applied power is
50 W:
ME.L(unique_idx+1) = 50/length(unique_idx);
Now that the linear system has been modified, set it back in the model:
mphinputmatrix(model,ME,'sol1','s1')
154 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
mphplot(model,'pg1','rangenum',1)
WO R K I N G W I T H M A T R I C E S
155
y = D C McA McB u
Let Null be the PDE constraint null-space matrix and ud a particular solution fulfilling
the constraints. The solution vector U for the PDE problem can then be written
U =
Null x
+ ud + u0
where u0 is the linearization point, which is the solution stored in the sequence once
the state-space export feature is run.
EXTRACT STATE-SPACE MATRICES
The function mphstate requires that the input variables, output variables, and the list
of the matrices to extract in the MATLAB workspace are all defined:
str = mphstate(model, <soltag>, 'input', <input>, ...
'output', <output>, 'out', out);
where <soltag> is the solver node tag used to assemble the system matrices listed in
the cell array out, and <input> and <output> are cell arrays containing the list of the
input and output variables, respectively.
The output data str returned by mphstate is a MATLAB structure and the fields
correspond to the assembled system matrices.
The input variables need to be defined as parameters in the COMSOL model. The
output variables are defined as domain point probes or global probes in the COMSOL
model.
The system matrices that can be extracted with mphstate are listed in the table:
156 |
EXPRESSION
DESCRIPTION
MA
McA matrix
MB
McB matrix
A matrix
B matrix
C matrix
D matrix
Mc
Mc matrix
Null
Null matrix
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
EXPRESSION
DESCRIPTION
ud
ud vector
x0
x0 vector
To keep the state-space feature node, set the property keepfeature to on:
str = mphstate(model, <soltag>, 'input', <input>, ...
'output', <output>, 'out', out, 'keepfeature', 'on');
SET LINEARIZATION POINTS
mphstate uses linearization points to assemble the state-space matrices. The default
linearization point is the current solution provided by the solver node, to which the
state-space feature node is associated. If there is no solver associated to the solver
configuration, a null solution vector is used as a linearization point.
You can manually select the linearization point to use. Use the initmethod property
to select a linearization point:
str = mphstate(model, <soltag>, 'input', <input>, ...
'output', <output>, 'out', out, 'initmethod', method);
where <initsoltag> is the solver tag to use for a linearization point. You can also set
the initsol property to 'zero', which corresponds to using a null solution vector as a
linearization point. The default is the current solver node where the assemble node is
associated.
For continuation, time-dependent, or eigenvalue analyses you can set which solution
number to use as a linearization point. Use the solnum property:
WO R K I N G W I T H M A T R I C E S
157
where <solnum> is an integer value corresponding to the solution number. The default
value is the last solution number available with the current solver configuration.
EXAMPLE: EXTRACTING STATE-SPACE MATRICES
To illustrate how to use the mphstate function to extract the state-space matrices of
the model heat_transient_axi from the COMSOL Multiphysics model library. To be
able to extract the state-space matrices you need to modify an existing model. First,
create a parameter T0 that is set as the external temperature:
model = mphload('heat_transient_axi');
model.param.set('Tinput','1000[degC]');
model.physics('ht').feature('temp1').set('T0', 1, 'Tinput');
Extract the matrices of the state-space system using Tinput as an input variable and
the probe comp1.ppb1 as an output variable:
M = mphstate(model,'sol1','out',{'Mc' 'MA' 'MB' 'C' 'D' 'x0'},...
'input','Tinput', 'output', 'comp1.ppb1');
Compare the solution computed with the system and the one computed with
COMSOL Multiphysics (see Figure 4-1):
plot(t,y)
hold on
Tnum = mphinterp(model,'T','coord',[0.2;0.3],'t',t);
158 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
plot(t,Tnum,'r+')
Figure 4-1: Temperature distribution computed with the state-space system (blue line) and
COMSOL Multiphysics (red marker).
WO R K I N G W I T H M A T R I C E S
159
This section includes information about Specifying the Solution Object and the
Output Format.
The function mphsolinfo replaces the function mphgetp. If you are
using the later you can now replace it as it will be removed in a future
version.
SPECIFYING THE SOLUTION OBJECT
To retrieve the information of a specific solution object, set the soltag property with
the solver tag soltag associated to the solution object:
info = mphsolinfo(model, 'soltag', <soltag>);
If there are several solution data sets attached to the solver, for example, solution data
sets with different selections, specify the data set to use to get the solution object
information with the dataset property:
info = mphsolinfo(model, 'dataset', <dsettag>);
160 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
OUTPUT FORMAT
The output info is a MATLAB structure. The default fields available in the structure
are listed in the table:
FIELDS
DESCRIPTION
soltag
study
size
nummesh
sizes
soltype
Solver type
solpar
Parameter name
sizesolvals
solvals
paramsweepnames
paramsweepvals
batch
Batch information
dataset
To get the information about the number of solutions, set the property nu to on:
info = mphsolinfo(model, 'nu', 'on');
DESCRIPTION
NUsol
NUreacf
NUadj
NUfsens
NUsens
DESCRIPTION
type
psol
E X T R A C T I N G S O L U T I O N I N F O R M A T I O N A N D S O L U T I O N VE C T O R S
161
BATCH FIELDS
DESCRIPTION
sol
seq
DESCRIPTION
solutions
sol#
162 |
FIELDS
DESCRIPTION
dataset
study
sequencetype
cellmap
values
parameters
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
FIELDS
DESCRIPTION
mapheaders
map
You can also retrieve the solution objects and solution data sets related to a specific
parameter value with the command:
info = mphsolutioninfo(model,'parameters',{'e1','v1','tol1'});
To retrieve the information of a specific solution object, set the soltag property with
the solver tag soltag associated to the solution object:
info = mphsolutioninfo(model, 'soltag', <soltag>);
If there are several solution data sets attached to the solver, for example, solution data
sets with different selections, specify the data set to use to get the solution object
information with the dataset property:
info = mphsolutioninfo(model, 'dataset', <dsettag>);
To include the cellmap field in the info.sol# substructure set the property cellmap
to on:
info = mphsolutioninfo(model, 'cellmap', 'on');
Improve the visibility of the map table by sorting the row using either the column
number or the name in the map header:
info = mphsolutioninfo(model, 'sort', <idx>);
E X T R A C T I N G S O L U T I O N I N F O R M A T I O N A N D S O L U T I O N VE C T O R S
163
This example shows how to use the function mphsolutioninfo to retrieve solution
information in a mode combining a parametric sweep and transient analysis.
Start by loading the base model model_tutorial_llmatlab from the COMSOL
Multiphysics model library; this model contains base settings for a thermal analysis:
model = mphload('model_tutorial_llmatlab');
Now create a study combining a parametric sweep and a transient study step. The
parametric sweep consist by varying the parameters that set the heat source and the
bottom temperature. This is done with these commands:
std = model.study.create('std');
param = std.feature.create('param', 'Parametric');
param.setIndex('pname', 'power', 0);
param.setIndex('plistarr', '30 60 90',0);
param.setIndex('pname', 'Temp', 1);
param.setIndex('plistarr', '300 320', 1);
time = std.feature.create('time', 'Transient');
time.set('tlist', 'range(0,1,25)');
Set the sweep type to generate all possible combinations of the parameters power and
tf and compute the study:
param.set('sweeptype', 'filled');
std.run;
Once the solution is computed (it takes about 90 seconds), you can retrieve the
solution information in the model:
info = mphsolutioninfo(model)
The output info is a structure containing nine fields. By navigating in the info
structure you can retrieve how the solutions are stored in the model.
info.sol1 contains the solution information related to the solver sequence sol1.
The associated dataset is dset1.
info.sol2 contains the solution information for the parametric sequence. This
regroups the solution vectors computed for all outer parameters.
The other substructures contain the solution information for all possible outer solution
combinations.
Get the relation between the parameter values and the inner and outer solution
numbers:
map = info.sol2.map
164 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
To get the list of the solutions that contain the given parameters enter:
solnum = info.solutions
where U is an Nx1 double array, with N the number of degrees of freedom of the
COMSOL Multiphysics model.
This section includes information about Specifying the Solution and the Output
Format.
You can refer to the function mphxmeshinfo to receive the DOF name or
the node coordinates in the solution vector, see Retrieving Xmesh
Information.
SPECIFYING THE SOLUTION
Change the solver node to extract the solution vector with the property solname:
U = mphgetu(model, 'soltag', <soltag>);
where <solnum> a positive integer vector that corresponds to the solution number to
use to extract the solution vector. For time-dependent and continuation analyses, the
E X T R A C T I N G S O L U T I O N I N F O R M A T I O N A N D S O L U T I O N VE C T O R S
165
default value for the solnum property is the last solution number. For an eigenvalue
analysis, it is the first solution number.
A model can contain different types of solution vectorsthe solution of the problem,
the reaction forces vector, the adjoint solution vector, the functional sensitivity vector,
or the forward sensitivity. In mphgetu, you can specify the type of solution vector to
extract with the type property:
U = mphgetu(model, 'type', type);
where type is one of these strings 'sol', 'reacf', 'adj', or 'sens' used to extract the
solution vector, the reaction forces, the functional sensitivity, or the forward sensitivity,
respectively.
OUTPUT FORMAT
mphgetu returns the default the solution vector. Get the time derivative of the solution
In case the property solnum is set as a 1x M array and the solver node only uses one
mesh to create the solution, the default output is an NxM array, where N is the number
of degrees of freedom of the model. Otherwise, the output U is a cell array that contains
each solution vector. If you prefer to have the output in a cell array format, set the
property matrix to off:
U = mphgetu(model, 'solnum', <solnum>, 'matrix', 'off');
166 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
where info is a MATLAB structure that contains the fields in the table:
FIELDS
DESCRIPTION
soltag
ndofs
fieldnames
fieldndofs
meshtypes
geoms
dofs
nodes
elements
167
DESCRIPTION
geomnums
coords
nodes
dofnames
Variable names
nameinds
DESCRIPTION
coords
Nodes coordinates
dofnames
Variable names
dofs
NxM array containing the index (0-based) of the dofs for each
node. N being the length of dofnames and M the number of nodes
DESCRIPTION
meshtypes
type
The type substructure lists the information for each element. The possible mesh types
are vtx, edg, quad, tri, quad, tet, hex, prism, and pyr. The substructure type
contains the fields listed in the table:
FIELDS
DESCRIPTION
localcoords
localdofcoords
localdofnames
nodes
dofs
To specify the solver node to retrieve the xmesh information, set the property solname
as in this command:
info = mphxmeshinfo(model, 'soltag', <soltag>);
168 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
where <soltag> is the tag of the solver used to extract the xmesh information.
To retrieve the xmesh information for a specific study step node, specify it with the
property studysteptag:
info = mphxmeshinfo(model, 'studysteptag', <studysteptag>);
where <meshcase> is the mesh case number or the tag of the mesh case.
169
170 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
If a new model object is created with the MATLAB object name model,
restart mphnavigator in order to have the updated model information.
171
The Settings menu only contains the Advanced options. Select or deselect the
advanced model object methods that are displayed in the Model Viewer tree.
The Help menu.
THE SHORTCUT ICON
Just under the menu bar are two shortcut buttonsPlot and Help.
These buttons are unavailable if no method has been selected in the Model Tree section.
The Plot button displays the geometry, the mesh, or a plot group in a MATLAB figure.
The Help button displays the page of the COMSOL API Reference Manual of the
corresponding method in your default web browser.
T H E M O D E L TRE E S E C T I O N
The Model Tree section has the list of the nodes of the model object. Use the scroll bar
to the right to scroll down the list and click the + icon to expand the model object
feature nodes.
172 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
When a feature node is selected, its associated command is listed just beneath the
model tree. Click Copy to copy syntax to the clipboard and then paste it in your script.
The Model Tree list is slightly different to the Model Builder list available in
the COMSOL Desktop. This is because mphnavigator displays all
feature nodes and does not use the same filter as in the COMSOL
Desktop to order the available feature nodes.
THE PROPERTIES SECTION
The Properties section lists the properties of a selected feature node and the associated
values.
Click Copy Table to copy the entire properties table to the clipboard, then paste into a
text or spreadsheet editor.
Click Copy to copy a selected cell in the properties table.
173
The Methods section lists all the methods associated to the feature node selected in the
Model Tree section.
Click Filter to filter the reduce the methods list to the one that returns simple
information.
Select a method in the list to get its associated syntax at the button of the Methods
section. Use the Copy button to copy the syntax to the clipboard.
To list the subfeature of the node type model.feature enter the command:
mphmodel(model.feature)
Use the flag -struct to return the model object information to MATLAB structure:
str = mphmodel(model.feature,'-struct')
str is a MATLAB structure and the fields consist of each feature node associated to the
node model.feature.
174 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
175
where str is a MATLAB structure that lists all the properties and the value of the
feature node model.feature.
where model.feature is the node to get the expressions from and expr is an Nx3 cell
array where N is the number of expressions for this node.
where seltag is the tag a selection node defined in the model object. The output str
is a MATLAB structure with the following fields:
dimension, the space dimension of the geometry entity selected,
geom, the tag of the geometry node used in the selection,
entities, the list of the entity indexes listed in the selection, and
isGlobal, Boolean value to indicate if the selection is global or not.
176 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
H A N D L I N G E RRO R S A N D WAR N I N G S
177
Alternatively mphshowerrors can also return the error and warning information in a
MATLAB variable:
str = mphshowerrors(model)
where str is an Nx2 cell array, with N the number of error and warning nodes that
contain the model object. str{i,1}, which contains the location in the model of the
i:th error/warning message, and str{i,2} contains the message of the ith
error/warning message.
178 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
Increasing the memory allocated for the Java process necessarily decreases
the memory available for the solver.
Either set The COMSOL Server Java Heap Size or The MATLAB Java Heap Size.
THE COMSOL SER VER JAVA HEAP SIZE
The Java heap size settings for the COMSOL server process are stored in the
comsolserver.ini file. You can find this file in the COMSOL44/bin/<arch> directory.
<arch> correspond to the architecture of the machine where the COMSOL server is
running (win32, win64, maci64, glnx86, or glnxa64).
Edit the file with a text editor, the Java heap settings are defined as in the following
lines:
-Xss4m
179
-Xms40m
-Xmx1024m
-XX:MaxPermSize=256m
The values are given in Mb, modify these value to satisfy the model requirements.
TH E MATLA B JAVA HE AP S IZE
To modify the Java heap size you need to edit the java.opts file available under the
COMSOL with MATLAB start-up directory. The java.opts file is stored by default
with the following settings:
-Xss4m
-Xmx768m
-XX:MaxPermSize=256m
The values are given in Mb, modify these value to satisfy the model requirements.
To modify the MATLAB Java Heap size the java.opts file has to be stored at the
MATLAB start-up directory. This is the case when starting COMSOL with MATLAB.
You have to enable the feature update prior to computing the solution unless the
model expressions would not be evaluated according to the model settings. Enabling
the feature update is also necessary before building the geometry or the mesh in case
these are defined using expressions.
To enable the feature model update, enter the command:
model.disableUpdates(false);
180 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
When the model history is disabled you no longer see the commands used to set up
the model when saving it as an M-file.
181
The simplified GUI only allows the user to compute a heat transfer problem on a given
geometry. The user can only change the radius and the position of the bottom circle
geometry. The heat source applied to the bottom circle is also defined by the user.
The button executes the building operation of the geometry and mesh. Another
button executes the computation of the solution.
182 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
as an MPH-file.
2 Load the model into COMSOL Multiphysics 4.4 and verify that the model settings
have been translated correctly. In addition, verify that the model can be meshed and
solved.
3 Compact the model history and save the model as a M-file.
183
184 |
C H A P T E R 4 : WO R K I N G W I T H M O D E L S
185
To evaluate a MATLAB function from in the COMSOL Multiphysics model you need
to add a MATLAB node in the model object where the function name, the list of the
arguments, and, if required, the function derivatives, are defined.
To add a MATLAB function node, on the Home toolbar, click Functions and choose
Global>MATLAB(
).
186 |
C H A P T E R 5 : C A L L I N G M AT L A B F U N C T I O N S
T H E M AT L A B F U N C T I O N F E A T U R E N O D E
187
D E F I N I N G T H E M AT L A B F U N C T I O N
Under Functions, define the function name and the list of the function arguments.
In the table columns and rows, enter the Function name and the associated function
Arguments. The table supports multiple function definitions. You can define several
functions in the same table or add several MATLAB nodes, as you prefer.
PLOTTING THE FUNCTION
To plot the function you first need to define limits for the arguments. Expand the Plot
Parameters section and enter the desired value in the Lower limit and Upper limit
columns. In the Plot Parameters table the number of rows correspond to the number
of input arguments of the function. The first input argument corresponds to the top
row.
In case there are several functions declared in the Functions table, only the function that
has the same number of input arguments as the number of filled in rows in the Plot
Parameters table is plotted.
188 |
C H A P T E R 5 : C A L L I N G M AT L A B F U N C T I O N S
If several functions have the same number of input arguments, the first function in the
table (from top to bottom) is plotted. Use the Move up (
) and Move down (
)
buttons to change the order of functions in the table.
EXAMPLE: DEFINE THE HANKEL FUNCTION
Assume that you want to use MATLABs Bessel function of the third kind (Hankel
function) in a COMSOL model. Add a MATLAB function node, then define the
following settings:
FUNCTION NAME
ARGUMENTS
besselh
nu, x
To plot the function you need first to define the lower and upper limits for both nu
and x. In the Plot Parameters table set the first row (which corresponds to the first
argument nu) of the Lower limit column to 0 and the Upper limit column to 5 and set
the second row (corresponding of x) of the Lower limit column to 0 and the Upper limit
column to 10:
T H E M AT L A B F U N C T I O N F E A T U R E N O D E
189
190 |
C H A P T E R 5 : C A L L I N G M AT L A B F U N C T I O N S
Define the function name and function arguments with the command:
model.func(<ftag>).setIndex('funcs', <function_name>, 0, 0);
model.func(<ftag>).setIndex('funcs', <arglist>, 0, 1);
where <function_name> is a string set with the function name and <arglist> is a
string that defines the list of the input arguments.
T H E M AT L A B F U N C T I O N F E A T U R E N O D E
191
This function looks good at first but it does not work in COMSOL Multiphysics
because the input x is a matrix:
Element-by-element multiplication, division, and power must be usedthat is, the
operators .*, ./, and .^. Replace expressions such as x/1.6 and x^2+0.3 with
x./1.6 and x.^2+0.3, respectively.
The comparison x 0.6 returns a matrix with ones (true) for the entries where the
expression holds true and zeros (false) where it is false. The function evaluates the
conditional statement if, and only if, all the entries are true (1).
You can replace the if statement with a single assignment to the indices retrieved from
the x 0.6 operation and another assignment to the indices where x 0,6 . The
function could then look like this:
function c = func2(x)
c = (x./1.6).*(x>0.6) + (x.^2+0.3).*(x<=0.6);
Updating Functions
If the function M-file is modified using a text editor, click Clear Functions to ensure that
the functions modifications are updated in the COMSOL Multiphysics model.
An alternative is to select the Clear functions automatically before solving check box.
192 |
C H A P T E R 5 : C A L L I N G M AT L A B F U N C T I O N S
argument. Finally in the Function derivative column enter the expression for the
corresponding derivative.
ARGUMENT
FUNCTION DERIVATIVE
besselh
nu
(besselh(nu-1,x)-besselh(nu+1,x))/2
besselh
(besselh(0,x)-besselh(2,x))/2
T H E M AT L A B F U N C T I O N F E A T U R E N O D E
193
194 |
C H A P T E R 5 : C A L L I N G M AT L A B F U N C T I O N S
Command Reference
The main reference for the syntax of the commands available with LiveLink for
MATLAB is the COMSOL API Reference Manual. This section documents
195
Summary of Commands
colortable
mphmesh
mphcd
mphmeshstats
mphdoc
mphmin
mpheval
mphmodel
mphevalglobalmatrix
mphmodellibrary
mphevalpoint
mphnavigator
mphgeom
mphparticle
mphgetadj
mphplot
mphgetcoords
mphsave
mphgetexpressions
mphsearch
mphgetproperties
mphselectbox
mphgetselection
mphselectcoords
mphgetu
mphshowerrors
mphglobal
mphsolinfo
mphimage2geom
mphsolutioninfo
mphinputmatrix
mphstart
mphint2
mphstate
mphinterp
mphtable
mphload
mphversion
mphmatrix
mphviewselection
mphmax
mphxmeshinfo
mphmean
196 |
C o m m a nds G r ou p ed b y Fu n c t i on
INTERFACE FUNCTIONS
FUNCTION
PURPOSE
mphcd
mphdoc
mphload
mphsave
mphstart
mphversion
GEOMETRY FUNCTIONS
FUNCTION
PURPOSE
mphgeom
mphimage2geom
mphviewselection
MESH FUNCTIONS
FUNCTION
PURPOSE
mphmesh
mphmeshstats
UTILITY FUNCTIONS
FUNCTION
PURPOSE
mphgetadj
mphgetcoords
mphgetu
mphinputmatrix
mphmatrix
mphselectbox
mphselectcoords
mphsolinfo
197
FUNCTION
PURPOSE
mphsolutioninfo
mphstate
mphxmeshinfo
POSTPROCESSING FUNCTIONS
FUNCTION
PURPOSE
mpheval
mphevalglobalmatrix
mphevalpoint
mphglobal
mphint2
mphinterp
mphmax
mphmean
mphmin
mphparticle
mphplot
mphtable
198 |
FUNCTION
PURPOSE
mphgetproperties
mphgetexpressions
mphgetselection
mphmodel
mphmodellibrary
mphnavigator
mphsearch
mphshowerrors
colortable
Return a MATLAB colormap for a COMSOL Multiphysics color table.
Purpose
colortable
Syntax
map = colortable(name)
Description
map = colortable(name) returns the color table (of 1024 colors) for name, where
name can be one of the following strings:
Cyclic - A color table that varies the hue component of the hue-saturation-value
color model, keeping the saturation and value constant (equal to 1). The colors
begin with red, pass through yellow, green, cyan, blue, magenta, and return to red.
This table is useful to display periodic functions and has a sharp color gradient.
Disco - This color table spans from red through magenta and cyan to blue.
Discolight - Similar to Disco but uses lighter colors.
Grayscale - A color table that uses no color, only the gray scale varying linearly
0.05, 0.05). This color table overcomes two disadvantages that the GrayScale
color table has when used for printouts on paperit gives the impression of being
dominated by dark colors and that white cannot be distinguished from the
background.
Rainbow - The color ordering in this table corresponds to the wavelengths of the
visible part of the electromagnetic spectrum: beginning at the small-wavelength end
with dark blue, the colors range through shades of blue, cyan, green, yellow, and
red.
Rainbowlight - Similar to Rainbow, this color table uses lighter colors.
Thermal - Ranges from black through red and yellow to white, which corresponds
red, yellow, and white, which means that the black and red regions become larger.
Traffic - Spans from green through yellow to red.
Trafficlight - Similar to Traffic but uses lighter colors.
Wave - Ranges linearly from blue to light gray, and then linearly from white to red.
When the range of the visualized quantity is symmetric around zero, the color red
or blue indicates whether the value is positive or negative, and the saturation
indicates the magnitude.
199
colortable
Wavelight - Similar to Wave and ranges linearly from a lighter blue to white
(instead of light gray) and then linearly from white to a lighter red.
200 |
mphcd
Change directory to the directory of the model
Purpose
mphcd
Syntax
mphcd(model)
Description
mphload, mphsave
201
mphdoc
Return HTML help of a specified function.
Purpose
mphdoc
Syntax
mphdoc arg1
mphdoc arg1 arg2
Description
mphdoc arg1 returns the HTML documentation associated to the function arg1.
mphdoc arg1 arg2 returns the HTML documentation associated to the feature
arg2 of the method arg1.
mphdoc arg1 -web returns the HTML documentation in the default web browser.
Example
202 |
mpheval
Evaluate expressions on node points.
Purpose
mpheval
Syntax
pd = mpheval(model,{e1,...,en},...)
Description
expressions e1,...,en.
The output value pd is a structure with fields expr, p, t, ve, unit and fields for data
values.
The field expr contains the expression name evaluated.
For each expression e1,...,en a field with the name d1,... dn is added with
the numerical values. The columns in the data value fields correspond to node
point coordinates in columns in p. The data contains only the real part of
complex-valued expressions.
The field p contains node point coordinate information. The number of rows in
p is the number of space dimensions.
The field t contains the indices to columns in p of a simplex mesh, each column
in t representing a simplex.
The field ve contains indices to mesh elements for each node point.
The field unit contains the list of the unit for each expression.
The function mpheval accepts the following property/value pairs:
TABLE 6-1: PROPERTY/VALUE PAIRS FOR THE MPHEVAL COMMAND.
PROPERTY
PROPERTY
VALUE
DEFAULT
DESCRIPTION
Complexfun
off | on
on
Complexout
off | on
off
Dataonly
off | on
off
Dataset
String
Edim
point |
edge |
boundary |
domain | 0
| 1 | 2 | 3
Geometry
space
dimension
Matherr
off | on
off
Outersolnum
Positive
integer |
all | end
203
mpheval
PROPERTY
VALUE
DEFAULT
DESCRIPTION
Pattern
lagrange |
gauss
lagrange
Phase
Scalar
Recover
off | ppr |
pprint
off
Refine
Integer
Selection
Integer
vector |
string |
all
All
domains
Smooth
Internal |
none |
everywhere
internal
Smoothing setting
Solnum
Integer
vector |
all | end
all
Double
array
The property Dataset controls which data set is used for the evaluation. Data Sets
contain or refer to the source of data for postprocessing purposes. Evaluation is
supported only on Solution Data Sets.
The property Edim decides which elements to evaluate on. Evaluation takes place
only on elements with space dimension Edim. If not specified, Edim equal to the
space dimension of the geometry is used. The setting is specified as one of the
following strings 'point', 'edge', 'boundary' or 'domain'. In previous
versions it was only possible to specify Edim as a number. For example, in a 3D
model, if evaluation is done on edges (1D elements), Edim is 1. Similarly, for
boundary evaluation (2D elements), Edim is 2, and for domain evaluation (3D
elements), Edim is 3 (default in 3D).
Use Recover to recover fields using polynomial-preserving recovery. This
techniques recover fields with derivatives such as stresses or fluxes with a higher
theoretical convergence than smoothing. Recovery is expensive so it is turned off by
default. The value pprint means that recovery is performed inside domains. The
value ppr means that recovery is also applied on all domain boundaries.
204 |
mpheval
The property Refine constructs evaluation points by making a regular refinements
of each element. Each mesh edge is divided into Refine equal parts.
The property Smooth controls if the post data is forced to be continuous on element
edges. When Smooth is set to internal, only elements not on interior boundaries are
made continuous.
The property Solnum is used to select the solution to plot when a parametric,
eigenvalue or time-dependent solver has been used to solve the problem.
The property Outersolnum is used to select the solution to plot when a parametric
sweep has been used in the study.
When the property Phase is used, the solution vector is multiplied with
exp(i*phase) before evaluating the expression.
The expressions e1,...,en are evaluated for one or several solutions. Each solution
generates an additional row in the data fields of the post data output structure. The
property Solnum and t control which solutions are used for the evaluations. The
Solnum property is available when the data set has multiple solutions, for example
in the case of parametric, eigenfrequency, or time-dependent solutions. The t
property is available only for time-dependent problems. If Solnum is provided, the
solutions indicated by the indices provided with the Solnum property are used. If t
is provided solutions are interpolated. If neither Solnum nor t is provided, all
solutions are evaluated.
For time-dependent problems, the variable t can be used in the expressions ei. The
value of t is the interpolation time when the property t is provided, and the time
for the solution, when Solnum is used. Similarly, lambda and the parameter are
available as eigenvalues for eigenvalue problems and as parameter values for
parametric problems, respectively.
Example
Evaluate both the total heat flux magnitude and the temperature:
data = mpheval(model,{'ht.tfluxMag', 'T'});
205
mpheval
data = mpheval(model,'T','dataonly','on');
Evaluate the temperature at every time step computed with power set to 30:
model = mphload('model_tutorial_llmatlab');
std = model.study.create('std');
param = std.feature.create('param','Parametric');
time = std.feature.create('time','Transient');
time.set('tlist', 'range(0,1,25)');
param.setIndex('pname','power',0);
param.setIndex('plistarr','30 60 90',0);
std.run;
data = mpheval(model,'T','dataset','dset2');
Evaluate the temperature at every time step computed with power set to 90:
data = mpheval(model,'T','dataset','dset2','outersolnum',3);
See also
206 |
mphevalglobalmatrix
Evaluate global matrix variables.
Purpose
mphevalglobalmatrix
Syntax
M = mphevalglobalmatrix(model,expr,...)
Description
PROPERTY
VALUE
Dataset
String
DEFAULT
DESCRIPTION
Example
Evaluate the S-parameters matrix using the solution data set dset4:
M = mphevalglobalmatrix(model,'emw.SdB','dataset','dset4');
See also
207
mphevalpoint
Evaluate expressions at geometry vertices.
Purpose
mphevalpoint
Syntax
[v1,...,vn] = mphevalpoint(model,{e1,...,en},...)
[v1,...,vn,unit] = mphevalpoint(model,{e1,...,en},...)
Description
the unit of all expressions e1,...,en in the 1xN cell array unit.
The function mphevalpoint accepts the following property/value pairs:
TABLE 6-3: PROPERTY/VALUE PAIRS FOR THE MPHEVAL COMMAND.
208 |
PROPERTY
PROPERTY
VALUE
Dataset
String
Dataseries
none | mean
| int | max
| min | rms
| std | var
none
Matrix
off | on
on
Minmaxobj
Real | abs
real
Outersolnum
Positive
integer |
all | end
Selection
Integer
vector |
string |
all
All
domains
Smooth
Internal |
none |
everywhere
internal
Smoothing setting
Solnum
Integer
vector |
all | end
all
Squeeze
on | off
on
Double
array
DEFAULT
DESCRIPTION
mphevalpoint
The property Dataset controls which data set is used for the evaluation. Data Sets
contain or refer to the source of data for postprocessing purposes. Evaluation is
supported only on Solution Data Sets.
The Dataseries property is used to control any filtering of the data series. The
supported operations are: average (mean), integral (int), maximum (max),
minimum (min), root mean square (rms), standard deviation (std) and variance
(var).
Set the property Matrix to off to get the results in a cell array format.
In case the property Datseries is either min or max, you can specify the how the
value are treated using the property Minmaxobj. Use either the real data or the
absolute data.
The property Solnum is used to select the solution to plot when a parametric,
eigenvalue or time-dependent solver has been used to solve the problem.
The expressions e1,...,en are evaluated for one or several solutions. Each solution
generates an additional row in the data fields of the post data output structure. The
property Solnum and t control which solutions are used for the evaluations. The
Solnum property is available when the data set has multiple solutions, for example
in the case of parametric, eigenfrequency, or time-dependent solutions. The t
property is available only for time-dependent problems. If Solnum is provided, the
solutions indicated by the indices provided with the Solnum property are used. If t
is provided solutions are interpolated. If neither Solnum nor t is provided, all
solutions are evaluated.
For time-dependent problems, the variable t can be used in the expressions ei. The
value of t is the interpolation time when the property t is provided, and the time
for the solution, when Solnum is used. Similarly, lambda and the parameter are
available as eigenvalues for eigenvalue problems and as parameter values for
parametric problems, respectively.
Example
209
mphevalpoint
Evaluate the temperature and the magnitude of the total heat flux on point 5:
[T, heatflux, unit] = mphevalpoint(model,{'T','ht.tfluxMag'},...
'selection',5);
Evaluate the temperature at every time step computed with power set to 30:
model = mphload('model_tutorial_llmatlab');
std = model.study.create('std');
param = std.feature.create('param','Parametric');
time = std.feature.create('time','Transient');
time.set('tlist', 'range(0,1,25)');
param.setIndex('pname','power',0)
param.setIndex('plistarr','30 60 90',0);
std.run;
T = mphevalpoint(model,'T','selection',5,'dataset','dset2');
210 |
mphgeom
Plot a geometry in a MATLAB figure.
Purpose
mphgeom
Syntax
mphgeom(model)
mphgeom(model,geomtag,...)
Description
in a MATLAB figure.
The function mphgeom accepts the following property/value pairs:
TABLE 6-4: PROPERTY/VALUE PAIRS FOR THE MPHGEOM COMMAND
PROPERTY
VALUE
DEFAULT
DESCRIPTION
Parent
Double
Parent axes
Selection
Positive
integer
array
Selection
Entity
point |
edge |
boundary |
domain
Geometric entity to
select
Build
on | off |
current |
string
on
Edgecolor
Char
Edge color
Edgelabels
on | off
off
Edgelabelscolor
Char
Edgemode
on | off
on
Show edges
Facealpha
Double
Facelabels
on | off
off
Facelabelscolor
Char
Facemode
on | off
on
Show faces
Vertexlabels
on | off
off
Vertexlabelscolor
Char
Vertexmode
on | off
off
Show vertices
The Build property determines if mphgeom build the geometry prior to display it.
If the Build property is set with a geometric object tag, the geometry is built up to
that object. mphgeom only displays built geometry objects.
211
mphgeom
Example
212 |
mphmesh, mphviewselection
mphgetadj
Return geometry entity indices that are adjacent to other.
Purpose
mphgetadj
Syntax
n = mphgetadj(model,geomtag,returntype,adjtype,adjnumber)
Description
Example
'point': 0
213
mphgetcoords
Return point coordinates of geometry entities.
Purpose
mphgetcoords
Syntax
c = mphgetcoords(model,geomtag,entitytype,entitynumber)
Description
coordinates of the points that belong to the entity object with the type entitytype
and the index entitynumber.
The entitytype property can be one of 'point', 'edge', 'boundary' or
'domain' following the entity space dimension defined below:
214 |
mphgetexpressions
Get the model variables and model parameters expressions.
Purpose
mphgetexpressions
Syntax
expr = mphgetexpressions(modelnode)
Description
See also
mphnavigator, mphmodel
215
mphgetproperties
Get the properties from a model node
Purpose
mphgetproperties
Syntax
mphproperties(modelnode)
Description
Example
Build the mesh in the model model_tutorial_llmatlab.mph and get the mesh
size properties:
model = mphload('model_tutorial_llmatlab');
model.mesh('mesh1').run;
prop = mphgetproperties(model.mesh('mesh1').feature('size'))
See also
216 |
mphnavigator
mphgetselection
Get information about a selection node.
Purpose
mphgetselection
Syntax
info = mphgetselection(selnode)
Description
node selnode.
The output info is a MATLAB structure defined with the following fields:
dimension, the space dimension of the geometry entity selected.
geom, the geometry tag.
entities, the indexes of the selected entities.
isGlobal, a Boolean expression that indicates if the selection is global.
Example
Add a selection node to the model busbar.mph and retrieve its information:
model = mphload('model_tutorial_llmatlab.mph');
ball = model.selection.create('ball','Ball');
ball.set('entitydim',2);
ball.set('posz',11e-3');
ball.set('r',1e-5);
info = mphgetselection(model.selection('ball'))
See also
mphnavigator
217
mphgetu
Return solution vector.
Purpose
mphgetu
Syntax
U = mphgetu(model,...)
[U,Udot] = mphgetu(model,...)
Description
U = mphgetu(model) returns the solution vector U for the default solution data set.
[U,Udot] = mphgetu(model,...) returns in addition Udot, which is the time
VALUE
DEFAULT
DESCRIPTION
Solname
String
Auto
Solnum
Positive integer
vector
Auto
Type
String
Sol
Solution type
Matrix
off | on
on
The Solname property set the solution data set to use associated with the defined
solver node.
Type is used to select the solution type. This is 'Sol' by default. The valid types are:
'Sol' (main solution), 'Reacf' (reaction force), 'Adj' (adjoint solution),
'Fsens' (functional sensitivity) and 'Sens' (forward sensitivity).
If Solnum is a vector and the result has been obtained with the same mesh then the
solution is stored in a matrix if the Matrix option is set to 'on'
Example
218 |
mphgetu
reacf = mphgetu(model,'type','reacf');
Extract the solution vectors for the first and the last time step:
model = mphload('model_tutorial_llmatlab');
std = model.study.create('std');
param = std.feature.create('param','Parametric');
time = std.feature.create('time','Transient');
time.set('tlist', 'range(0,1,25)');
param.setIndex('pname','power',0);
param.setIndex('plistarr','30 60 90',0);
std.run;
U = mphgetu(model,'solnum',[1,26]);
mphsolinfo
219
mphglobal
Evaluate global quantities.
Purpose
mphglobal
Syntax
[d1,...,dn] = mphglobal(model,{e1,...,en},...)
[d1,...,dn,unit] = mphglobal(model,{e1,...,en},...)
Description
PROPERTY VALUE
DEFAULT
DESCRIPTION
Complexfun
off | on
on
Use complex-valued
functions with real input
Complexout
off | on
off
Dataset
String
Active solution
data set
Matherr
off | on
off
Outersolnum
Positive
integer | all
| end
Phase
Scalar
Solnum
Integer vector
| all | end
all
Double array
Unit
String | cell
array
The property Dataset controls which data set is used for the evaluation. Data Sets
contain or refer to the source of data for postprocessing purposes. Evaluation is
supported only on solution data sets.
When the property Phase is used, the solution vector is multiplied with
exp(i*phase) before evaluating the expression.
The expressions ei are evaluated for one or several solutions. Each solution
generates an additional row in the output data array di. The property Solnum and
t control which solutions are used for the evaluations. The Solnum property is
available when the data set has multiple solutions, for example in the case of
220 |
mphglobal
parametric, eigenfrequency, or time-dependent solutions. The t property is
available only for time-dependent problems. If Solnum is provided, the solutions
indicated by the indices provided with the Solnum property are used. If t is provided
solutions are interpolated. If neither Solnum nor t is provided, all solutions are
evaluated.
For time-dependent problems, the variable t can be used in the expressions ei. The
value of t is the interpolation time when the property t is provided, and the time
for the solution, when Solnum is used. Similarly, lambda and the parameter are
available as eigenvalues for eigenvalue problems and as parameter values for
parametric problems, respectively.
In case of multiple expression if the unit property is defined with a string, the same
unit is used for both expressions. To use different units, set the property with a cell
array. In case of inconsistent unit definition, the default unit is used instead.
Solnum is used to select the solution number when a parametric, eigenvalue or
time-dependent solver has been used.
Outersolnum is used to select the outer solution number when a parametric sweep
Evaluate a global expression at every time step computed with power set to 30:
model = mphload('model_tutorial_llmatlab');
model.cpl.create('maxop', 'Maximum', 'geom1').selection.all;
std = model.study.create('std');
param = std.feature.create('param','Parametric');
time = std.feature.create('time','Transient');
time.set('tlist', 'range(0,1,25)');
param.setIndex('pname','power',0);
param.setIndex('plistarr','30 60 90',0);
221
mphglobal
std.run;
maxT = mphglobal(model,'maxop(T)','dataset','dset2');
Evaluate maxop(T) at every time step computed with power set to 90:
maxT = mphglobal(model,'maxop(T)',dataset','dset2',...
'outersolnum',3);
See also
222 |
mphimage2geom
Convert image data to geometry.
Purpose
mphimage2geom
Syntax
model = mphimage2geom(imagedata,level,...)
Description
PROPERTY VALUE
DEFAULT
DESCRIPTION
Rtol
Value
1e-3
Type
Solid | closed
| open
solid
Curvetype
Auto | polygon
auto
Scale
Value
Mindist
Value
Compose
on | off
on
Rectangle
on | off
off
The default curve types creates a geometry with the best suited geometrical
primitives. For interior curves this is Interpolation Curves and for curves that are
touching the perimeter of the image, Polygons is used.
Example
Create a geometry object following the contour made with point of value 50 and
set a scaling factor of 1e-3:
223
mphimage2geom
model = mphimage2geom(p, 50,'scale',1e-3);
figure(2); mphgeom(model)
224 |
mphinputmatrix
Add matrix system for linear solver.
Purpose
mphinputmatrix
Syntax
mphinputmatrix(model,str,soltag,soltypetag)
Description
matrices is associated to the linear solver configuration defined with the tag soltag
and solved with the solver defined with the tag soltypetag.
soltypetag can only be one of the following solver type: Stationary, Eigenvalue,
Time.
A valid structure for a stationary solver includes the following fields:
TABLE 6-8: PROPERTY/VALUE PAIRS FOR THE MPHINT2 COMMAND.
FIELD NAME
DESCRIPTION
Stiffness matrix
Load vector
Constraint vector
Constraint Jacobian
DESCRIPTION
Stiffness matrix
Load vector
Constraint vector
Constraint Jacobian
Damping matrix
Mass matrix
There is also the possibility to include the constraint force Jacobian vector NF.
Once the matrix system is loaded in the model, the solver configuration is set ready
to run.
225
mphinputmatrix
Note: The system matrices are not stored in the model when it is saved as a
MPH-file or loaded into the COMSOL Desktop.
Example
Change the linear system by scaling the stiffness matrix and insert the system
matrices back to the model:
str.K = str.K*0.5;
mphinputmatrix(model,str,'sol1','s1')
226 |
mphmatrix, mphxmeshinfo
mphint2
Perform integration of expressions.
Purpose
mphint2
Syntax
[v1,...,v2] = mphint2(model,{e1,...,en},edim,...)
[v1,...,v2,unit] = mphint2(model,{e1,...,en},edim,...)
Description
the string expressions e1,...,en and returns the result in N matrices v1,...,vn
with M rows and P columns. M is the number of inner solution and P the number
of outer solution used for the evaluation. edim defines the element dimension, as a
string: line, surface, volume or as an integer value.
[v1,...,vn] = mphint2(model,{e1,...,en},...) also returns the units of the
PROPERTY VALUE
DEFAULT
DESCRIPTION
Dataset
String
active
solution
data set
Intorder
Positive integer
Integration order
Intsurface
on | off
off
Intvolume
on | off
off
Matrix
off | on
on
Method
auto |
integration |
summation
auto
Integration method
Outersolnum
Positive integer
| all | end
Selection
Integer vector |
string | all
all
Solnum
Integer vector |
end | all
all
Squeeze
on | off
on
Squeeze singleton
dimensions
Double array
The property Dataset controls which data set is used for the evaluation. Data Sets
contain or refer to the source of data for postprocessing purposes. Evaluation is
supported only on Solution Data Sets.
227
mphint2
The expressions e1,...,en are integrated for one or several solutions. Each
solution generates an additional column in the returned matrix. The property
Solnum and t control which solutions are used for the integrations. The Solnum
property is available when the data set has multiple solutions, for example in the case
of parametric, eigenfrequency, or time-dependent solutions. The t property is
available only for time-dependent problems. If Solnum is provided, the solutions
indicated by the indices provided with the Solnum property are used. If t is provided
solutions are interpolated. If neither Solnum nor t is provided, all solutions are
evaluated.
For time-dependent problems, the variable t can be used in the expressions ei. The
value of t is the interpolation time when the property t is provided, and the time
for the solution, when Solnum is used. Similarly, lambda and the parameter are
available as eigenvalues for eigenvalue problems and as parameter values for
parametric problems, respectively.
The unit property defines the unit of the integral, if a inconsistent unit is entered,
the default unit is used. In case of multiple expression, if the unit property is
defined with a string, the same unit is used for both expressions. To use different
units, set the property with a cell array. In case of inconsistent unit definition, the
default unit is used instead.
Solnum is used to select the solution number when a parametric, eigenvalue or
time-dependent solver has been used.
Outersolnum is used to select the outer solution number when a parametric sweep
228 |
mphinterp
Evaluate expressions in arbitrary points or data sets.
Purpose
mphinterp
Syntax
[v1,...,vn] = mphinterp(model,{e1,...,en},'coord',coord,...)
[v1,...,vn] = mphinterp(model,{e1,...,en},'dataset',dsettag,...)
[v1,...,vn,unit] = mphinterp(model,{e1,...,en},...)
Description
[v1,...,vn] = mphinterp(model,{e1,...,en},'coord',coord,...)
evaluates expressions e1,...en on the specified data set dsettag. In this case the
data set needs to be of a type that defines an interpolation in itself, such as cut planes,
revolve, and so forth.
[v1,...,vn,unit] = mphinterp(model,{e1,...,en},...) returns in addition
PROPERTY
VALUE
DEFAULT
DESCRIPTION
Complexfun
off | on
on
Complexout
off | on
off
Coord
Double
array
Coorderr
off | on
off
Dataset
String
Auto
Edim
'point' |
'edge' |
'boundary'
| 'domain'
| 0 | 1 | 2
| 3
Geometry
space
dimension
Ext
Value
0.1
Extrapolation control
Matherr
off | on
off
Outersolnum
Positive
integer |
all | end
229
mphinterp
PROPERTY
VALUE
DEFAULT
DESCRIPTION
Phase
Scalar
Recover
off | ppr |
pprint
off
Selection
Positive
Integer
array | all
all
Selection list
Solnum
Positive
integer
array | all
| end
all
Double
array
Unit
String |
Cell array
The columns of the matrix coord are the coordinates for the evaluation points. If
the number of rows in coord equals the space dimension, then coord are global
coordinates, and the property Edim determines the dimension in which the
expressions are evaluated. For instance, Edim='boundary' means that the
expressions are evaluated on boundaries in a 3D model. If Edim is less than the space
dimension, then the points in coord are projected onto the closest point on a
domain of dimension Edim. If, in addition, the property Selection is given, then
the closest point on domain number Selection in dimension Edim is used.
If the number of rows in coord is less than the space dimension, then these
coordinates are parameter values on a geometry face or edge. In that case, the
domain number for that face or edge must be specified with the property
Selection.
The expressions that are evaluated can be expressions involving variables, in
particular physics interface variables.
The matrices v1,...,vn are of the size k-by-size(coord,2), where k is the number
of solutions for which the evaluation is carried out, see below. The value of
expression ei for solution number j in evaluation point coord(:,m) is vi(j,m).
The vector pe contains the indices m for the evaluation points code(:,m) that are
outside the mesh, or, if a domain is specified, are outside that domain.
230 |
mphinterp
The property Data controls which data set is used for the evaluation. Data Sets
contain or refer to the source of data for postprocessing purposes. Evaluation is
supported only on Solution Data Sets. The active solution data set is used by default.
The property Edim decides which elements to evaluate on. Evaluation takes place
only on elements with space dimension Edim. If not specified, Edim equal to the
space dimension of the geometry is used. The setting is specified as one of the
following strings 'point', 'edge', 'boundary' or 'domain'. In previous
versions it was only possible to specify Edim as a number. For example, in a 3D
model, if evaluation is done on edges (1D elements), Edim is 1. Similarly, for
boundary evaluation (2D elements), Edim is 2, and for domain evaluation (3D
elements), Edim is 3 (default in 3D).
Use Recover to recover fields using polynomial-preserving recovery. This
techniques recover fields with derivatives such as stresses or fluxes with a higher
theoretical convergence than smoothing. Recovery is expensive so it is turned off by
default. The value pprint means that recovery is performed inside domains. The
value ppr means that recovery is also applied on all domain boundaries.
The property Refine constructs evaluation points by making a regular refinements
of each element. Each mesh edge is divided into Refine equal parts.
The property Smooth controls if the post data is forced to be continuous on element
edges. When Smooth is set to internal, only elements not on interior boundaries are
made continuous.
When the property Phase is used, the solution vector is multiplied with
exp(i*phase) before evaluating the expression.
The expressions e1,...,en are evaluated for one or several solutions. Each solution
generates an additional row in the data fields of the post data output structure. The
property Solnum and t control which solutions are used for the evaluations. The
Solnum property is available when the data set has multiple solutions, for example,
in the case of parametric, eigenfrequency, or time-dependent solutions. The t
property is available only for time-dependent problems. If Solnum is provided, the
solutions indicated by the indices provided with the Solnum property are used. If t
is provided solutions are interpolated. If neither Solnum nor t is provided, all
solutions are evaluated.
For time-dependent problems, the variable t can be used in the expressions ei. The
value of t is the interpolation time when the property t is provided, and the time
for the solution, when Solnum is used. Similarly, lambda and the parameter are
231
mphinterp
available as eigenvalues for eigenvalue problems and as parameter values for
parametric problems, respectively.
In case of multiple expression, if the unit property is defined with a string, the same
unit is used for both expressions. To use different units, set the property with a cell
array. In case of inconsistent unit definition, the default unit is used instead.
Solnum is used to select the solution number when a parametric, eigenvalue or
time-dependent solver has been used.
Outersolnum is used to select the outer solution number when a parametric sweep
Modify the extrapolation distance for point coordinates outside of the geometry:
232 |
mphinterp
coord = [5e-2;5e-2;1.1e-2];
T = mphinterp(model,'T','coord',coord)
T = mphinterp(model,'T','coord',coord,'ext',0.5);
Extract data using a cut line data set. First create the cutline data set, then evaluate
the temperature field along the line:
cln = model.result.dataset.create('cln', 'CutLine3D');
cln.setIndex('genpoints','1e-2',1,0);
cln.setIndex('genpoints','1e-2',0,2);
cln.setIndex('genpoints','5e-2',1,0);
T = mphinterp(model,'T','dataset','cln');
Evaluate the temperature at every time step computed with power set to 30:
coord = [0 0 1e-2;0 0 1e-2;0 1e-2 1e-2];
T = mphinterp(model,'T','coord',coord,'dataset','dset2');
Evaluate the temperature at every time step computed with power set to 90:
T = mphinterp(model,'T','coord',coord,'dataset','dset2',...
'outersolnum',3)
See also
233
mphload
Load a COMSOL Multiphysics model MPH-file.
Purpose
mphload
Syntax
model =
model =
model =
[model,
Description
mphload(filename)
mphload(filename, ModelObjectName)
mphload(filename, ModelObjectName, '-history')
filename] = mphload(filename, ModelObjectName)
history recording.
[model, filenameloaded] = mphload(filename, ModelObjectName) also
returns the full file name filenameloaded of the file that was loaded.
If the model name is the same as a model that is currently in the COMSOL server
the loaded model overwrites the existing one.
Note that MATLAB searches for the model on the MATLAB path if an absolute
path is not supplied.
mphload turns off the model history recording by default, unless the property
'-history' is used.
Load the file model_tutorial_llmatlab.mph and set the model name in the
COMSOL server to Model2:
model = mphload('model_tutorial_llmatlab','Model2');
234 |
mphsave
mphmatrix
Get model matrices.
Purpose
mphmatrix
Syntax
str = mphmatrix(model,soltag,'Out',...)
Description
structure str containing the matrix A assembled using the solver node soltag and
accessible as str.A. A being taken from the Out property list.
str = mphmatrix(model,soltag,fname,'Out',{'A','B',...}) returns a
MATLAB structure str containing the matrices A, B, ... assembled using the solver
node solname and accessible as str.A and str.B. A and B being taken from the
Out property list.
The function mphmatrix accepts the following property/value pairs:
TABLE 6-12: PROPERTY/VALUE PAIRS FOR THE MPHMATRIX COMMAND
PROPERTY
EXPRESSION
out
Cell array of
strings
DEFAULT
DESCRIPTION
Eigname
String
lambda
Eigenvalue name
Eigref
Double
Value of eigenvalue
linearization point
Initmethod
init | sol
sol
Initsol
string | zero
Active
solver tag
Solnum
Positive
integer| auto
auto
Solution number
Study
Study tag
{First
study}
EXPRESSION
DESCRIPTION
out
Stiffness matrix
Load vector
Constraint vector
Constraint Jacobian
Damping matrix
Mass matrix
NF
235
mphmatrix
Property/Value Pairs for the property out.
PROPERTY
EXPRESSION
DESCRIPTION
NP
MP
MLB
MUB
Kc
Lc
Dc
Ec
Null
Nullf
ud
Particular solution ud
uscale
Scale vector
Get the stationary matrix system, use the initial solution as linearization point:
str = mphmatrix(model,'sol1','out',{'K','L','M','N'},...
'initmethod','init');
Display the sparsity of the stiffness matrix and the constraint vector and compute the
total load applied in the matrix system:
subplot(2,1,1); spy(str.K);subplot(2,1,2);spy(str.N)
236 |
mphmatrix
Q = sum(str.L)
Get the eliminated matrix system, use the initial solution as linearization point:
str = mphmatrix(model,'sol1','out',{'Kc'},'initmethod','init');
Compare the sparsity between the eliminated and non-eliminated stiffness matrix:
subplot(2,1,1); hold on; spy(str.Kc,'r')
Evaluate the eliminated load vector using the current solution as linearization point:
str = mphmatrix(model,'sol1','out',{'Lc'},'initmethod','sol');
237
mphmax
Perform maximum of expressions.
Purpose
mphmax
Syntax
[v1,...,vn] = mphmax(model,{e1,...,en},edim,...)
[v1,...,vn,unit] = mphmax(model,{e1,...,en},edim,...)
Description
PROPERTY VALUE
DEFAULT
DESCRIPTION
Dataset
String
active
solution
data set
Matrix
off | on
on
Outersolnum
Positive integer
array | all |
end
Selection
Integer vector |
string | all
all
Solnum
Integer vector |
end | all
all
Squeeze
on | off
on
Squeeze singleton
dimensions
Double array
The property Dataset controls which data set is used for the evaluation. Data Sets
contain or refer to the source of data for postprocessing purposes. Evaluation is
supported only on Solution Data Sets.
The maximum expressions e1,...,en is evaluated for one or several solutions.
Each solution generates an additional column in the returned matrix. The property
Solnum and t control which solutions are used for the evaluation. The Solnum
property is available when the data set has multiple solutions, for example in the case
of parametric, eigenfrequency, or time-dependent solutions. The t property is
238 |
mphmax
available only for time-dependent problems. If Solnum is provided, the solutions
indicated by the indices provided with the Solnum property are used. If t is provided
solutions are interpolated. If neither Solnum nor t is provided, all solutions are
evaluated.
Solnum is used to select the solution number when a parametric, eigenvalue or
Evaluate the maximum of the temperature at every time step computed with power
set to 30:
maxT = mphmax(model,'T','volume','dataset','dset2');
Evaluate the maximum of the temperature at 10.5 sec and 15.2 sec:
239
mphmax
maxT = mphmax(model,'T','volume','dataset','dset2',...
't',[10.5,15.2]);
Evaluate the maximum of the temperature at every time step computed with power
set to 90:
maxT = mphmax(model,'T','volume','dataset','dset2',....
'outersolnum',3);
See also
240 |
mphmean, mphmin
mphmean
Perform mean of expressions.
Purpose
mphmean
Syntax
[v1,...,vn] = mphmean(model,{e1,...,en},edim,...)
[v1,...,vn,unit] = mphmean(model,{e1,...,en},edim,...)
Description
PROPERTY VALUE
DEFAULT
DESCRIPTION
Dataset
String
active
solution
data set
Intorder
Positive integer
Integration order
Matrix
off | on
on
Method
auto |
integration |
summation
auto
Integration method
Outersolnum
Positive integer
array | all |
end
Selection
Integer vector |
string | all
all
Solnum
Integer vector |
end | all
all
Squeeze
on | off
on
Squeeze singleton
dimensions
Double array
The property Dataset controls which data set is used for the evaluation. Data Sets
contain or refer to the source of data for postprocessing purposes. Evaluation is
supported only on Solution Data Sets.
241
mphmean
The mean of expressions e1,...,en is evaluated for one or several solutions. Each
solution generates an additional column in the returned matrix. The property
Solnum and t control which solutions are used for the evaluation. The Solnum
property is available when the data set has multiple solutions, for example in the case
of parametric, eigenfrequency, or time-dependent solutions. The t property is
available only for time-dependent problems. If Solnum is provided, the solutions
indicated by the indices provided with the Solnum property are used. If t is provided
solutions are interpolated. If neither Solnum nor t is provided, all solutions are
evaluated.
Solnum is used to select the solution number when a parametric, eigenvalue or
time-dependent solver has been used.
Outersolnum is used to select the outer solution number when a parametric sweep
Evaluate the mean of the temperature at every time step computed with power set
to 30:
242 |
mphmean
maxT = mphmean(model,'T','volume','dataset','dset2');
Evaluate the mean of the temperature at 10.5 sec and 15.2 sec:
maxT = mphmean(model,'T','volume','dataset','dset2',...
't',[10.5,15.2]);
Evaluate the mean of the temperature at every time step computed with power set
to 90:
maxT = mphmean(model,'T','volume','dataset','dset2',....
'outersolnum',3);
See also
mphmax, mphmin
243
mphmesh
Plot a mesh in a MATLAB figure window.
Purpose
mphmesh
Syntax
mphmesh(model)
mphmesh(model,meshtag,...)
Description
figure.
The function mphmesh accepts the following property/value pairs:
TABLE 6-15: PROPERTY/VALUE PAIRS FOR THE MPHMESH COMMAND
Example
PROPERTY
VALUE
DEFAULT
DESCRIPTION
Parent
Double
Edgecolor
Char
Edge color
Edgelabels
on | off
off
Edgelabelscolor
Char
Edgemode
on | off
on
Show edges
Facealpha
Double
Facelabels
on | off
off
Facelabelscolor
Char
Facemode
on | off
on
Show faces
Parent axis
Meshcolor
Char
flat
Vertexlabels
on | off
off
Vertexlabelscolor
Char
Vertexmode
on | off
off
Show vertices
Create a second mesh case with an extra fine default mesh settings and plot it:
mesh = model.mesh.create('mesh2', 'geom1');
mesh.autoMeshSize(2);
mesh.run;
mphmesh(model,'mesh2','meshcolor','r');
See also
244 |
mphmeshstats
Return mesh statistics and mesh data information
Purpose
mphmeshstats
Syntax
stats = mphmeshstats(model)
stats = mphmeshstats(model, meshtag)
[stats,data] = mphmeshstats(model, meshtag)
Description
DESCRIPTION
Meshtag
Geomtag
Isactive
Hasproblems
Iscomplete
Sdim
Space dimension
Types
Numelem
Minquality
Minimum quality
Meanquality
Mean quality
Qualitydistr
Minvolume
Maxvolume
Volume
245
mphmeshstats
The output structure data contains the following fields:
TABLE 6-17: FIELDS IN THE DATA STRUCTURE
Example
FIELD
DESCRIPTOIN
Vertex
Elem
Elementity
246 |
mphmesh
mphmin
Perform minimum of expressions.
Purpose
mphmin
Syntax
[v1,...,vn] = mphmin(model,{e1,...,en},edim,...)
[v1,...,vn,unit] = mphmin(model,{e1,...,en},edim,...)
Description
minimum of the string expressions e1,...,en and returns the result in N matrices
v1,...,vn with M rows and P columns. M is the number of inner solution and P
the number of outer solution used for the evaluation. edim defines the element
dimension: line, surface, volume or as an integer value.
[v1,...,vn] = mphmin(model,{e1,...,en},edim,...) also returns the units
PROPERTY VALUE
DEFAULT
DESCRIPTION
Dataset
String
active
solution
data set
Matrix
off | on
on
Outersolnum
Positive integer
array | all |
end
Selection
Integer vector |
string | all
all
Solnum
Integer vector |
end | all
all
Squeeze
on | off
on
Squeeze singleton
dimensions
Double array
The property Dataset controls which data set is used for the evaluation. Data Sets
contain or refer to the source of data for postprocessing purposes. Evaluation is
supported only on Solution Data Sets.
The mean of expressions e1,...,en is evaluated for one or several solutions. Each
solution generates an additional column in the returned matrix. The property
Solnum and t control which solutions are used for the evaluation. The Solnum
property is available when the data set has multiple solutions, for example in the case
of parametric, eigenfrequency, or time-dependent solutions. The t property is
247
mphmin
available only for time-dependent problems. If Solnum is provided, the solutions
indicated by the indices provided with the Solnum property are used. If t is provided
solutions are interpolated. If neither Solnum nor t is provided, all solutions are
evaluated.
Solnum is used to select the solution number when a parametric, eigenvalue or
Evaluate the minimum of the temperature at every time step computed with power
set to 30:
maxT = mphmin(model,'T','volume','dataset','dset2');
Evaluate the minimum of the temperature at 10.5 sec and 15.2 sec:
248 |
mphmin
maxT = mphmin(model,'T','volume','dataset','dset2',...
't',[10.5,15.2]);
Evaluate the minimum of the temperature at every time step computed with power
set to 90:
maxT = mphmin(model,'T','volume','dataset','dset2',....
'outersolnum',3);
See also
mphmax, mphmean
249
mphmodel
Return tags for the nodes and subnodes in the COMSOL model object.
Purpose
mphmodel
Syntax
mphmodel(model)
str = mphmodel(model,'-struct')
Description
mphmodel(model) returns the tags for the nodes and subnodes of the object model.
str = mphmodel(model,'-struct') returns the tags for the nodes and subnodes
of the object model as a MATLAB structure str.
The function mphmodel can be used when navigating the model object and learning
about its structure. The mphmodel function is mainly designed for usage when
working on the command line and one needs to learn what nodes are placed under
a particular node.
Example
Load the model busbar.mph and get the list of the nodes available under the root
node:
model = mphload('busbar')
mphmodel(model)
250 |
mphnavigator, mphsearch
mphmodellibrary
Graphical User Interface for viewing the Model Libraries.
Purpose
mphmodellibrary
Syntax
mphmodellibrary
Description
mphmodellibrary starts a GUI to visualize and access the example model available
in the COMSOL Multiphysics Model Libraries. The model MPH-file can be loaded
in MATLAB and the model documentation PDF-file is accessible directly. Models
that are specific to LiveLink for MATLAB also contains the script M-file.
251
mphnavigator
Graphical User Interface for viewing the COMSOL Multiphysics model object
Purpose
mphnavigator
Syntax
mphnavigator
mphnavigator(modelvariable)
Description
interface that can be used to navigate the model object and to view the properties
and methods of the nodes in the model tree.
The GUI requires that the COMSOL objest is stored in a variable in the base
workspace (at the MATLAB command prompt) with the name model.
mphnavigator(modelvariable) opens the model object defined with the name
modelvariable in Model Object Navigator.
Example
Navigate the model object that is accessible with the variable model
mphnavigator
252 |
mphnavigator
Load effective_diffusivity.mph from the model library and set the model
object with the variable eff_diff:
eff_diff = mphload('effective_diffusivity');
Navigate the model object that is accessible with the variable eff_diff
mphnavigator(eff_diff)
See also
253
mphparticle
Evaluate expressions on particle trajectories
Purpose
mphparticle
Syntax
pd = mphparticle(model)
pd = mphparticle(model,'expr',{e1,...,en},...)
Description
mphparticle(model) returns particle position and particle velocity at all time steps
stored in the first particle dataset.
mphparticle(model,'expr',{e1,...,en},...) returns particle position,
particle velocity and expressions e1, ..., en evaluated on particle trajectories.
VALUE
Expr
String |
String cell
array
DEFAULT
DESCRIPTION
Dataonly
on | off
off
Dataset
String
First
particle
dataset
Double array
Expressions to evaluate
CONTENT
d#
Result of evaluation #
expr
Evaluated expressions
unit
Unit of evaluations
Note: mphparticle requires a particle dataset generated with the Particle Tracing
Module.
Example
254 |
mphparticle
model = mphload('laminar_mixer_particle');
Extract the particle positions and particle velocities along the computed trajectories
at every time steps stored in the model:
pd = mphparticle(model)
Evaluate the fluid pressure and fluid velocity magnitude value along the particle
trajectories at t=2.65 sec., extract only the data:
pd = mphparticle(model,'expr',{'p','spf.U'},'t',2.65,...
'dataonly','on')
See also
255
mphplot
Render a plot group in a figure window.
Purpose
mphplot
Syntax
mphplot(model,pgtag,...)
pd = mphplot(model,pgtag,...)
mphplot(pd,...)
Description
using the function mpheval. Plots involving points, lines and surfaces are supported.
The function mphplot accepts the following property/value pairs:
TABLE 6-21: PROPERTY/VALUE PAIRS FOR THE MPHPLOT COMMAND
PROPERTY
VALUE
DEFAULT
DESCRIPTION
Colortable
String
Rainbow
Index
Positive
integer
Mesh
on | off
on
Parent
Double
Rangenum
Positive
Integer
none
Server
on | off
off
Plot on server
Note: The plot on server option requires that you start COMSOL with MATLAB
in graphics mode.
Only one color range bar and one legend bar is supported in a MATLAB figure.
When the option plot on server is active, all active color range bar are displayed.
Example
256 |
mphplot
std.run;
model.result.dataset.create('mir', 'Mirror3D');
pg = model.result.create('pg', 'PlotGroup3D');
pg.set('data', 'mir');
surf1 = pg.feature.create('surf1', 'Surface');
surf1.set('colortable', 'Thermal');
mphplot(model,'pg')
Display the plot group and the color range bar of the second plot type:
mphplot(model,'pg','rangenum',2)
colortable, mpheval
257
mphsave
Save a COMSOL Multiphysics model
Purpose
mphsave
Syntax
mphsave(model)
mphsave(model, filename)
Description
If the file name is not provided, the model has to be saved previously on disk.
If the file name does not provide a path, the file is saved relatively to the current path
in MATLAB.
The model can be saved as an MPH-file, Java file, or M-file. The file extension
determines which format that is saved.
See also
258 |
mphload
mphsearch
GUI for searching expressions in the COMSOL Multiphysics model object
Purpose
mphsearch
Syntax
mphsearch(model)
Description
expressions in the model object model. Search using a text available in the name,
expression or description of the variable.
See also
mphgetexpressions, mphnavigator
259
mphselectbox
Select geometric entity using a rubberband/box.
Purpose
mphselectbox
Syntax
n = mphselectbox(model,geomtag,boxcoord,entity,...)
Description
of the geometry entities that are inside a selection domain (rectangle or box). This
method looks only on the vertex coordinates and does not observe all points on
curves and surfaces.
boxcoord set the coordinates of the selection domain, specified as a Nx2 array,
VALUE
DEFAULT
DESCRIPTION
Adjnumber
Scalar
none
When a model uses form an assembly more than one vertex can have the same
coordinate if the coordinate is shared by separate geometric objects. In that case one
can use the adjnumber property in order to identify the domain that the vertices
should be adjacent to.
Example
Find the boundaries inside the selection box that are adjacent to domain number 1:
n = mphselectbox(model,'geom1',coordBox,'boundary',...
'adjnumber',1);
260 |
mphselectbox
Find geometry entity number in an assembly
model = mphload('model_tutorial_llmatlab');
geom = model.geom('geom1');
geom.feature('fin').set('action','assembly');
geom.run('fin');
261
mphselectcoords
Select geometric entity using point coordinates
Purpose
mphselectcoords
Syntax
n = mphselectcoords(model,geomtag,coord,entity,...)
Description
VALUE
DEFAULT
DESCRIPTION
Adjnumber
Scalar
none
Radius
Scalar
auto
Search radius
Include
all | any
all
When a model uses form an assembly more than one vertex can have the same
coordinate if the coordinate is shared by separate geometric objects. In that case one
can use the adjnumber property in order to identify the domain that the vertices
should be adjacent to.
The radius property is used to specify the radius of the sphere/circle that the
search should be within. A small positive radius (based on the geometry size) is used
by default in order to compensate for rounding errors.
Use the property include when two point coordinates are used. Set it to all to
select objects within the search radius of all points. any returns objects within the
search radius of any points.
Examplee
262 |
mphselectcoords
model = mphload('model_tutorial_llmatlab');
coord = [10e-3 0 10e-3;0 10e-3 10e-3];
n = mphselectcoords(model,'geom1',coord','point')
Return the indices of the point at coordinates within a search radius of 0.011:
n = mphselectcoords(model,'geom1',coord','point',...
'radius',0.011)
Return the indices of the boundaries that have a vertex within the search radius:
n = mphselectcoords(model,'geom1',coord','boundary',...
'radius',11e-3)
Return the indices of the edges that have a vertex within the search radius from all
points:
coord = [5e-3 0 10e-3;0 5e-3 10e-3];
n = mphselectcoords(model,'geom1',coord','edge',...
'radius',6e-3);
Return the indices of the edges that have a vertex within the search radius from at
least one point:
n = mphselectcoords(model,'geom1',coord','edge',...
'radius',6e-3,'include','any');
Return the indices of the boundaries that have any vertices within the search range
of a point:
coord = [0,0,10e-3];
n0 = mphselectcoords(model,'geom1',coord,'boundary')
Return the indices of the boundaries that also are adjacent to domain 1:
n1 = mphselectcoords(model,'geom1',coord,'boundary',...
'adjnumber',1);
Return the indices of the boundaries that also are adjacent to domain 2:
n1 = mphselectcoords(model,'geom1',coord,'boundary',...
'adjnumber',2);
See also
263
mphshowerrors
Show messages in error nodes in the COMSOL Multiphysics model
Purpose
mphshowerrors
Syntax
mphshowerrors(model)
list = mphshowerrors(model)
Description
mphshowerrors(model) shows the error and warning messages stored in the model
and where they are located. The output is displayed in the command window.
list = mphshowerrors(model) returns the error and warning messages stored in
the model and where they are located in the Nx2 cell array list. N corresponding to
the number of errors or warning found in the model object. The first column
contains the node of the error and the second column contain the error message.
See also
264 |
mphnavigator
mphsolinfo
Get information about a solution object
Purpose
mphsolinfo
Syntax
info = mphsolinfo(model,...)
info = mphsolinfo(model,'solname',soltag,...)
Description
object.
info = mphsolinfo(model,'solname',soltag,...) returns information about
VALUE
DEFAULT
DESCRIPTION
Solname
String
Active solution
object
Dataset
String
Active
solution data
set
NU
on | off
off
CONTENT
Solname
Solution name
Size
Nummesh
Sizes
Soltype
Solpar
Sizesolvals
Solvals
Paramsweepnames
Paramsweepvals
NUsol
NUreacf
265
mphsolinfo
CONTENT
NUadj
NUfsens
NUsens
You can use the function mphgetu to obtain the actual values of the solution vector.
Note that these functions are low level functions and you most often would use
functions such as mphinterp and mpheval to extract numerical data from a model.
Examplee
Get the information about the 1st outer solution (power = 30):
solinfo = mphsolinfo(model,'soltag','sol3');
Get the solution vector for 2nd outer solution (power = 60):
solinfo = mphsolinfo(model,'soltag','sol4');
See also
266 |
mphsolutioninfo
Get information about solution objects and datasets containing given parameters
Purpose
mphsolutioninfo
Syntax
info = mphsolutioninfo(model)
info = mphsolutioninfo(model,'parameters',{{ei,vi,toli},...},...)
Description
VALUE
DEFAULT
DESCRIPTION
Cellmap
off | onn
off
Dataset
String
Parameters
Cell | Cell
array
Soltag
String |
String cell
array
Sort
String |
Scalar | auto
auto
CONTENT
Solutions
Sol#
CONTENT
Dataset
Study
Sequencetype
267
mphsolutioninfo
Example
FIELD
CONTENT
cellmap
values
parameters
mapheaders
map
Load model_tutorial_llmatlab.mph:
model = mphload('model_tutorial_llmatlab');
268 |
mphstart
Connect MATLAB to a COMSOL server.
Purpose
mphstart
Syntax
mphstart
mphstart(port)
mphstart(ipaddress,
mphstart(ipaddress,
mphstart(ipaddress,
mphstart(ipaddress,
Description
port)
port, username, password)
port, comsolpath)
port, comsolpath, username, password)
mphstart creates a connection with a COMSOL server using the default port
number (which is 2036).
mphstart(port) creates a connection with a COMSOL server using the specified
port number port.
mphstart(ipaddress, port) creates a connection with a COMSOL server using
the specified IP address ipaddress and the port number port. This command
assumes that the client and the server machine share the same login properties.
mphstart(ipaddress, port, username, password) creates a connection with
a COMSOL server using the specified IP address ipaddress and the port number
port, the username username and password password.
mphstart(ipaddress, port, comsolpath) creates a connection with a
COMSOL server using the specified IP address and port number using the
comsolpath that is specified. This is useful if mphstart cannot find the location of
the COMSOL Multiphysics installation.
mphstart(ipaddress, port, comsolpath, username, password) creates a
connection with a COMSOL server using the specified IP address, the port
number, the username and password using the comsolpath that is specified. This
is useful if mphstart cannot find the location of the COMSOL Multiphysics
installation.
mphstart can be used to create a connection from within MATLAB when this is
started without using the COMSOL with MATLAB option. mphstart then sets up
the necessary environment and connect to COMSOL.
269
mphstate
Get state-space matrices for dynamic system.
Purpose
mphstate
Syntax
str = mphstate(model,soltag,'Out',{'SP'})
str = mphstate(model,soltag,'Out',{'SP1','SP2',...})
Description
structure
str containing the state space matrix SP assembled using the solver node soltag
and accessible as str.SP. SP being taken from the Out property list.
str = mphstate(model,soltag,'Out',{'SP1','SP2',...}) returns a
MATLAB structure str containing the state space matrices SP1, SP2,... assembled
using the solver node soltag and accessible as str.SP1and str.SP2. SP1 and SP2
being taken from the Out property list.
VALUE
DEFAULT
DESCRIPTION
Out
MA | MB | A | B |
C | D |Mc |Null |
ud | x0
Keepfeature
off | on
Input
String
Output
String
Sparse
off | on
Initmethod
init | sol
Initsol
solname | zero
solname
Solnum
Positive integer
auto
Solution number
Output matrix
off
off
The property Sparse controls whether the matrices A, B, C, D, M, MA, MB, and Null
are stored in the sparse format.
The equations correspond to the system below:
Mcx = McAx + McBu
y = Cx + Du
where x are the state variables, u are the input variables, and y are the output
variables.
270 |
mphstate
A static linearized model of the system can be described by:
y = D C McA 1 McB u
The full solution vector U can be then obtained from
U = Nullx + ud + u0
where Null is the null space matrix, ud the constraint contribution and u0 is the
linearization point, which is the solution stored in the sequence once the state space
export feature is run.
The matrices Mc and MA are produced by the same algorithms that do the
finite-element assembly and constraint elimination in COMSOL Multiphysics. Mc
and MA are the same as the matrices Dc (eliminated mass matrix) and Kc (Kc is the
eliminated stiffness matrix). The matrices are produced from an exact residual vector
Jacobian calculation (that is, differentiation of the residual vector with respect to the
degrees of freedoms x) plus an algebraic elimination of the constraints. The matrix
C is produced in a similar way; that is, the exact output vector Jacobian matrix plus
constraint elimination.
The matrices MB and D are produced by a numerical differentiation of the residual
and output vectors, respectively, with respect to the input parameters (the algorithm
systematically perturbs the input parameters by multiplying them by a factor
(1+10-8)).
The input cannot be a variable constraint in the model.
Example
Load model_tutorial_llmatlab.mph:
model = mphload('model_tutorial_llmatlab');
model.mesh('mesh1').autoMeshSize(9);
std = model.study.create('std');
time = std.feature.create('time','Transient');
time.set('tlist','range(0,1,50)');
std.run;
271
mphstate
M = mphstate(model,'sol1','out',{'A','B','C','D'},...
'input','power','output','comp1.ppb1');
272 |
mphtable
Get table data.
Purpose
mphtable
Syntax
info = mphtable(model,tabletag)
Description
Example
FIELD
CONTENT
Headers
Tag
Data
Filename
Evaluate the maximum temperature in the model and set the results in a table:
max = model.result.numerical.create('max','MaxVolume');
max.selection.all;
tbl = model.result.table.create('tbl','Table');
tbl.comments('Volume Maximum (T)');
max.set('table','tbl');
max.setResult;
273
mphversion
Return the version number of COMSOL Multiphysics.
Purpose
mphversion
Syntax
v = mphversion
[v,vm] = mphversion(model)
Description
Example
Load model_tutorial_llmatlab.mph:
model = mphload('model_tutorial_llmatlab');
274 |
mphviewselection
Display a geometric entity selection in a MATLAB figure.
Purpose
mphviewselection
Syntax
mphviewselection(model,geomtag,number,entity,...)
mphviewselection(model,seltag,...)
Description
VALUE
DEFAULT
DESCRIPTION
Edgecolor
Edgecolorselected
RGB array
[1,0,0]
Edgelabels
on | off
off
Edgelabelscolor
Edgemode
on | off
on
Show edges
Entity
Domain |
boundary | edge
| point
Facealpha
Double
Facecolor
RGB array
[0.6,0.6,0.6]
Facecolorselected
RGB array
[1,0,0]
Facelabels
on | off
off
Facelabelscolor
Facemode
on | off
on
Show faces
Geommode
on | off
Marker
on
Vertex marker
Markercolorselected
Markersize
Int
12
Parent
Double
Parent axis
275
mphviewselection
VALUE
DEFAULT
DESCRIPTION
Renderer
Opengl |
zbuffer
opengl
Selection
String | Positive
integer array
Selectoralpha
Double
0.25
Set selector
transparency value
Selectorcolor
RGB array
[0,0,1]
Showselector
on | off
on
Show Selector
Vertexlabels
on | off
off
Vertexlabelscolor
Vertexmode
on | off
off
Show vertices
Example
Add an explicit selection for boundaries 7 to 12 and plot the selection in a figure:
model.selection.create('sel1','Explicit').geom(2).set(7:12);
mphviewselection(model,'sel1');
Add a selection to get the vertex indices with the box delimited with the coordinates
[-1e-3 11e-3;-1e-3 11e-3;9e-3 11e-3] and plot both the selected entities and the
selector:
box = model.selection.create('box1', 'Box');
box.set('entitydim', '0');
box.set('xmin', '-1e-3').set('xmax', '11e-3');
box.set('ymin', '-1e-3').set('ymax', '11e-3');
box.set('zmin', '10e-3').set('zmax', '11e-3');
mphviewselection(model,'box1','facemode','off');
See also
276 |
mphxmeshinfo
Extract information about the extended mesh.
Purpose
mphxmeshinfo
Syntax
info = mphxmeshinfo(model)
Description
VALUE
DEFAULT
DESCRIPTION
Solname
String
Active
solution
object
Studysteptag
String
Meshcase
Positive
integer |
String
The function xmeshinfo returns a structure with the fields shown in the table below
TABLE 6-33: FIELD IN THE RETURNED STRUCTURE FROM MPHXMESHINFO
Example
FIELD
DESCRIPTION
Solname
Ndofs
Number of DOFs
Fieldnames
Fieldndofs
Meshtypes
Dofs
Nodes
Elements
277
mphxmeshinfo
Get the number of degrees of freedom and the nodes coordinates:
dofs = info.ndofs
coords = info.dofs.coords;
Get the index of the nodes for element with the index 100:
idx_nodes = info.elements.tet.nodes(:,100)
Get the index of the dofs for element with the index 100:
idx_dofs = info.elements.tet.dofs(:,100)
Get the index of the variables names corresponding to the dofs with the index
idx_dofs:
idx_names = info.dofs.nameinds(idx_dofs);
Get the coordinates of the dofs corresponding to the dependent variable V that
belong to element 100:
info.dofs.coords(:,idx_dofs(idx))
See also:
278 |
I n d e x
A
adding
model objects 26
animations 112
client-server mode 16
ball selections 92
box selections 94
geometry operations 31
global equations 86
combining meshes 66
interpolation functions 88
compose operation 35
COMSOL API 24
mesh sequences 52
COMSOL server 16
adjacent selections 95
connect to server 29
connecting MATLAB 18
constructor name 81
converting
curve segments 38
image data 49
mesh elements 72
copying
boundary meshes 70
boundary meshes 70
creating
boundary modeling 37
box selections 94, 97
1D geometries 33
building
2D geometries 34, 37
geometry sequences 32
3D geometries 38
mesh sequences 53
composite objects 34
meshes 62
CAD formats 41
mesh information 77
model objects 25
clearing
functions 192
D
INDEX|
279
defining
extracting
materials 85
selections 91
matrices 156
settings 88
mesh information 77
Delaunay method 58
difference operation 35
disconnecting MATLAB 20
free meshing 66
displaying
geometries 32
meshes 53
selections 97
functions
documentation 11
interpolation 88
MATLAB 117
DXF files 41
E
emailing COMSOL 13
GDS format 41
geometry
creating 46
entity, geometry 33
displaying 32
equations, modifying 85
exporting 40
errors 177
parameterized 43
evaluating
data 111
retrieve information 42
expressions 120
sequence 31
global equations 86
integrals 129
explicit selections 91
exporting
history, model 27
data 113
geometries 4041
plugins 90
280 | I N D E X
importing
quality 74
meshes 73
refining 69
resolution 55
sequence 52
importing 73
geometries 41
statistics 75
Internet resources 10
methods 24
interpolation curve 46
interpolation functions 88
Microsoft Windows 17
Java 24
Java heap size 179
job sequences 104
Model Library 12
model object
Linux 17
calling 117
load model 27
information 174
methods 25
Mac OS X 17
mass matrix 156
materials 8485
MATLAB desktop 16
MATLAB feature node 191
MATLAB functions 117, 186
MATLAB functions, plot 188
matrices, state-space 155
maximum of expression 133
measuring, mesh quality 74
memory requirements 181
mesh
boundary layers 67
converting 72
copying 70
data 76
displaying 53
element size, controlling 54
navigating 170
Model Tree 172
models, running in loops 142
ModelUtil method 25
modifying equations 85
mpheval 120123
mphevalglobalmatrix 133
mphevalpoint 126128
MPH-files 12
mphgetexpressions 176
mphgetproperties 176
mphgetselection 176
mphgetu 165166
mphglobal 131133
mphinputmatrix 150151
mphint2 129131
mphinterp 123126
mphmatrix 147149
INDEX|
281
mphmax 133135
mphmean 135137
mphmin 137139
mphmodel 174
mphnavigator 170174
mphparticle 139141
mphsearch 175
mphshowerrors 177
mphsolinfo 160161
mphsolutioninfo 162164
mphstate 155158
mphtable 119
mphxmeshinfo 154, 167168
myscript 145
N
NASTRAN 73
setting
parameterized geometries 43
parametric jobs 104
parametric sweep 103
particle trajectories 139
physics interfaces 8182
plot data, extracting 108
plot groups 106107
plot while solving 104
plotting data, example 109
port number 16
preferences 20
prism mesh 65
progress bar 26
refining meshes 69
remove model object 26
resolution, mesh 55
282 | I N D E X
VRML format 41
W warnings 177
xmesh 167
xterm 145146
INDEX|
283
284 | I N D E X