Live Link Format Lab Users Guide
Live Link Format Lab Users Guide
User’s Guide
LiveLink™ for MATLAB® User’s Guide
© 2009–2018 COMSOL
Protected by patents listed on www.comsol.com/patents, and U.S. Patents 7,519,518; 7,596,474;
7,623,991; 8,457,932; 8,954,302; 9,098,106; 9,146,652; 9,323,503; 9,372,673; and 9,454,625. Patents
pending.
This Documentation and the Programs described herein are furnished under the COMSOL Software License
Agreement (www.comsol.com/comsol-license-agreement) and may be used or copied only under the terms
of the license agreement.
COMSOL, the COMSOL logo, COMSOL Multiphysics, COMSOL Desktop, COMSOL Server, and
LiveLink are either registered trademarks or trademarks of COMSOL AB. MATLAB is a registered
trademark of The MathWorks, Inc.. All other trademarks are the property of their respective owners, and
COMSOL AB and its subsidiaries and products are not affiliated with, endorsed by, sponsored by, or
supported by those or the above non-COMSOL trademark owners. For a list of such trademark owners, see
www.comsol.com/trademarks.
Version: COMSOL 5.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:
Chapter 1: Introduction
CONTENTS |3
The Model Object Methods. . . . . . . . . . . . . . . . . . . 39
The General Utility Functionality . . . . . . . . . . . . . . . . . 39
The Model History . . . . . . . . . . . . . . . . . . . . . . 40
Loading and Saving a Model . . . . . . . . . . . . . . . . . . . 41
Sharing the Model Between the COMSOL Desktop® and the
MATLAB® Prompt . . . . . . . . . . . . . . . . . . . . 45
4 | CONTENTS
Computing the Solution 131
The Study Node . . . . . . . . . . . . . . . . . . . . . . 131
The Solver Sequence Syntax . . . . . . . . . . . . . . . . . 132
Run the Solver Sequence . . . . . . . . . . . . . . . . . . . 133
Adding a Parametric Sweep . . . . . . . . . . . . . . . . . . 134
Adding a Job Sequence. . . . . . . . . . . . . . . . . . . . 134
Plot While Solving . . . . . . . . . . . . . . . . . . . . . 135
CONTENTS |5
Running Models in a Loop 181
The Parametric Sweep Node . . . . . . . . . . . . . . . . . 181
Running Model in a Loop Using the MATLAB® Tools . . . . . . . . 181
6 | CONTENTS
Improving Performance for Large Models 233
Allocating Memory . . . . . . . . . . . . . . . . . . . . . 233
Disabling Model Feature Update . . . . . . . . . . . . . . . . 234
Disabling The Model History . . . . . . . . . . . . . . . . . 235
CONTENTS |7
mphevaluate . . . . . . . . . . . . . . . . . . . . . . . 267
mphgeom. . . . . . . . . . . . . . . . . . . . . . . . . 268
mphgetadj . . . . . . . . . . . . . . . . . . . . . . . . 270
mphgetcoords . . . . . . . . . . . . . . . . . . . . . . . 271
mphgetexpressions . . . . . . . . . . . . . . . . . . . . . 272
mphgetproperties . . . . . . . . . . . . . . . . . . . . . 272
mphgetselection . . . . . . . . . . . . . . . . . . . . . . 273
mphgetu . . . . . . . . . . . . . . . . . . . . . . . . . 273
mphglobal . . . . . . . . . . . . . . . . . . . . . . . . 275
mphimage2geom . . . . . . . . . . . . . . . . . . . . . . 278
mphinputmatrix . . . . . . . . . . . . . . . . . . . . . . 279
mphint2 . . . . . . . . . . . . . . . . . . . . . . . . . 282
mphinterp . . . . . . . . . . . . . . . . . . . . . . . . 284
mphinterpolationfile. . . . . . . . . . . . . . . . . . . . . 289
mphlaunch . . . . . . . . . . . . . . . . . . . . . . . . 290
mphload . . . . . . . . . . . . . . . . . . . . . . . . . 291
mphmatrix . . . . . . . . . . . . . . . . . . . . . . . . 293
mphmax . . . . . . . . . . . . . . . . . . . . . . . . . 296
mphmean. . . . . . . . . . . . . . . . . . . . . . . . . 299
mphmesh . . . . . . . . . . . . . . . . . . . . . . . . . 301
mphmeshstats . . . . . . . . . . . . . . . . . . . . . . . 303
mphmin . . . . . . . . . . . . . . . . . . . . . . . . . 305
mphmodel . . . . . . . . . . . . . . . . . . . . . . . . 308
mphnavigator . . . . . . . . . . . . . . . . . . . . . . . 309
mphopen . . . . . . . . . . . . . . . . . . . . . . . . . 310
mphparticle . . . . . . . . . . . . . . . . . . . . . . . . 312
mphplot . . . . . . . . . . . . . . . . . . . . . . . . . 314
mphquad2tri . . . . . . . . . . . . . . . . . . . . . . . 316
mphray . . . . . . . . . . . . . . . . . . . . . . . . . 317
mphreadstl . . . . . . . . . . . . . . . . . . . . . . . . 318
mphreduction . . . . . . . . . . . . . . . . . . . . . . . 319
mphsave . . . . . . . . . . . . . . . . . . . . . . . . . 321
mphsearch . . . . . . . . . . . . . . . . . . . . . . . . 322
mphselectbox . . . . . . . . . . . . . . . . . . . . . . . 323
mphselectcoords . . . . . . . . . . . . . . . . . . . . . . 324
mphshowerrors . . . . . . . . . . . . . . . . . . . . . . 326
mphsolinfo . . . . . . . . . . . . . . . . . . . . . . . . 327
mphsolutioninfo . . . . . . . . . . . . . . . . . . . . . . 329
8 | CONTENTS
mphstart . . . . . . . . . . . . . . . . . . . . . . . . . 331
mphstate . . . . . . . . . . . . . . . . . . . . . . . . . 333
mphsurf . . . . . . . . . . . . . . . . . . . . . . . . . 335
mphtable . . . . . . . . . . . . . . . . . . . . . . . . . 336
mphtags . . . . . . . . . . . . . . . . . . . . . . . . . 337
mphthumbnail . . . . . . . . . . . . . . . . . . . . . . . 338
mphversion . . . . . . . . . . . . . . . . . . . . . . . . 339
mphviewselection . . . . . . . . . . . . . . . . . . . . . 340
mphwritestl . . . . . . . . . . . . . . . . . . . . . . . . 342
mphxmeshinfo . . . . . . . . . . . . . . . . . . . . . . . 343
CONTENTS |9
10 | C O N T E N T S
1
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 Multiphysics Programming
Reference Manual provides additional documentation of the COMSOL API.
In this chapter:
11
About this Product
LiveLink™ for MATLAB® connects COMSOL Multiphysics to the MATLAB scripting
environment. Using this functionality you can do the following:
12 | CHAPTER 1: INTRODUCTION
Connect to COMSOL Server ™
LiveLink™ for MATLAB® has the ability to connect to COMSOL Server™ as well as
COMSOL Multiphysics Server. This means that MATLAB scripts and GUIs that
utilize COMSOL functionality can be distributed to and used by any user that have
access to COMSOL Server™.
• Getting Help
• Where Do I Access the Documentation and the Application Libraries?
Getting Help
COMSOL Multiphysics and LiveLink™ for MATLAB® have several sources of help and
information.
T H E I N T R O D U C T I O N T O L I V E L I N K ™ for M A T L A B ®
To get started with LiveLink™, 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.
You can access the online documentation directly at the MATLAB prompt using the
function mphdoc.
mphdoc
mphdoc(node)
mphdoc(node,<fname>)
14 | CHAPTER 1: INTRODUCTION
where <fname> is a string defining the feature name in the COMSOL API, e.g.
mphdoc(model,'Rectangle').
help mphinterp
and
doc mphinterp
M-FILES
You can save COMSOL Multiphysics models as M-files. 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.
Since version 5.3 a new syntax closer to the structure in the Model Builder is available.
This new syntax includes the component node as in the example below:
model.component(<cTag>).geom(<geomTag>)
In the previous syntax to access the geometry node you need to enter:
model.geom(<geomTag>)
Both versions are fully supported, and the new syntax is used by default when saving a
model in the M-file format. To save a model M-file using the old syntax, you need to
change the preferences settings as described in the steps below:
At the MATLAB prompt use mphsave to save the model object model in the *.m
format as in the command below:
mphsave(model,<filename.m>)
To save the model object in the *.m format using the component syntax enter:
mphsave(model,<filename.m>,'component','on');
Models created with older versions than COMSOL 5.3 cannot be saved
using the component syntax unless File>Compact History is used.
16 | CHAPTER 1: INTRODUCTION
THE APPLICATION LIBRARIES WINDOW
If you have installed the COMSOL apps in the MATLAB Apps ribbon,
click the COMSOL Application Libraries icon ( ).
The following are some models that can help you get 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
If you are reading the documentation as a PDF file on your computer, the
blue links do not work to open an application 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), application examples, and documentation sets.
18 | CHAPTER 1: INTRODUCTION
Opening Topic-Based Help
The Help window is useful as it is connected to many of the features on the GUI. To
learn more about a node in the Model Builder, or a window on the Desktop, click to
highlight a node or window, then press F1 to open the Help window, which then
displays information about that feature (or click a node in the Model Builder followed
by the Help button ( ). This is called topic-based (or context) help.
• In the Model Builder or Physics Builder click a node or window and then
press F1.
• On the main toolbar, click the Help ( ) button.
• From the main menu, select Help>Help.
• Press Ctrl+F1.
• From the File menu select Help>Documentation ( ).
• Press Ctrl+F1.
• On the main toolbar, click the Documentation ( ) button.
• From the main menu, select Help>Documentation.
Once the Application Libraries window is opened, you can search by name or browse
under a module folder name. Click to view a summary of the application and its
properties, including options to open it or a PDF document.
To include the latest versions of model examples, from the Help menu
select ( ) Update COMSOL Application Library.
20 | CHAPTER 1: INTRODUCTION
CONTACTING COMSOL BY EMAIL
For general product information, contact COMSOL at [email protected].
To receive technical support from COMSOL for the COMSOL products, please
contact your local COMSOL representative or send your questions to
[email protected]. An automatic notification and case number is sent to you by
email.
COMSOL WEBSITES
Getting Started
In this chapter:
• The Client-Server Architecture
• Running COMSOL Models at the Command Line
• The COMSOL Apps
• Calling External Function within the Model
23
The Client-Server Architecture
LiveLink™ for MATLAB® uses the client-server mode to connect a COMSOL server
and MATLAB.
When starting COMSOL with MATLAB, two processes are started — a COMSOL
Multiphysics server and the MATLAB desktop. The COMSOL Desktop does not have
to be started, but it possible to have both MATLAB and COMSOL Desktop
connected to the same COMSOL Multiphysics server at the same time.
The communication between the two processes is based on a TCP /IP communication
protocol. You provide login information the first time COMSOL is started with
MATLAB. The login information is not related to the system’s username and
password. 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.
You can manually specify the port number. See the COMSOL
Multiphysics Installation Guide for more information on the COMSOL
server start-up properties.
A connection can be local (on the same computer), which is the common case, or
remote to a COMSOL server located on a different computer, in the later case you to
connect manually MATLAB to the COMSOL server as described in the section
Connecting a COMSOL server and MATLAB® Manually.
In this section:
• On Windows® use the COMSOL Multiphysics with MATLAB shortcut icon that is
created on the desktop after the automatic installation. A link is also available in the
Windows start menu under All Programs>COMSOL Multiphysics 5.3a>COMSOL
Multiphysics 5.3a with MATLAB.
• On Mac OS X, use the COMSOL with MATLAB application available in the Application
folder.
• On Linux®, enter the command comsol mphserver matlab at a terminal window.
To reset the login information, add the flag -login force to the icon
target path.
where filename.m is the file containing both MATLAB and COMSOL API
command to be executed using COMSOL with MATLAB.
The above command starts MATLAB without splash screen and without the MATLAB
desktop.
To avoid the splash screen on the COMSOL Server you need to create the
environment variable COMSOL_MATLAB_INIT and set it to matlab -nosplash.
COMSOL_MATLAB_INIT=’matlab -nosplash’
If the COMSOL Multiphysics server started listening to a different port than the
default one (which is 2036) use the mphstart function as in the command below:
mphstart(<portnumber>)
mphstart(<ipaddress>, <portnumber>)
<ipaddress> can also be defined with the COMSOL 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:
You can also specify all the information to connect a COMSOL server within the same
command, use the following command:
MEMORY SETTINGS
To be able to manipulate the model object and extract data at the MATLAB prompt,
you may need to modify the Java® heap size in MATLAB. See Improving Performance
for Large Models.
import com.comsol.model.util.*
ModelUtil.disconnect;
When using LiveLink for MATLAB with COMSOL Server™ this way MATLAB is
installed on the local computer where the user is executing commands and COMSOL
Server™ will most often be on another computer that is handled by an IT-department.
It is recommended to install Desktop and Start menu shortcuts. If these are not
installed, the only way to create a link between MATLAB and COMSOL Server is to
use the mphstart command as previously described for use with COMSOL
Multiphysics Server.
When clicking on this shortcut MATLAB will start and a dialog box appears that makes
it possible to connect to the COMSOL Server™ that is already assumed running
• Some graphical user interfaces that are included in a regular COMSOL Multiphysics
license do not work
• mphplot cannot plot on the server but has to plot on a local MATLAB figure.
1 From the File (Windows users) or Options menu (Mac and Linux users), select
Preferences ( ).
2 In the Preferences dialog box, click LiveLink products.
3 Set the MATLAB root directory path in the MATLAB installation folder field.
4 Windows OS users also need to click the Register MATLAB as COM Server button;
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.
1 In the MATLAB Desktop, go to the Apps Tab and select Install App.
2 Browse to the COMSOL Installation directory and go to the folder:
COMSOL53a/Multiphysics/mli/toolbox
3 Change File name extension to All Files (*.*) and select the file
LiveLink for MATLAB.mltbx
4 Click OK. This opens the Install LiveLink for MATLAB window.
• COMSOL Model Library, opens a GUI for viewing the Model Library, see also The
Application Libraries Window.
• COMSOL Model Navigator, opens a GUI for viewing the COMSOL model object
defined as model in MATLAB. You can get more information in the section
Navigating the Model Object Using a GUI.
• COMSOL Open, opens a GUI for opening recent files, see also Loading a Model
from a List of Existing files.
• COMSOL Search, opens a GUI for searching for expressions in the COMSOL
model object defined as model in MATLAB. See also Finding Model Expressions.
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:
37
The Model Object
While working with the LiveLink™ interface in MATLAB® you work with models
through the model object. Use methods to create, modify, and access models.
In this section:
• All algorithms and data structures for the model are integrated in the model object.
• The model object is used by the COMSOL Desktop to represent your model. This
means that the model object and the COMSOL Desktop behavior are virtually
identical.
• The model object includes methods to set up and run sequences of operations to
create geometry, meshes, and to solve your model.
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');
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');
ModelUtil.clear
List the names of the model objects available on the COMSOL server with the
command:
mphtags -show
ModelUtil.showProgress(true)
ModelUtil.showProgress(false)
Using the model history is a convenient way to learn the COMSOL API.
The latest settings enter in the command Desktop being listed at the end
of the M-file.
The model history is automatically enabled when the model is created in the
COMSOL Desktop. It is however possible to manually disable the model history
recording from the MATLAB prompt with the command:
model.hist.enable
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
model = mphopen(<filename>)
where <filename> is a string. This creates a model object Model on the COMSOL
server that is accessible using the MATLAB variable model.
mphopen <filename>
that will load the model with the given filename and use the variable name model for
accessing the model later. Any existing variable model will be overwritten without
warning.
The function mphload can also be used with the same property. In the
following documentation the commands also work with mphload.
Once the model is loaded, the file name and its associated model object tag are
displayed in the COMSOL server window.
If there is already a model object Model in the COMSOL server, mphopen overrides
the existing model object unless the model is also open in a COMSOL Multiphysics
Client. In the later case, an index number is appended to the new model object name,
for instance Model1.
mphopen and mphload do not look for lock file when opening a model
in the COMSOL server.
If you want to manually specify the model object in the COMSOL server. use the
command:
where <ModelTag> is a string defining the tag that defines the loaded model in the
COMSOL server.
When using the function mphopen, 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 mphopen:
model = mphopen(<filename>,'-history');
The history recording can be useful when using the COMSOL Desktop.
All the operations are then stored in the saved M-file.
If you do not want to update the recent opened file list with the model you are about
to open, use the -nostore flag with the function mphopen as in the command below:
If the model mph-file is protected using a password, use mphload as in the command
below:
mphopen
If you have installed the COMSOL apps in the MATLAB Apps ribbon,
click the COMSOL Open icon ( ).
For each selected files, the model information is available in the File Info section.
Click the Recent button to get the list of the recent opened file. Click the Search button
to search for a file using file pattern. Click the Browse button to browse the directory
where to get filename list.
mphopen -clear
To open the GUI with the list of files in a specific directory (<dirpath>), enter the
command:
SAVING A MODEL
Use the function mphsave to save the model object linked to the MATLAB object
model:
mphsave(model,<filename>)
where <filename> is a string. If the filename specified <filename> does not provide
a path, the file is saved relative to the current MATLAB path. The file extension
determines the format to use (*.mph, *.m, *.java, or *.vba).
model.save(<filename>)
If <filename> does not provide a path, the file is saved relative to the local server path.
Any files saved in the MPH format can be loaded by COMSOL Desktop. In addition,
the model can be saved as an M-file:
model.save(<filename>,'m')
When saving the model as an M-file mphsave does not automatically use
the component syntax to save model using the COMSOL API, to enable
this syntax run the command below:
mphsave(model,<filename>,'component','on')
You can also use a MATLAB figure to set the thumbnail. The following command will
set the thumbnail to the image of the current figure:
mphthumbnail(model,gcf)
Note that the thumbnail is stored in memory. In order to save the thumbnail in the
model file the model must be saved.
You can extract the image and image filename for the thumbnail stored in model, enter
the command:
Example
The code below shows how to get the model thumbnail as MATLAB image data, show
the image in a MATLAB figure and store the new image as thumbnail in the model.
mphopen model_tutorial_llmatlab
im = mphthumbnail(model);
imshow(im)
mphthumbnail(model, gcf)
mphlaunch
mphlaunch ModelTag
List the tags of the application loaded in the server with the command
mphtags.
You can also specify the MATLAB object name that is link to the application to be
imported in the COMSOL Desktop, enter the command:
mphlaunch(model)
1 From the File (Windows users) or Options menu (Mac and Linux users), select
COMSOL Multiphysics 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 COMSOL Multiphysics Server name (the
default name is localhost) and the Port number (the default is 2036). This number
corresponds to the port that the COMSOL Multiphysics Server is listening to, the
number is displayed at the COMSOL Multiphysics 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 Multiphysics Server.
The first time you connect the COMSOL Desktop to the COMSOL
Multiphysics Server no model is loaded to the GUI. See Import An
application from the COMSOL Multiphysics Server to the COMSOL
Desktop to know how connect the GUI to a model loaded in the
COMSOL Multiphysics Server.
1 From the File (Windows users) or Options menu (Mac and Linux users), select
COMSOL Multiphysics Server>Import Application from Server ( ).
2 In the Import Application from Server window, specify the application you want to
import.
model = ModelUtil.model(<ModelTag>)
where model is the variable in MATLAB used to access the model stored on the
COMSOL server and <ModelTag> is the tag of the COMSOL Model.
You can get the list of the models stored in the COMSOL Multiphysics server with the
command:
mphtags -show
ModelUtil.setServerBusyHandler(ServerBusyHandler(<timeout>))
Where <timeout> is the time in millisecond to wait the server to be free again.
model.component(<ctag>).geom.create(<geomtag>, sdim)
where <geomtag> is a string used to refer to the geometry and <ctag> is the string
defined when the component is created. The integer sdim specifies the space
dimension of the geometry and it can be either 0, 1, 2, or 3.
geometry.feature.create(<ftag>, operation)
where geometry is a link to the geometry node. The string <ftag> is used to refer to
the operation.
geometry.feature(<ftag>).set(property, <value>)
geometry.run
Alternatively, to build the geometry sequence up to and including a given feature ftag
enter:
geometry.run(<ftag>)
mphgeom(model)
mphgeom(model, <geomtag>)
Adding a view property will add some view settings from the COMSOL model such
as axes labels (units) and grid and supports hiding of geometric entities. Usually it is
sufficient to use the auto value for the view property:
If the model only contains a single geometry the <geomtag> can be left empty.
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:
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:
• vertexmode • edgecolor
• edgemode • vertexlabelscolor
• facemode • edgelabelscolor
• vertexlabels • facelabelscolor
• edgelabels • domainlabelscolor
• facelabels • facealpha
• domainlabels
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:
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
• Creating a 2D Geometry Using Primitive Geometry Objects
• Creating a 2D Geometry Using Boundary Modeling
• Creating a 3D Geometry Using Solid Modeling
CREATING A 1D GEOMETRY
From the MATLAB command prompt, create a 1D geometry model by adding a
geometry sequence and then adding geometry features. The last step is to run the
sequence using the run method.
model = ModelUtil.create('Model');
model.component.create('comp1',true);
geom1 = model.component('comp1').geom.create('geom1',1);
i1 = geom1.feature.create('i1','Interval');
i1.set('intervals','many');
i1.set('p','0,1,2');
geom1.run;
Then enter:
p1 = geom1.feature.create('p1','Point');
p1.set('p',0.5);
geom1.run;
mphgeom(model,'geom1','vertexmode','on');
model = ModelUtil.create('Model');
comp1 = model.component.create('comp1',true);
geom2 = comp1.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.
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.
co1 = geom2.feature.create('co1','Compose');
co1.selection('input').set({'c1' 'sq1'});
co1.set('formula','sq1-c1');
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;
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');
geom2.run;
The geometry sequence is updated with rounded corners. To view the result, enter:
model = ModelUtil.create('Model');
comp1 = model.component.create('comp1',true);
The objects c1, c2, c3, c4, c5, and c6 are all curve2 objects. The vector [1 w 1]
specifies the weights for a rational Bézier 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'});
g1.run;
model = ModelUtil.create('Model');
comp1 = model.component.create('comp1',true);
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;
geom1.runCurrent;
b1 = wp2.geom.feature.create('b1', 'BezierPolygon');
b1.set('type', 'open');
b1.set('degree', [1 1 1 1]);
b1.set('p',
{'0.75','1','1','0.8','0.75';'0.1','0.1','0.05','0.05','0.1'});
b1.set('w', {'1','1','1','1','1','1','1','1'});
geom1.run;
mphgeom(model);
model = ModelUtil.create('Model');
comp1 = model.component.create('comp1',true);
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
geom1.getUpDown
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 (0.2, 0.5), enter:
geom1.faceX(1,[0.2,0.5])
To get the range of the parameters of a given face, use the method
faceParamRange(N), where N is the face number. For example:
geom1.faceParamRange(1)
returns a 4x1 array following the given format: [s1min; s1max; s2min; s2max] where
s1min and s1max are the minimum, and maximum respectively, of the first surface
To get the parameter range of an edge, use the edgeParamRange(N) method. For
example, to get the length of edge number 3, enter:
geom1.edgeParamRange(3)
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
geom1.obj('blk1').getNBoundaries
geom1 = comp1.geom.create('geom1',2);
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);
model.param.set('a',0.5);
for a=0.2:0.1:0.5
model.param.set('a',a);
geom1.run;
end
Create a mesh:
comp1.mesh.create('mesh1');
std1 = model.study.create('std1');
p1 = model.batch.create('p1','Parametric');
p1.set('pname', 'a');
p1.set('plist','range(0.2,0.1,0.8)');
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
model.component(<ctag>).geom(<geomtag>).feature.create(<ftag>,
'InterpolationCurve')
ftag.set('table', <data>)
where ftag is the curve interpolation node and <data> can either be a 2xN cell array
or a 2xN array.
Control the type of geometry generated by the operation with the command:
ftag.set('type', type)
where type can either be 'solid' to generate a solid object, 'closed' to generate a
closed curve or 'open' to generate an open curve.
1 Create data points that describe a circle, sorted by the angle, and remove some of
the points:
phi = 0:0.2:2*pi;
phi([1 3 6 7 10 20 21 25 28 32]) = [];
p = [cos(phi);sin(phi)];
ic1.set('table', p');
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:
where imagedata is a C array containing the image data, and level is the contour
level value used to generate the geometry contour.
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:
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:
Set the minimum distance (in pixels) between coordinates in curve with the mindist
property where mindist is a double value:
Set the minimum area (in square pixels) for interior curves where minarea is a double
value:
To create a rectangle domain surrounding the object generated use the property
rectangle:
It is also possible to create a geometry object and include it in an existing model object,
to proceed use the command below:
where <geomnode> is the geometry node object where to include the newly generated
geometry.
To manually specify the tag of the model object created in the COMSOL server use
the command below:
where <Modeltag> is a string defining the tag of the model object in the COMSOL
server.
p = (peaks+7)*5;
[c,h] = contourf(p);
clabel(c, h);
model = mphimage2geom(p, 40);
figure(2)
mphgeom(model)
Use the property type to create closed or open curves. For example, to create a
geometry following contour 40 with closed curves, enter:
To scale the geometry, use the scale property. Using the current model scale the
geometry with a factor of 0.001 (1e-3):
To insert a rectangle in the geometry that has an outer domain surrounding the
created contour, set the property rectangle to on:
Only include the interior curves with an area larger than 100 square pixels:
model = mphopen('model_tutorial_llmatlab');
geom1 = model.component('comp1').geom('geom1');
wp1 = geom1.feature.create('wp1', 'WorkPlane');
wp1.set('quickz',1e-2);
mphimage2geom(p, 50, 'scale', 1e-3, 'geom', wp1.geom);
model.component(<ctag>).mesh.create(<meshtag>, <geomtag>)
where <meshtag> is a string that you use to refer to the meshing sequence. The tag
geomtag specifies the geometry to use for this mesh node.
mesh.feature.create(<ftag>, operation)
where mesh is a link to a mesh node and the string <ftag> is a string that you use to
refer to the operation.
mesh.feature(<ftag>).set(property, <value>)
mesh.run
mesh.run(ftag)
mphmesh(model)
If there are several meshes in a model, specify the mesh to display using the command:
mphmesh(model, <meshtag>)
Adding a view property will add some view settings from the COMSOL model such
as axes labels (units) and grid and supports hiding of mesh entities. Usually it is
sufficient to use the auto value for the view property:
If the model only contains one mesh then the <meshtag> may be left empty.
Use the parent property to specify the axes handle where to display the plot:
The following properties are also available to specify the vertex, edge, or face
rendering:
• vertexmode • meshcolor
• edgemode • edgecolor
• facemode • edgelabelscolor
• vertexlabels • vertexlabelscolor
• edgelabels • facelabelscolor
• facelabels • facealpha
These properties are available both globally and locally. The following examples are
included: Creating a 2D Mesh with Triangular Elements and Creating a 2D Mesh with
Quadrilateral Elements. Also discussed is The Free Meshing Method.
For details about predefined mesh size settings and mesh element size
parameters, see Size in the COMSOL Multiphysics Programming
Reference Manual.
model = ModelUtil.create('Model');
mesh1 = comp1.mesh.create('mesh1');
ftri1 = mesh1.feature.create('ftri1','FreeTri');
mesh1.run;
The default size feature is generated with the property hauto set to 5, that is:
mesh1.feature('size').set('hauto',5);
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)
Sometimes a nonuniform mesh is desirable. Make a mesh that is denser on the left side
by specifying a smaller maximum element size only on the edge segment to the left
(edge number 1):
mesh1.feature('size').set('hauto',5);
size1 = ftri1.feature.create('size1','Size');
size1.set('hmax',0.02);
size1.selection.geom('geom1',1);
size1.selection.set(1);
mesh1.run
model = ModelUtil.create('Model');
c1 = geom1.feature.create('c1','Circle');
c1.set('r','0.5');
co1 = geom1.feature.create('co1','Compose');
co1.selection('input').set({'c1' 'r1'});
co1.set('formula','r1-c1');
geom1.runAll;
mesh1 = comp1.mesh.create('mesh1');
ftri1 = mesh1.feature.create('ftri1','FreeTri');
ftri1.set('method','del');
mesh1.run;
mphmesh(model,'mesh1')
model = ModelUtil.create('Model');
comp1 = model.component.create('comp1', true);
geom1 = comp1.geom.create('geom1',2);
geom1.feature.create('c1','Circle');
mesh1 = comp1.mesh.create('mesh1');
mesh1.feature.create('ftri1','FreeQuad');
mesh1.run;
mphmesh(model)
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.
model = ModelUtil.create('Model');
comp1 = model.component.create('comp1', true);
geom1 = comp1.geom.create('geom1',2);
geom1.feature.create('r1','Rectangle');
r2 = geom1.feature.create('r2','Rectangle');
r2.set('pos',[1 0]);
c1 = geom1.feature.create('c1','Circle');
c1.set('r','0.5');
c1.set('pos',[1.1 -0.1]);
dif1 = geom1.feature.create('dif1', 'Difference');
dif1.selection('input').set({'r1' 'r2'});
dif1.selection('input2').set({'c1'});
geom1.run('dif1');
mesh1 = comp1.mesh.create('mesh1');
map1 = mesh1.feature.create('map1','Map');
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:
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.
model = ModelUtil.create('Model');
comp1 = model.component.create('comp1', true);
geom1 = comp1.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 = comp1.mesh.create('mesh1');
mesh1.run;
mphmesh(model)
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.
The left-hand side plot in Figure 3-7 is obtained with this command:
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;
Thus, to get the FreeQuad feature before the FreeTri feature, the dis1 feature needs
to be made the current feature by building it with the run method. Alternatively, parts
del1 = mesh1.feature.create('del1','Delete');
del1.selection.geom('geom1', 2).set(2);
del1.set('deladj','on');
frq1 = mesh1.feature.create('frq1','FreeQuad');
frq1.selection.geom('geom1', 2).set(2);
mesh1.run;
For further details on the various commands and their properties see the
COMSOL Multiphysics Programming Reference Manual.
model = ModelUtil.create('Model');
comp1 = model.component.create('comp1', true);
mesh1 = comp1.mesh.create('mesh1');
mesh1.feature.create('ftri1', 'FreeTri');
mesh1.feature('ftri1').selection.geom(2);
mesh1.feature('ftri1').selection.set(2);
mesh1.runCurrent;
mesh1.run;
mphmesh(model)
To obtain a torus, leave the angles property unspecified; the default value gives a
complete revolution.
model = ModelUtil.create('Model');
comp1 = model.component.create('comp1', true);
geom1 = comp1.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 = comp1.mesh.create('mesh1');
mesh1.run;
mphmesh(model);
model = ModelUtil.create('Model');
comp1 = model.component.create('comp1', true);
geom1 = comp1.geom.create('geom1', 3);
cone1 = geom1.feature.create('cone1', 'Cone');
cone1.set('r', 0.3).set('h', 1).set('ang', 9);
cone1.set('pos', [ 0 0.5 0.5]).set('axis', [-1 0 0]);
geom1.feature.create('blk1', 'Block');
mesh1 = comp1.mesh.create('mesh1');
mesh1.run;
mphmesh(model);
mphgeom(model,'geom1','facemode','off','facelabels','on')
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
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');
comp1 = model.component.create('comp1', true);
mesh1 = comp1.mesh.create('mesh1');
mesh1.run;
mphmesh(model);
It is also possible to insert boundary layers in an existing mesh. Use the following
meshing sequence with the geometry sequence from the previous example:
bl1.active(false);
Figure 3-12: Initial unstructured quad mesh (left) and resulting boundary layer mesh
(right).
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.
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 adaption solver step. See
Adaption in the COMSOL Multiphysics Programming Reference
Manual.
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');
comp1 = model.component.create('comp1', true);
mesh1 = comp1.mesh.create('mesh1');
mesh1.run;
mphmesh(model);
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:
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
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.
This example demonstrates how to convert a quad mesh into a triangle mesh:
model = ModelUtil.create('Model');
comp1 = model.component.create('comp1', true);
geom1 = comp1.geom.create('geom1', 2);
geom1.feature.create('c1', 'Circle');
geom1.feature.create('r1', 'Rectangle');
int1 = geom1.feature.create('int1', 'Intersection');
int1.selection('input').set({'c1' 'r1'});
mesh1 = comp1.mesh.create('mesh1', 'geom1');
mesh1.feature.create('fq1', 'FreeQuad');
mesh1.runCurrent;
mphmesh(model);
mesh1.feature.create('conv1', 'Convert');
mesh1.run;
mphmesh(model);
Figure 3-15: Mesh using free quad elements (left) and converted mesh from quad to
triangle (right).
IMPORTING MESHES
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:
mesh1.run;
mphmesh(model);
Where COMSOL is the path of root directory where COMSOL Multiphysics is installed.
The above command sequence results in Figure 3-16.
For a description of the text file format see the COMSOL Multiphysics
Reference Manual.
The following commands show how to visualize the mesh quality for a mesh on the
unit circle:
model = ModelUtil.create('Model');
comp1 = model.component.create('comp1', true);
geom1 = comp1.geom.create('geom1', 2);
geom1.feature.create('c1', 'Circle');
geom1.runAll;
mesh1 = comp1.mesh.create('mesh1');
mesh1.feature.create('ftri1', 'FreeTri');
mesh1.run;
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
Figure 3-17: Visualizations of the mesh quality: worst 25% (left) and best 25% (right).
stats = mphmeshstats(model)
If several mesh cases are available in the model object, specify the mesh tag:
stats = mphmeshstats(model,<meshtag>,'qualityhistogram',<num>)
Set the mesh quality measure from for the mesh statistics with the property
qualitymeasure:
stats = mphmeshstats(model,<meshtag>,'qualitymeasure',<quality>)
stats = mphmeshstats(model,<meshtag>,'entity',entity)
Use the selection property to specify the entity number where to get the mesh
statistics:
stats =
mphmeshstats(model,<meshtag>,'entity',entity,'selection',<selnum>
)
It is also possible to use the selection property to define a selection node defined in the
model:
stats = mphmeshstats(model,<meshtag>,'selection',<seltag>)
The properties entity and selection cannot be set if the mesh data
information is returned.
stats = mphmeshstats(model,<meshtag>,'type',type)
where type is one of the mesh element type available: vertex ('vtx'), edge ('edg'),
triangle ('tri'), quad ('quad'), tetrahedron ('tet'), pyramid ('pyr'), prism
('prism') or hexahedron ('hex'). type can also be a cell array to return the mesh
statistics of several mesh element type.
[meshstats,meshdata] = mphmeshstats(model)
model = ModelUtil.create('Model');
comp1 = model.component.create('comp1', true);
geom1 = comp1.geom.create('geom1', 2);
[meshstats,meshdata] = mphmeshstats(model);
meshdata =
vertex: [2x12 double]
elem: {[2x8 int32] [3x14 int32] [0 5 7 11]}
elementity: {[8x1 int32] [14x1 int32] [4x1 int32]}
vtx = meshdata.vertex
vtx =
Columns 1 through 7
0 0.5000 0.3024 0 0.6314 1.0000 0.3511
0 0 0.3023 0.5000 0.3632 0 0.6397
Columns 8 through 12
0 0.6730 1.0000 0.5000 1.0000
1.0000 0.6728 0.5000 1.0000 1.0000
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}
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:
The node distribution obtained with this command corresponds to the mesh in
Figure 3-18.
4 8
3 7
2 6
1 5
Figure 3-18: Mesh with elements (bold) and nodes (italic) indices.
ELEMENT NODES
1 1, 4, 5
2 1, 2, 5
3 2, 5, 6
4 2, 3, 6
5 4, 7, 8
6 4, 5, 8
7 5, 8, 9
8 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];
model.component(<ctag>).physics.create(<phystag>,physint,
<geomtag>)
where <phystag> is a string that identifies the physics interface node. 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.
phys.feature.create(<ftag>, operation)
where phys is a link to a physics node. <ftag> is a string that you use to refer to the
operation. To set a property to a value in a operation, enter:
phystag.feature(<ftag>).set(property, <value>)
To disable or remove a feature node, use the methods active or remove, respectively.
The command:
phystag.feature(<ftag>).active(false)
To activate the feature node you can set the active method to true:
phystag.feature(<ftag>).active(true)
phystag.feature.remove(<ftag>)
model = ModelUtil.create('Model');
comp1 = model.component.create('comp1', true);
The tag of the interface is ht. The interface constructor is HeatTransfer. The physics
is defined on geometry geom1.
comp1.physics('ht')
ans =
The physics method has the following child nodes: solid1, init1, ins1, idi1, os1,
and cib1. 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: Solid
Tag: solid1
Operation: SolidHeatTransferModel
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:
Then add a mesh and a study feature and compute the solution:
comp1.mesh.create('mesh1');
std = model.study.create('std1');
std.feature.create('stat', 'Stationary');
std.run
pg = model.result.create('pg1', 'PlotGroup3D');
pg.feature.create('surf1', 'Surface');
mphplot(model,'pg1','rangenum',1)
model.component(<ctag>).material.create(<mattag>)
A Material is a collection of material models, where each material model defines a set
of material properties, material functions, and model inputs. To add a material model,
use the syntax:
mat.materialmodel.create(<mtag>)
where mat is a link to a material node. The string <mtag> refers to the material model.
To define material properties for the model, set the property value pairs by entering:
mat.materialmodel(<mtag>).set(property, <value>)
mat = model.component('comp1').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');
info = phystag.feature(<ftag>).featureInfo('info');
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.
ht = model.component('comp1').physics('ht');
info = ht.feature('solid1').featureInfo('info');
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(:)
java.lang.String[]:
'(-(ht.k_effxx*Tx+ht.k_effxy*Ty+ht.k_effxz*Tz)*test(Tx)-(ht.k_eff
…'
'root.comp1.ht.solid1.weak$1'
'4'
'Spatial'
'Domain 1'
'3'
'-ht.rho*ht.Cp*(ht.ux*Tx+ht.uy*Ty+ht.uz*Tz)*test(T)*ht.d'
'root.comp1.ht.solid1.weak$2'
'4'
'Spatial'
'Domain 1'
'3'
'ht.streamline'
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_effy
x*Tx+ht.k_effyy*Ty+ht.k_effyz*Tz)*test(Ty)-(ht.k_effzx*Tx+ht.k_ef
fzy*Ty+ht.k_effzz*Tz)*test(Tz))*ht.d
equExpr = '200[W/(m*K)]*(-Tx*test(Tx)-Ty*test(Ty)-Tz*test(Tz))';
info.lock(list(2), {equExpr});
These commands set the heat conductivity to a constant value directly within the heat
balance equation.
model.component(<ctag>).physics.create(<odestag>,
'GlobalEquations')
To define the name of the variable to be solved by the global equation, enter:
where ode is a link to a Global Equations node and <idx> is the index of the global
equation, and <name> a string with the name of the variable.
Initial value and initial velocity can be set with the commands:
·
·· u
u + --- + 1 = 0
2
u0 = 0
·
u 0 = 20
model.func.create(<functag>, 'Interpolation')
If you have several model nodes in your model and you want to attach it to the
specified component node <ctag>, enter:
model.component(<ctag>).func.create(<functag>, 'Interpolation')
where <ctag> 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:
where func is a link to a function node and <t_value> is the interpolation parameter
value and <ft_value> is the function value. <i> is the index (0-based) in the
interpolation table. If the number of rows is large then it takes a long time to create
the table element by element. Instead store all the data as a cell array of strings and
set the values all at once:
func.set('table', data)
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:
func.set('source', 'file')
func.set('filename', <filename>)
Several interpolation methods are available. Choose the one to use with the command:
func.set('interp', method)
func.set('extrap', method)
model.component(<ctag>).selection.create(<seltag>, 'Explicit')
To specify the domain entity dimension to use in the selection node, enter:
sel.geom(sdim)
• 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:
sel.set(<idx>)
where <idx> is an array of integers that list the geometric entity indices to add in the
selection.
Coordinate-Based Selections
model.component(<ctag>).selection.create(<seltag>, 'Ball')
To set the coordinates (<x0>, <y0>, <z0>) of the selection center point, enter:
sel.set('posx', <x0>)
sel.set('posy', <y0>)
sel.set('posz', <z0>)
where sel is a link to a Ball Selection node and <x0>, <y0>, <z0> are double values.
sel.set('r', <r0>)
sel.set('entitydim', edim)
The selection also specifies the condition for geometric entities to be selected:
sel.set('condition', condition)
To get the geometric entities enclosed by a ball of radius r0, with its center positioned
at (x0,y0,z0) enter the command:
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.
You can also refine the search using several search ball. To do so set the coordinates as
a NxM array where N corresponds of the number of point to use and M the space
dimension of the geometry as in the command below:
This returns the geometric entity indices that have vertices near both the given
coordinates using the tolerance radius.
To include any geometric entities in the selection that have at least one vertex inside
the search ball, set the property include to 'any':
where <idx> is the domain index adjacent to the desired geometric entities.
model.component(<ctag>).selection.create(<seltag>, 'Box')
To specify the points (<x0>, <y0>, <z0>) and (<x1>, <y1>, <z1>), enter:
sel.set('xmin', <x0>)
sel.set('ymin', <y0>)
sel.set('zmin', <z0>)
sel.set('xmax', <x1>)
sel.set('ymax', <y1>)
sel.set('zmax', <z1>)
where sel is a link to a Box Selection node and <x0>, <y0>, <z0>, <x1>, <y1>, <z1>
are double values.
sel.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:
sel.set('condition', condition)
To get the geometric entities of type entitytype enclosed by the box defined by the
points (x0,y0,z0) and (x1,y1,z1), enter the command:
idx = mphselectbox(model,<geomtag>,...
[<x0> <x1>;<y0> <y1>;<z0> <z1>], entitytype)
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.
c = mphgetcoords(model,<geomtag>,entitytype,<idx>)
model.component(<ctag>).selection.create(<seltag>, 'Adjacent')
sel.set(edim)
where sel is a link to an Adjacent Selection node and 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:
sel.set( 'Adjacent')
sel.set('input', <seltag>)
Select the level of geometric entities to add in the selection with the command:
sel.set('outputdim', 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).
If there are multiple domains in the geometry to include in the interior and exterior
selected geometric entities, then enter:
sel.set('interior', 'on')
sel.set('exterior', 'on')
To get a list of entities of type entitytype adjacent to the entity with the index
<adjnumber> of type adjtype, enter:
where <geomtag> is the tag of geometry where the selection applies, returntype is
the type of geometry entities whose index are returned and adjtype is the type of
input geometry entity. The string variables returntype and adjtype can be one of
'point', 'edge', 'boundary', or 'domain'.
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:
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 axes, set the property 'parent' with the axes
handle. For instance, the command below displays the selection in the current axis:
• 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.
• 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])
• Study steps, which determines overall settings suitable for a certain study type,
• Solver sequence, and
• Job configurations for distributed parametric jobs, batch jobs, and cluster
computing.
model.study.create(<studytag>)
study.feature.create(<ftag>, operation)
where study is a link to 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.
study.feature(<ftag>).set(property, <value>)
To generate the default solver sequence associated with the physics solved in the model
and compute the solution, run the study node with the command:
study.run
model.sol.create(<soltag>)
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:
sol.study(<studytag>)
where <studytag> is the tag of the study you want to associate the solver sequence
sol.
• Study Step, where the study and study step is specified for compiling the equations
and computing the current solver sequence;
sol.feature.create(<ftag>, operation)
where sol is a link to a solver sequence node. 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'.
feat.set(property, <value>)
For a list of the operations available for the solver node, see Features
Producing and Manipulating Solutions and Solvers and Study Steps, in
the COMSOL Multiphysics Programming Reference Manual.
Use the methods run or runAll to run the entire solver configuration node:
model.sol(<soltag>).run
model.sol(<soltag>).runAll
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>)
study.feature.create(<ftag>, 'Parametric')
where study is a link to a valid study node where to include the parametric sweep
defined with the tag <ftag>.
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.
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:
study.feature(<ftag>).set('sweeptype', type)
where type is a string defining the sweep type, it can take either the value 'filled'
or 'sparse', referring to all combinations or specified combinations of the parameter
values, respectively.
model.batch.create(<batchtag>, type)
For a solver sequence you need to attach the job sequence to an existing study node.
Enter the command:
model.batch(<batchtag>).atach(<studytag>)
Each job type, such as parametric, batch, or cluster job, can be defined with specific
properties. Use the set method to add a property to the batch job:
model.batch(<batchtag>).set(property, <value>)
You can get the list of the properties in model.batch() in the COMSOL
Multiphysics Programming Reference Manual or type at the MATLAB
prompt: mphdoc(model.batch).
model.batch(<batchtag>).run
study.feature(<studysteptag>).set('plot', 'on')
where study is a link to a valid study node and <studysteptag> is a string that refers
to the study step.
Specify the plot group to plot by setting the plot group tag:
study.feature(<studysteptag>).set('plotgroup', <ptag>)
To activate Plot While Solving for a probe plot, enter the command:
study.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:
study.feature(<studysteptag>).set('probes', <list>)
where <list> is the a cell array containing the list of the probe to use.
model.result.create(<pgtag>, sdim)
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:
pg.feature.create(<ftag>, plottype)
where pg is a link to a plot group node and plottype is a string that defines the plot
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:
pg.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 Multiphysics
Programming Reference Manual or type at the MATLAB prompt:
mphdoc(model.result).
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 COMSOL Multiphysics Server. To do this for a plot group
<pgtag> enter:
Another way to plot in a COMSOL Graphics window is to use the run method:
model.result(<pgtag>).run
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:
where the integer <idx> identifies the plot for which the color legend should be
displayed.
pd = mphplot(model, <pgtag>)
The data fields contained in pd returned by mphplot are subject to change. The most
important fields are:
• p, the coordinates for each point that are used for creating lines or triangles.
• n, the normals in each point for the surfaces. These are not always available.
• t, contains the indices to columns in p of a simplex mesh, each column in t
representing a simplex.
• d, the data values for each point.
• rgb, the color values (red, green and blue) entities at each point.
If you don’t want to generate a figure when extracting the plot data structure, set the
property createplot to off as in the command below:
model = mphopen('model_tutorial_llmatlab');
std = model.study.create('std');
std.feature.create('stat','Stationary');
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')
surf2 = pg.feature.create('surf2', 'Surface');
surf2.set('data', 'dset1').set('expr', 'ht.tfluxMag');
Now plot the result and extract the associated plot data structure:
pd = mphplot(model,'pg');
pd1 = pd{1}{1}
pd1 =
p: [3x1410 single]
t: [2x816 int32]
rgb: [3x1 double]
type: 'line'
plottype: 'PlotGroup3D'
tag: 'pg'
preserveaspect: 'on'
title: 'Surface: Temperature (K) Surface: Total heat
flux magnitude (W/m^{2})'
To investigate the plot data information of the second surface plot feature (surf2)
enter:
pd3 = pd{3}{1}
pd3 =
p: [3x5250 single]
n: [3x5250 single]
t: [3x9558 int32]
d: [5250x1 single]
colortable: 'Rainbow'
rgb: [5250x3 single]
type: 'surface'
plottype: 'Surface'
tag: 'surf2'
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 supports only plotting of data structures that are of the type
point, line or surface evaluations from mpheval.
Using the colortable option to select from several available color tables when
visualizing data:
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:
First load the Busbar model from the COMSOL Multiphysics Applications Libraries.
Enter:
model = mphopen('busbar');
To extract the temperature and the electric potential field, use the command mpheval:
dat = mpheval(model,{'T','V'},'selection',1);
mphplot(dat,'index',1,'colortable','thermal');
dat.d2 = dat.d2*1e-3;
To emphasize the geometry use the function mphgeom to display line plot on the same
figure:
hold on;
mphgeom(model, 'geom1', 'facemode', 'off')
All plots refer to data sets; the solutions are always available as the default
data set.
model.result.numerical.create(<numtag>, numtype)
For a list of the syntax of the numerical results type available, see About
Results Commands in the COMSOL Multiphysics Programming
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')
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 COMSOL Multiphysics Server to enable plot on server.
model.result.export.create(<animtag>, 'Animation')
To change the animation type use the 'type' property according to:
animtag.set('type', type)
animtag.set(typefilename, <filenname>)
animtag.run
animtag.set('fps', <fps_number>)
For all animation types you can modify the width and the height of the plot with the
set method:
animtag.set('width', <width_px>)
animtag.set('height', <height_px>)
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>)
model.result.export(<datatag>).set('struct', datastruct)
To export the data in the specified file, run the export node:
model.result.export.(<datatag>).run
ANIMATION PLAYER
For transient and parametric studies, an animation player can be generated to create
interactive animations.
model.result.export.create(<playtag>, 'Player')
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.
model.result.export(<playtag>).run
This section introduces you to the functionality available for LiveLink™ for
MATLAB® including the wrapper functions and the MATLAB tools that can be
®
used and combined with a COMSOL Multiphysics model object.
In this chapter:
149
Using Workspace Variables in Model
Settings
LiveLink™ for MATLAB® allows you to define the model properties with MATLAB
variables or a MATLAB M-function.
In this section:
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. <value>
can also be a string, in this case the value or expression is defined within the model
object.
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]'])
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 or a string, 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:
where [unit] is the unit you want to set the value property.
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.
feature.set(property, myfun(<arg>))
The function is called only when the command is executed at the MATLAB prompt.
The argument of the function <arg> called can be MATLAB variables. To include an
expression value from the model object, first extract it at the MATLAB prompt, as
described in Extracting Results.
The function myfun() accepts the model object model as an input argument as any
MATLAB variable.
In this section:
[d1,...] = mphinterp(model,{'e1',...},'coord',<coord>)
The rest of this section has additional information for the function mphinterp:
<dsettag> is the tag of a solution data set or a mesh data set. The default value is
the current solution data set of the model. When a mesh data set is specified the
expression <expr> can only be geometry or mesh expression.
• selection, specify the domain selection for evaluation:
data =
mphinterp(model,<expr>,'coord',<coord>,'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:
data = mphinterp(model,<expr>,'coord',<coord>,'edim',edim)
where edim is one of the strings 'point', 'edge', 'boundary' or 'domain'. One
can also use numerical values instead, which in 3D are the values from 0 to 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.
• 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 = mphinterp(model,<expr>,'coord',<coord>,solnum',<solnum>)
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>)
OUTPUT FORMAT
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:
To extract the unit of the evaluated expression, define an extra output variable:
with unit is a 1xN cell array where N is the number of expressions to evaluate.
Returns only the real part in the data evaluation with the property complexout:
data = mphinterp(model,<expr>,'coord',<coord>,'complexout','off')
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')
By default the function returns the value NaN for any points that are outside the
domain.
data = mphinterp(model,<expr>,'coord',<coord>,'evalmethod',method)
If the property evalmethod is set to harmonic, you specify whether the expression
should be linearized or not with the property differential as shown below:
The default property value settings ('on') evaluates the differential of the expression
with respect to the perturbation at the linearization point. If diffvalue is off, it
evaluates the expression by taking the values of any dependent variables from the
harmonic perturbation part of the solution.
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.
data = mphinterp(model,<expr>,'coord',<coord>,'unit',<unit>)
To not use complex-value functions with real inputs, use the property complexfun:
data = mphinterp(model,<expr>,'coord',<coord>,'complexfun','off')
Use the property matherr to return an error for undefined operations or expressions:
• data =
mphinterp(model,<expr>,'coord',<coord>,'matherr','on')
To evaluate the minimum of the COMSOL expressions e1,... use the command
mphmin:
[d1,...] = mphmin(model,{'e1',...},edim)
The rest of this section has additional information for the function mphmin:
<dsettag> is the tag of a solution data set. The default value is the current solution
data set of the model.
• selection, specify the domain selection for evaluation:
data = mphmin(model,<expr>,edim,'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.
• 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>)
where <time> is a double array. The default value corresponds to all the stored time
steps.
• In case of data series, such as from a parametric or a transient study, an operation
can be applied. To perform data series operation use the function mphmin as in the
command below:
data = mphmin(model,<expr>,edim,'dataseries',<dataoperation>)
where <dataoperation> can be one of the following value: 'none' (no operation
performed), 'average' (to compute average of the selected series), 'integral'
(to integrate over series), 'maximum' (to evaluate the maximum over series),
'minimum' (to evaluate the minimum), 'rms' (to compute the root mean square),
'stddev' (to compute the standard deviation) or 'variance' (to compute the
variance).
OUTPUT FORMAT
The function mphmin also supports other output formats.
To extract the unit of the evaluated expression, define an extra output variable:
[data,unit] = mphmin(model,<expr>,edim)
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')
To evaluate the maximum of the COMSOL Multiphysics expressions e1,... use the
command:
[d1,...] = mphmax(model,{'e1',...},edim)
where edim is a string to define the element entity dimension: 'volume', 'surface',
or 'line'. edim can also be a positive integer (3, 2, or 1 respectively). The output
variables d1,... 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:
<dsettag> is the tag of a solution data set. The default value is the current solution
data set of the model.
• selection, specify the domain selection for evaluation:
data = mphmax(model,<expr>,edim,'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.
• 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:
where <time> is a double array. The default value corresponds to all the stored time
steps.
• In case of data series, such as from a parametric or a transient study, an operation
can be applied. To perform data series operation use the function mphmax as in the
command below:
data = mphmax(model,<expr>,edim,'dataseries', <dataoperation>)
where <dataoperation> can be one of the following value: 'none' (no operation
performed), 'average' (to compute average of the selected series), 'integral'
(to integrate over series), 'maximum' (to evaluate the maximum over series),
'minimum' (to evaluate the minimum), 'rms' (to compute the root mean square),
'stddev' (to compute the standard deviation) or 'variance' (to compute the
variance).
OUTPUT FORMAT
The function mphmax also supports other output formats.
To extract the unit of the evaluated expression, define an extra output variable:
[data,unit] = mphmax(model,<expr>,edim)
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:
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')
Evaluating an Integral
Evaluate an integral of expression with the function 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,...] = mphint2(model,{'e1',...},edim)
where e1,... are the expressions to integrate. The values d1,... 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:
<dsettag> is the tag of a solution data set. The default value is the current solution
data set of the model.
• selection, specify the integration domain:
data = mphint2(model,<expr>,edim,'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.
where <time> is a double array. The default value corresponds to all the stored time
steps.
• In case of data series, such as from a parametric or a transient study, an operation
can be applied. To perform data series operation use the function mphint2 as in the
command below:
data = mphint2(model,<expr>,edim,'dataseries',<dataoperation>)
where <dataoperation> can be one of the following value: 'none' (no operation
performed), 'average' (to compute average of the selected series), 'integral'
(to integrate over series), 'maximum' (to evaluate the maximum over series),
'minimum' (to evaluate the minimum), 'rms' (to compute the root mean square),
'stddev' (to compute the standard deviation) or 'variance' (to compute the
variance).
OUTPUT FORMAT
The function mphint2 also supports other output formats.
To extract the unit of the evaluated expression, define an extra output variable:
[data,unit] = mphint2(model,<expr>,edim)
with unit is a 1xN cell array where N is the number of expressions to evaluate.
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')
For data sets other than Solution, Particle, Cut*, Time Integral, Time
Average, Surface, and Line, the integration order does correspond to an
element refinement.
[d1,...] = mphmean(model,{'e1',...},edim)
The rest of this section has additional information for the function mphmean:
<dsettag> is the tag of a solution data set. The default value is the current solution
data set of the model.
• selection, specify the domain selection for evaluation:
data = mphmean(model,<expr>,edim,'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.
• 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>)
where <time> is a double array. The default value corresponds to all the stored time
steps.
• In case of data series, such as from a parametric or a transient study, an operation
can be applied. To perform data series operation use the function mphmean as in the
command below:
data = mphmean(model,<expr>,edim,'dataseries',<dataoperation>)
where <dataoperation> can be one of the following value: 'none' (no operation
performed), 'average' (to compute average of the selected series), 'integral'
(to integrate over series), 'maximum' (to evaluate the maximum over series),
'minimum' (to evaluate the minimum), 'rms' (to compute the root mean square),
'stddev' (to compute the standard deviation) or 'variance' (to compute the
variance).
OUTPUT FORMAT
The function mphmean also supports other output formats.
To extract the unit of the evaluated expression, define an extra output variable:
[data,unit] = mphmean(model,<expr>,edim)
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')
pd = mpheval(model, <expr>)
where <expr> is a string cell array that lists the expression to evaluate. The expression
has to be defined in the COMSOL model object in order to be evaluated.
• 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:
<dsettag> is the tag of a solution data set. The default value is the current solution
data set of the model. Selection data sets 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)
• 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:
pd = mpheval(model, <expr>, 'solnum', <solnum>)
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>)
OUTPUT FORMAT
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.
This is speeds up the call to COMSOL since the coordinate and element information
is not retrieved.
Returns only the real part in the data evaluation with the property complexout:
where <refine> is a positive integer. The default value is 1 which set the simplex
mesh identical to the geometric mesh. Many model use second order elements for
which a refine value of 2 must be used to use all the data in the model.
• smooth, specify the smoothing method to enforce continuity on discontinuous data
evaluation:
pd = mpheval(model, <expr>, 'smooth', smooth)
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.
Use the property matherr to return an error for undefined operations or expressions:
where e1,... are the COMSOL expressions to evaluate. The output d1,... 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:
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>)
where <time> is a double array. The default value corresponds to all the stored time
steps.
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
operations—mean, 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)
OUTPUT FORMAT
The function mphevalpoint supports other output formats.
To extract the unit of the evaluated expression, define an extra output variable:
[data,unit] = mphevalpoint(model,<expr>)
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')
In this section you can replace the command mphparticle and mphray
as they support the same properties.
Evaluate expressions on particle and ray trajectories with either the function
mphparticle or mphray.
To evaluate the particle position and the particle velocity run mphparticle as in this
command:
pd = mphparticle(model)
• 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:
Use a string cell array to evaluate several expressions at once. The result of the
evaluation is then stored in the field d1,... corresponding to each evaluated
expression.
<dsettag> is the tag of a particle solution data set. The default value is the current
particle solution data set of the model.
• To evaluate the expression data at a specific time use the property t:
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 function mphparticle also supports other output formats.
Set the property dataonly to on to return only the data related to the specified
expression:
pd = mphparticle(model,'expr',<expr>,'dataonly','on')
The output structure pd only contains the field unit, d#, expr, and t (described
above).
[d1,...] = mphglobal(model,{'e1',...})
The rest of this section has additional information for the function mphglobal:
<dsettag> is the tag of a solution data set. The default value is the current solution
data set of the model.
• 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 = mphglobal(model,<expr>,'solnum',<solnum>)
where <time> is a double array. The default value corresponds to all the stored time
steps.
OUTPUT FORMAT
The function mphglobal also supports other output formats.
To extract the unit of the evaluated expression, define an extra output variable:
[data,unit] = mphglobal(model,<expr>)
with unit is a 1xN cell array where N is the number of expressions to evaluate.
Returns only the real part in the data evaluation with the property complexout:
data = mphglobal(model,<expr>,'complexout','off')
data = mphglobal(model,<expr>,'unit',<unit>)
Use the property matherr to return an error for undefined operations or expressions:
data = mphglobal(model,<expr>,'matherr','on')
M = mphevalpointmatrix(model,<expr>,...)
The rest of this section has additional information for the function
mphevalpointmatrix:
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:
M = mphevalpointmatrix(model,<expr>,'solnum',<solnum>)
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:
M = mphevalpointmatrix(model,<expr>,'dataseries', dataseries)
To evaluate the global matrix associated to the expression <expr>, enter the
command:
M = mphevalglobalmatrix(model,<expr>)
The output data M is a NxN double array, where N is the number of port boundary
condition set in the model.
The rest of this section has additional information for the function
mphevalglobalmatrix:
• Set the solution data set for evaluation with the property dataset:
M = mphevalglobalmatrix(model,<expr>,'dataset',<dsettag>)
• 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:
M = mphevalglobalmatrix(model,<expr>,'solnum',<solnum>)
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:
M = mphevalglobalmatrix(model,<expr>,'dataseries', dataseries)
M = mphevalglobalmatrix(model,<expr>,'trans',<trans>)
M = mphevalglobalmatrix(model,<expr>,'trans','sy','y0',<value>)
M = mphevalglobalmatrix(model,<expr>,'trans','ys','y0',<value>)
M = mphevalglobalmatrix(model,<expr>,'trans','sz','z0',<value>)
M = mphevalglobalmatrix(model,<expr>,'trans','zs','z0',<value>)
Use mphtable to extract the data stored in the table with the tag <tbltag>. Enter:
tabl = mphtable(model,<tbltag>)
In this section:
By using the COMSOL built-in function to run models in loops, you can
ensure the model is saved automatically at each iteration. COMSOL also
offers tools to take advantage of clusters and distributed computer
architectures.
To run a model in a loop you do not need to run the entire M-file’s commands from
scratch. It is recommended to load a COMSOL model in MATLAB and run the loop
only over the desired operations. The COMSOL model is automatically updated when
running the study node.
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 needed 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.
GEOMETRY PARAMETRIZATION
This example shows how to proceed to geometry parametrization using a MATLAB
for loop. The model consists of the busbar example available in the COMSOL
Multiphysics Applications Libraries; see the Introduction to COMSOL Multiphysics.
In this example the loop iterates over the busbar’s width, wbb. The solution for each
parameter value is displayed using the second plot group defined in the COMSOL
model. All the results are plotted in the same figure.
To run in batch an M-script that runs COMSOL Model is required. Start COMSOL
with MATLAB at a terminal window with this command:
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:
These steps describe how to run an M-script that runs a COMSOL model:
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
in order to connect MATLAB to COMSOL:
matlab -nodesktop -nosplash -r "mphstart; myscript"
For more information about how to connect MATLAB to a COMSOL server see
Starting COMSOL® with MATLAB® on Windows ®/ Mac OSX / Linux®.
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.
See the Advanced section and the Assemble section in the COMSOL
Multiphysics Reference Manual, for more information about matrix
evaluation.
The system matrices that can be extracted with mphmatrix are listed in the table:
EXPRESSION DESCRIPTION
K Stiffness matrix
L Load vector
M Constraint vector
N Constraint Jacobian
D Damping matrix
E Mass matrix
NF Constraint force Jacobian
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)
To set the solution to use for the linearization point, use the property initsol:
str = mphmatrix(model,<soltag>,'out',out,'initsol',<initsoltag>)
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.
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.
str = mphmatrix(model,<soltag>,'out',out,'extractafter',<nodetag>)
where <nodetag> is the tag of a solution sequence node such as dependent variable or
solver nodes.
EIGENVALUE PROBLEMS
For eigenvalue problems, it is necessary to specify the eigenvalue name and the
eigenvalue linearization point. Used the property eigname to specify the name of the
eigenvalue and eigref to specify the value of eigenvalue linearization point:
str = mphmatrix(model,<soltag>,'out',out,'eigname',<eigname>)
str = mphmatrix(model,<soltag>,'out',out,'eigname',<eigname>,...
'eigref', <eigref>)
str = mphmatrix(model,<soltag>,'out',out,'rowscale','off')
str = mphmatrix(model,<soltag>,'out',out,'symmetry',sym)
Use the nullfun property to specify the method for computation of matrices needed
for constraint handling:
COMPLEX FUNCTION
If the system contains complex function, use the property complexfun to specify how
to handle such a function. Set this property to on to use complex-valued function with
real input:
str = mphmatrix(model,<soltag>,'out',out,'complexfun','on');
str = mphmatrix(model,<soltag>,'out',out,'matherr','off')
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 and the discretization is set with linear element.
model = ModelUtil.create('Model2');
comp1 = model.component.create('comp1', true);
geom1 = comp1.geom.create('geom1', 2);
geom1.feature.create('sq1', 'Square');
geom1.run;
mat1 = comp1.material.create('mat1');
def = mat1.materialModel('def');
def.set('thermalconductivity',4e2);
temp1 = ht.feature.create('temp1','TemperatureBoundary',1);
temp1.selection.set([1 2]);
mesh1 = comp1.mesh.create('mesh1');
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;
To extract the solution vector of the computed solution, run the function mphgetu as
in this command:
U = mphgetu(model);
Solve for the eliminated solution vector using the extracted eliminated system:
Uc = MA.Null*(MA.Kc\MA.Lc);
U0 = Uc+MA.ud;
U1 = U0.*MA.uscale;
mphinputmatrix(model,<str>,<soltag>,<soltypetag>)
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:
FIELD DESCRIPTION
K Stiffness matrix
L Load vector
M Constraint vector
N Constraint Jacobian
EXPRESSION DESCRIPTION
K Stiffness matrix
L Load vector
M Constraint vector
N Constraint Jacobian
D Damping matrix
E 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 when it is saved in the
MPH-format or loaded to the COMSOL Desktop.
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.
model = mphopen('model_tutorial_llmatlab.mph');
mphgeom(model)
Draw the line to be used as a line heat source in the model and plot the modified
geometry:
comp1 = model.component('comp1');
b1 = comp1.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);
mesh1 = comp1.mesh('mesh1');
mesh1.feature.create('ftet1', 'FreeTet');
mesh1.feature('size').set('hauto', 3);
mesh1.run;
mphmesh(model)
std1 = model.study.create('std1');
std1.feature.create('stat', 'Stationary');
sol1 = model.sol.create('sol1');
sol1.study('std1');
st1 = sol1.feature.create('st1', 'StudyStep');
st1.set('studystep', 'stat');
Shape = comp1.physics('ht').prop('ShapeProperty');
Shape.set('order_temperature', 1, 1);
The heat transfer interface automatically compute for internal DOFs in order to
evaluate fluxes accurately at the boundaries. Deactivate the internal DOFs with this
command:
Shape.set('boundaryFlux_temperature', false);
Now extract the matrices of the linear system associated to the solver sequence sol1:
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:
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:
dofs = info.elements.edg.dofs;
edgdofs_idx = [];
for i = 1:length(elem_idx)
edgdofs_idx = [edgdofs_idx; 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_idx = unique(edgdofs_idx);
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')
Note: mphmatrix only assembles the matrix system for the dofs solved in the specified
solver configuration. mphinputmatrix insert the matrix system as defined by the user.
When inserting matrices in an existing model, the solution format may not be
compatible with the inserted system matrices.
In order to have a compatible xmesh solution format compatible with the size of the
inserted matrices, add a new equation form physics interface, solving only for one
variable.
comp1.physics('ht').active(false);
model.sol('sol1').runAll;
This section includes information about The State-Space System, how to Extract
State-Space Matrices and Set Linearization Points and has an Extracting State-Space
Matrices.
dx
------- = Ax + Bu
dt
y = Cx + Du
·
M C x = M C Ax + M C Bu
y = Cx + Du
This form is more suitable for large systems because the matrices MC and MCA usually
become much more sparse than A.
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 + u 0
where u0 is the linearization point, which is the solution stored in the sequence once
the state-space export feature is run.
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:
EXPRESSION DESCRIPTION
MA McA matrix
MB McB matrix
A A matrix
B B matrix
C C matrix
D D matrix
Mc Mc matrix
Null Null matrix
ud ud vector
x0 x0 vector
To keep the state-space feature node, set the property keepfeature to on:
You can manually select the linearization point to use. Use the initmethod property
to select a linearization point:
To set the solution to use for the linearization point, use the property initsol:
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:
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.
model = mphopen('heat_transient_axi');
model.param.set('Tinput','1000[degC]');
comp1 = model.component('comp1');
comp1.physics('ht').feature('temp1').set('T0', 1, 'Tinput');
time = model.study('std1').feature('time');
time.set('tlist','range(0,50,2e3)');
Extract the matrices of the state-space system using Tinput as an input variable and
the probe comp1.ppb1 as an output variable:
u = 1;
T0= 1273.15;
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);
1200
1000
800
600
400
200
0 200 400 600 800 1000 1200 1400 1600 1800 2000
Figure 4-1: Temperature distribution computed with the state-space system (blue line) and
COMSOL Multiphysics (red marker).
The function mphreduction can be used to add studies to a model that add a training
and model reduction study to a model. The number of eigenvalues can be specified as
well as their range. mphreduction returns state-space matrices or a MATLAB
state-space model using the ss function.
See the Modal Reduced-Order Model and The Modal Solver Algorithm in the
COMSOL Multiphysics Reference Manual for more information.
The following example sets up a model using commands from MATLAB. If the Heat
Transfer Module or MEMS Module is available, then the model can be set up using
the Heat Transfer in Solids physics interface. If these modules are not available, the
example shows how to set up the model using the Heat Equation from the collection
of classical PDEs in COMSOL Multiphysics.
Geometry
First the model and its geometry and mesh are constructed. The parameter Qin is later
used as an input for the reduced state-space model.
model = ModelUtil.create('Model');
model.component.create('comp1', true);
model.param.set('Qin', '10000');
model.component('comp1').geom.create('geom1', 2);
model.component('comp1').mesh.create('mesh1');
model.component('comp1').mesh('mesh1').autoMeshSize(3);
model.component('comp1').geom('geom1').create('r1', 'Rectangle');
model.component('comp1').geom('geom1'). ...
feature('r1').set('size', [0.1 0.01]);
model.component('comp1').geom('geom1').run;
Flux boundary conditions are set up at the left side (1) and top (3) of the rectangle.
model.component('comp1').physics('ht'). ...
create('hf1', 'HeatFluxBoundary', 1);
model.component('comp1').physics('ht').feature('hf1').set('q0', 'Qin');
model.component('comp1').physics('ht').feature('hf1').selection.set(1);
model.component('comp1').physics('ht'). ...
create('hf2', 'HeatFluxBoundary', 1);
model.component('comp1').physics('ht').feature('hf2').selection.set(3);
model.component('comp1').physics('ht'). ...
feature('hf2').set('HeatFluxType', 'ConvectiveHeatFlux');
model.component('comp1').physics('ht').feature('hf2').set('h', 100);
Skip the next section and continue the model from the Output section below.
Flux boundary conditions are set up at the left side (1) and top (3) of the rectangle.
model.component('comp1').physics('hteq').create('flux1', ...
'FluxBoundary', 1);
model.component('comp1').physics('hteq').feature('flux1').selection.set(1);
model.component('comp1').physics('hteq').feature('flux1').set('g', 'Qin');
model.component('comp1').physics('hteq').create('flux2', ...
'FluxBoundary', 1);
model.component('comp1').physics('hteq').feature('flux2').selection.set(3);
model.component('comp1').physics('hteq').feature('flux2').set('g', ...
'100*(293.15-u)');
Training Study
For heat transfer problems, it is necessary to manually add a training study, which must
be an eigenvalue study. The solver it set up such that it finds 5 eigenvalues.
model.study.create('std2');
model.study('std2').create('eigv', 'Eigenvalue');
model.study('std2').feature('eigv').activate('ht', true);
model.study('std2').feature('eigv').set('neigsactive', true);
model.study('std2').feature('eigv').set('neigs', 5);
Now the reduced-order system can be simulated using the function ode23s.
u = 10000;
func = @(t,x) MR.MA*x + MR.MB*u
tspan = 0:1000;
opt = odeset('mass', MR.Mc);
[t,x] = ode23s(func, tspan, zeros(size(MR.MA,1),1), opt);
yt = MR.C*x'; % deviation variables
303
302
Temperature (K), Boundary Probe 1 avh1
301
300
299
298
297
296
295
294
293
0 100 200 300 400 500 600 700 800 900 1000
Time (s)
As an alternative to using ode23s, you can use functions in the Control System
Toolbox, which is an add-on to MATLAB. The matrices stored in MR can be used to
manually construct a state-space system using the function ss, or you can call
mphreduction using the return option to specify that mphreduction should do the
conversion.
sys = mphreduction(model, ...
'out', {'MA' 'MB' 'A' 'B' 'C' 'D' 'Mc' 'x0' 'Y0' 'Kr'}, ...
'controls', {'Qin'}, ...
'controlvals', [10000], ...
'output', 'comp1.bnd1', ...
'unreducedstudy', 'std1', ...
'trainingstudy', 'std2', ...
'return', 'ss')
The system can, for example, be simulated using the step function.
opt = stepDataOptions('StepAmplitude', 10000);
figure(2)
step(sys, 1:1000, opt)
std1 = model.study.create('std1');
std1.create('time', 'Transient');
std1.feature('time').set('tlist', 'range(0,1,1000)');
sol1 = model.sol.create('sol1');
sol1.createAutoSequence('std1');
sol1.feature('t1').set('tstepsbdf', 'intermediate');
sol1.runAll;
mphplot(model, 'pg1'); hold on
std2 = model.study.create('std2');
std2.create('eigv', 'Eigenvalue');
std2.feature('eigv').activate('ht', true);
std2.feature('eigv').set('neigsactive', true);
std2.feature('eigv').set('neigs', 5);
MR = mphreduction(model, ...
'out', {'MA' 'MB' 'A' 'B' 'C' 'D' 'Mc' 'x0'}, ...
'controls', {'Qin'}, ...
'controlvals', [10000], ...
'output', 'comp1.bnd1', ...
'unreducedstudy', 'std1', ...
'trainingstudy', 'std2')
u = 10000;
func = @(t,x) MR.MA*x + MR.MB*u
tspan = 0:1000;
opt = odeset('mass', MR.Mc);
[t,x] = ode23s(func, tspan, zeros(size(MR.MA,1),1), opt);
yt = MR.C*x'; % deviation variables
y0 = MR.C*MR.x0; % initial output value
y = yt+y0;
plot(t, y, 'r')
info = mphsolinfo(model)
This section includes information about Specifying the Solution Object and the
Output Format.
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:
FIELDS DESCRIPTION
To get the information about the number of solutions, set the property nu to on:
FIELDS DESCRIPTION
The parameters used in a study can be group in two distinct solution number types:
• The inner solution, containing the solution computed with parameters such as
eigenvalues, time steps, or continuation parameter combinations.
• The outer solution, containing the solution computed with parameters defined in
parametric sweep.
To get information about all solution object and solution data set combinations in the
model enter the command:
info = mphsolutioninfo(model)
FIELDS DESCRIPTION
FIELDS DESCRIPTION
dataset List of the tags of the data set associated to the solution
study Tag of the study that computed the solution
sequencetype Type of solution node
cellmap Connections between parameters and inner/outer solution
numbers; the field is not available by default.
values Values of the parameters used in the solution
parameters Names of the parameters used in the solution
info = mphsolutioninfo(model,'parameters',{'e1','v1','tol1'})
The property parameters can also be set as a 1xN cell array where N corresponds to the
number of parameters to specify.
This section includes information about Specifying the Solution Object and the
Output Format. It also includes the section, Retrieving Solution Information.
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:
OUTPUT FORMAT
To include the cellmap field in the info.sol# substructure set the property cellmap
to on:
Improve the visibility of the map table by sorting the row using either the column
number or the name in the map header:
model = mphopen('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 data set 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:
To get the list of the solutions that contain the given parameters enter:
solnum = info.solutions
U = mphgetu(model)
where U is an Nx1 double array, where N is the number of degrees of freedom of the
COMSOL Multiphysics model.
You can refer to the function mphxmeshinfo to receive the DOF name or
the node coordinates in the solution vector, see Retrieving Xmesh
Information.
For solver settings that compute for several inner solutions, select the inner solution to
use with the solnum property:
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
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 vectors—the 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:
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
vector Udot by adding a second output variable:
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
In this section:
info = mphxmeshinfo(model)
where info is a MATLAB structure that contains the fields in the table:
FIELDS DESCRIPTION
FIELDS DESCRIPTION
FIELDS DESCRIPTION
coords Global coordinates for all nodes. The nth column contains the
coordinates of node point number n
dofnames DOF names in this geometry
dofs 0-based DOF numbers for all nodes in this geometry.
dofs()[k][n] is the DOF number for DOF name
dofNames()[k] at node point n. A value of -1 means that there
is no DOF with this name at the node. Note: If there is a slit, only
one of the DOFs is given for each node point
FIELDS DESCRIPTION
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
nodes 0-based node point indices for all mesh elements of type type.
A value -1 means that there is no node point at this location
dofs 0-based DOF numbers for all mesh elements of type type. A
value -1 means that there is no DOF at this location
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:
In case several mesh cases have been used by a specific solver, for example, with an
automatic remeshing procedure, you can specify which mesh case to use to get the
discretization information:
where <meshcase> is the mesh case number or the tag of the mesh case.
In this section:
An alternative approach is to call the function mphnavigator that displays the model
object information in a MATLAB® GUI. To run the function at the MATLAB prompt
enter the command:
mphnavigator
If you have installed the COMSOL apps in the MATLAB Apps ribbon, click the
COMSOL Model Navigator icon ( ).
If the COMSOL model objected is not stored in the MATLAB variable model enter
the command:
mphnavigator(<modelvar>)
where <modelvar> is the variable name in MATLAB that contains the model.
If a new model object is created with the same MATLAB object name,
restart mphnavigator in order to have the updated model information.
• The File menu, where the current model object can be saved in the MPH-format, a
new model object can be opened, and the mphnavigator window can be closed.
• The Tools menu lists the navigation tools available for the model object. Search is a
shortcut to the command mphsearch that starts a GUI to search expressions or tags
in the model object (see Finding Model Expressions). Solutions starts a GUI to
display the solution object available in the COMSOL Multiphysics model object.
Show Errors lists the error or warning nodes available in the model object (see
Handling Errors and Warnings).
• 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.
These buttons are unavailable if no method has been selected in the Model Tree section.
• The Open plot window button ( ) generate the plot in COMSOL of the selected
node and transfer the image in a MATLAB figure. This supports other plot than
geometry, mesh or plot group such as functions.
• The Plot button ( ) displays the geometry, the mesh, or a plot group in a
MATLAB figure.
• The Help button ( ) shows context sensitive help for the currently selected node
in the model tree.
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.
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 and the Value sections list the properties of a selected feature node and
the associated values respectively. The Allowed Value section list the allowed value for
the corresponding property.
Not all feature node returns a list of allowed value for the properties.
Click Copy set to copy to the clipboard the command that sets the selected property to
its current value.
Click Copy get to copy to the clipboard the command to get the value of the currently
selected property.
Click Copy Table to copy the entire properties table to the clipboard, then paste into a
text or spreadsheet editor.
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 that is easy and fast to evaluate.
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. Click Copy call to
copy the method syntax associated to the selected feature node, the syntax is ready to
use at the MATLAB prompt.
To get the list of the main feature nodes and the tags of the model object model, enter
the command:
mphmodel(model)
To list the subfeature of the node type model.feature enter the command:
mphmodel(model.feature)
mphmodel(model.feature(<ftag>))
Use the flag -struct to return the model object information to MATLAB structure:
str is a MATLAB structure and the fields consist of each feature node associated to the
root node.
The function mphsearch starts a MATLAB® GUI that displays the list of all the
expressions, constants, solution variables, or parameters available in the model object.
To run the function type at the MATLAB prompt:
mphsearch
If you have installed the COMSOL apps in the MATLAB Apps ribbon, click the
COMSOL Search icon ( ).
Using the COMSOL Model Search apps( ) only model object with
name model are supported.
If the COMSOL model objected is linked with a MATLAB object with a different
name than model, enter the command:
mphsearch(modelname)
The Search section has a search tool to filter the list. Enter any string in the text field
and select where to search the string—in the name, the expression, or the description
of the table entry. You can also select the type you want to list. The expression type can
be Equation, Field, Function, Geom, Mesh, Tag, VarNames, or Weak. You can select
Starts with to search for any expression that start with the string enter in the text field.
• Click Go to display the result of the search. Click Clear to clear the search settings.
• Click Model info to get the model description in a separate window.
• Click Copy to copy any entry of the table to the clipboard.
• Click Close to close the mphsearch window.
The evaluation does not require an existing solution data set in the model, which
means you can evaluate the expression even if there is no solution computed in the
model.
The output str is an array of structs with the same size as for the cell array of
expressions. For multiple parameters evaluation only a single output is permitted. The
struct contains the following fields: name, the parameter name; value, its value in the
unit specified in the field unit; def, the string for the definition of the parameter; and
descr the string description of the parameter.
str = mphevaluate(model)
The output str is an array of structs with the same size as for the parameters table.
Get the full information of a model parameter expression with the command:
where value, unit, def and descr are the parameter value, the parameter unit, the
parameter definition and the parameter description respectively.
You can specify the unit of the expression to evaluate with the command:
To evaluate and return only the value of the expression use the command:
To evaluate and return only the unit of the expression use the command:
To evaluate and return the definition string of the expression use the command:
The above command can be used to set a new parameter using an existing one.
str = mphgetproperties(model.<feature>)
where str is a MATLAB structure that lists all the properties and the value of the
feature node <feature>.
Some model node provides also a list of allowed value for their properties, to get such
a list enter the command:
this also returns the MATLAB structure allowed containing the list of the allowed
values for the properties of the feature node <feature>.
expr = mphgetexpressions(<node>)
where <node> is the node to get the expressions from. Nodes that can be used are
model.param, model.variable(<tag>), and model.result.param.
expr is an Nx3 cell array where N is the number of expressions for this node.
str = mphgetselection(model.selection(<seltag>))
where <seltag> is the tag a selection node defined in the model object. The output
®
str is a MATLAB structure with the following fields:
For both errors and warnings a message is stored in a separate node located just below
the problematic model feature node.
In case of errors, a Java® Exception is thrown to MATLAB®, which also breaks the
execution of the script.
In a loop, for example, use the try and catch statements to continue to the next
iteration. For automatic geometry or mesh generation you can use it to set the model
properties with alternative values that circumvent the problem.
mphshowerrors(model)
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, str{i,2} contains the message of the ith error/warning
message, str{i,3} contains a cell arrays of the model tree nodes that contain the error
information. This last information make it easier to extract error information for
automated processing of error and warning conditions.
• Allocating Memory
• Disabling Model Feature Update
• Disabling The Model History
Allocating Memory
COMSOL Multiphysics stores the data in Java®. If you are experiencing memory
problems during meshing, postprocessing operations, or when exchanging data
between the COMSOL server and MATLAB®, this can mean that the Java heap size
is set with too low a value.
Increasing the memory allocated for the Java process necessarily decreases
the memory available for the solver.
Either set The COMSOL Multiphysics Server Java Heap Size or Setting Manually the
Memory in MATLAB.
Edit the file with a text editor, the Java heap settings are defined as in the following
lines:
The values are given in Mb, modify these value to satisfy the model requirements.
-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.
For models that contain a large amount of physics feature nodes this update operation
can take some time. For small models this is not an issue, but for larger models the
checks can be time consuming. It can help to deactivate the model feature update.
model.disableUpdates(true)
You have to enable the feature update again prior to computing the solution in order
to make sure that COMSOL works on an updated model definition. Enabling the
model.disableUpdates(false)
model.hist.disable
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.
model.hist.enable
The figure below illustrates a GUI made in MATLAB and linked to a COMSOL model
object.
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.
This section introduces you to the MATLAB® function callback from the
COMSOL Desktop® and COMSOL Multiphysics® model object.
In this chapter:
237
Running External Function
When running the model containing a MATLAB function feature node, COMSOL
Multiphysics automatically starts a MATLAB process that evaluates the function and
returns the value to the COMSOL model.
In the COMSOL Desktop go to the Preferences and select Security, in the General
section select Allow external MATLAB© functions. Then click OK.
Applications that use external MATLAB function are not supported using
the COMSOL Client. It is only possible to use such applications using a
browser.
• Parameters
• Geometry settings
• Mesh settings
• Material properties
• Physics settings (domain conditions, boundary conditions, etc.)
Material properties and physics settings are evaluated while the model is solved
whereas the features can be used while the model is constructed.
• Functions, where you declare the name of the MATLAB functions and their
arguments.
• Derivatives, where you define the derivative of the MATLAB functions with respect
to all function arguments.
• Plot Parameters, where you can define the limit of the arguments value in order to
display the function in the COMSOL Desktop Graphics window.
Under Functions, you 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.
• It can take any number of inputs as vectors and must return a single output vector.
• The input vectors can be of arbitrary size, but in a single call the inputs vectors will
all have the same length. The returned vector must have exactly the same length as
the input vectors.
For example, functions such as + and - (plus and minus) work well on vector inputs,
but matrix multiplication (*, mtimes) and matrix power (^, mpower) do not. Instead,
use the elementwise array operators .* and .^. See also Function Input/Output
Considerations.
input = (1:10)'
size(input)
out = besselj(input, input)
size(out)
Here there are no errors, and the size of the input and output is the same.
input = (1:10)'
size(input)
out = corrcoef(input, input)
size(out)
There are no errors when calling corrcoef using vector inputs, but the result does not
have the same size as the input and hence a call to corrcoef in this way will not work.
Click the Create Plot button ( ) to create a plot group under the Results node.
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.
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.
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:
To proceed you have these options to set the directory path in MATLAB:
model.func.create(<ftag>, 'MATLAB')
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.
When you write your own functions, remember that the input arguments
are vectors. The output must have the same size as the input. All
arguments and results must be double-precision vectors real or complex
valued.
Consider the following example function where the coefficient c depends on the x
coordinate:
function c = func1(x)
if x > 0.6
c = x/1.6;
else
c = x^2+0.3;
end
• 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.
Expand the Derivatives section to define the derivatives of the function with respect to
the function arguments. In the table define the derivative for each function argument.
In the Function column enter the function name, in the Argument column enter the
The section, Example: Define the Hankel Function, defined the function derivative by
entering the following settings in the table:
besselh nu (besselh(nu-1,x)-besselh(nu+1,x))/2
besselh x (besselh(0,x)-besselh(2,x))/2
Command Reference
The main reference for the syntax of the commands available with LiveLink™ for
MATLAB® is the COMSOL Multiphysics Programming Reference Manual. This
section documents additional interface functions that come with the product.
In this chapter:
• Summary of Commands
• Commands Grouped by Function
249
Summary of Commands
colortable mphmeshstats
mphapplicationlibraries mphmin
mphcd mphmodel
mphdoc mphnavigator
mpheval mphopen
mphevalglobalmatrix mphparticle
mphevalpoint mphplot
mphevalpointmatrix mphquad2tri
mphevaluate mphray
mphgeom mphreadstl
mphgetadj mphreduction
mphgetcoords mphsave
mphgetexpressions mphsearch
mphgetproperties mphselectbox
mphgetselection mphselectcoords
mphgetu mphshowerrors
mphglobal mphsolinfo
mphimage2geom mphsolutioninfo
mphinputmatrix mphstart
mphint2 mphstate
mphinterp mphsurf
mphinterpolationfile mphtable
mphlaunch mphtags
mphload mphthumbnail
mphmatrix mphversion
mphmax mphviewselection
mphmean mphwritestl
mphmesh mphxmeshinfo
FUNCTION PURPOSE
GEOMETRY FUNCTIONS
FUNCTION PURPOSE
MESH FUNCTIONS
FUNCTION PURPOSE
UTILITY FUNCTIONS
FUNCTION PURPOSE
FUNCTION PURPOSE
FUNCTION PURPOSE
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:
AuroraAustralis - A color table that spans from white through green and indigo to
blue as for the colors in the aurora australis (southern light).
AuroraBorealis - This color table resembles the colors in the aurora borealis
(northern light). The color table spans from white through green and indigo to blue
but with a larger indigo portion.
Cividis - Uses yellow and blue colors in a color table that is suited for normal vision,
a deuteranomaly, or red-green colorblindness.
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.
Grayscale - A color table that uses no color, only the gray scale varying linearly from
black to white.
Grayprint - Varies linearly from dark gray (0.95, 0.95, 0.95) to light gray (0.05, 0.05,
0.05). This color table overcomes two disadvantages that the GrayScale color table
has when used for printouts on paper—it gives the impression of being dominated by
dark colors and that white cannot be distinguished from the background.
HeatCamera - The colors range from black through blue, magenta, red, and yellow to
white, corresponding to the colors in an image from a heat camera.
JupiterAuroraBorealis - the color table spans from black through blue to white as
for the Jupiter’s aurora.
Thermal - Ranges from black through red and yellow to white, which corresponds to
the colors iron takes as it heats up.
Thermalequidistant - Similar to Thermal but uses equal distances from black to red,
yellow, and white, which means that the black and red regions become larger.
Twilight - The color table uses colors associated with twilight (the illumination of the
Earth’s lower atmosphere when the Sun is not directly visible), spanning colors from
pink through white to blue.
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.
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.
EXAMPLE
Create a rainbow color map
map = colortable('Rainbow');
map = rainbow;
mphapplicationlibraries
Graphical user interface (GUI) for viewing the Application Libraries.
SYNTAX
mphapplicationlibraries
mphcd
Change directory to the directory of the model.
SYNTAX
mphcd(model)
DESCRIPTION
®
mphcd(model) changes the current directory in MATLAB to the directory where the
model was last saved.
mphdoc
Open help window for a certain topic.
SYNTAX
mphdoc
mphdoc(node)
mphdoc(node,fname)
mphdoc api
DESCRIPTION
mphdoc opens the COMSOL documentation Help Desk.
mphdoc(node,fname) opens the help window for the entry on node with the feature
fname.
mphdoc api opens a window with the JavaDoc help for the COMSOL API.
EXAMPLE
Create a model a model object:
model = ModelUtil.create('Model');
mphdoc(model.mesh)
mphdoc(model.geom,'Rectangle')
SEE ALSO
mphapplicationlibraries
mpheval
Evaluate expressions on node points.
SYNTAX
pd = mpheval(model,{e1,...,en},...)
The output value pd is a structure with fields expr, p, t, ve, unit and fields for data
values.
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).
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 the temperature at node points:
model = mphopen('model_tutorial_llmatlab');
std = model.study.create('std');
std.feature.create('stat','Stationary');
std.run;
dat = mpheval(model,'T');
Evaluate both the total heat flux magnitude and the temperature:
data = mpheval(model,'T','dataonly','on');
data = mpheval(model,'T','selection',2);
data = mpheval(model,'T','selection',7,'edim','boundary');
data = mpheval(model,'T','refine',2);
data = mpheval(model,'T','pattern','gauss');
Evaluate the temperature at every time step computed with power set to 30:
model = mphopen('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');
data = mpheval(model,'T','dataset','dset2','solnum',5);
data = mpheval(model,'T','dataset','dset2','t',[10.5,15.2]);
Evaluate the temperature at every time step computed with power set to 90:
data = mpheval(model,'T','dataset','dset2','outersolnum',3);
SEE ALSO
mphevalglobalmatrix, mphevalpoint, mphevalpointmatrix, mphglobal,
mphint2, mphinterp, mphparticle, mphray
mphevalglobalmatrix
Evaluate global matrix variables.
SYNTAX
M = mphevalglobalmatrix(model,expr,...)
EXAMPLE
Load lossy_circulator_3d.mph from the RF Module’s Applications Libraries:
model = mphopen('lossy_circulator_3d.mph');
Evaluate the S-parameters matrix using the solution data set dset4:
SEE ALSO
mpheval, mphevalpoint, mphevalpointmatrix, mphglobal, mphint2, mphinterp,
mphparticle, mphray
mphevalpoint
Evaluate expressions at geometry vertices.
SYNTAX
[v1,...,vn] = mphevalpoint(model,{e1,...,en},...)
[v1,...,vn,unit] = mphevalpoint(model,{e1,...,en},...)
DESCRIPTION
[v1,...,vn] = mphevalpoint(model,{e1,...,en},...) returns the results from
evaluating the expressions e1,...,en at the geometry vertices. The values v1,...,vn
can either be a cell array or a matrix depending on the options.
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.
model = mphopen('model_tutorial_llmatlab');
std = model.study.create('std');
std.feature.create('stat','Stationary'); std.run;
T = mphevalpoint(model,'T');
T = mphevalpoint(model,'T','selection',5);
Evaluate the temperature and the magnitude of the total heat flux on point 5:
Evaluate the temperature at every time step computed with power set to 30:
model = mphopen('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');
T = mphevalpoint(model,'T','selection',5,'dataset','dset2',...
'solnum',7);
T = mphevalpoint(model,'T','selection',5,'dataset','dset2',...
't',10.5);
T = mphevalpoint(model,'T','selection',5,'dataset','dset2',...
'outersolnum',3)
T_avg = mphevalpoint(model,'T','selection',5,...
'dataset','dset2','dataseries','average');
mphevalpointmatrix
Evaluate matrix quantities at points in the geometry.
SYNTAX
M = mphevalpointmatrix(model, expr, ...)
DESCRIPTION
M = mphevalpointmatrix(model, expr, ...) evaluates the point matrix of the
variable expr and returns the full matrix M.
SEE ALSO
mpheval, mphevalglobalmatrix, mphevalpoint, mphglobal, mphint2,
mphinterp, mphparticle, mphray
SYNTAX
mphevaluate(model,expr)
str = mphevaluate(model)
[value,unit,def,descr] = mphevaluate(model,expr,...)
[value,...] = mphevaluate(model,expr,unit)
[value,...] = mphevaluate(model,expr,asvalue)
DESCRIPTION
mphevaluate(model,expr) evaluates the expression expr defined in the Parameters
node.
The evaluation does not require an existing solution data set in the model.
EXAMPLE
Evaluate the parameter power defined in the model:
model = mphopen('model_tutorial_llmatlab');
[Temp,unit,def] = mphevaluate(model,'Temp','degC');
Temp = mphevaluate(model,'Temp+20[degC]','degF');
SEE ALSO
mpheval, mphglobal, mphinterp, mphparticle, mphray
mphgeom
Plot a geometry in a MATLAB® figure.
SYNTAX
mphgeom(model)
mphgeom(model,geomtag,...)
DESCRIPTION
mphgeom(model) plots the model geometry in a MATLAB figure.
EXAMPLE
Plot the model geometry:
model = mphopen('model_tutorial_llmatlab.mph');
mphgeom(model)
mphgeom(model,'geom1','facelabels','on','facelabelscolor','r');
mphgeom(model,'geom1','entity','boundary',...
'selection',[7:9,11]);
figure(2);
mphgeom(model, 'geom1','parent', gca);
SEE ALSO
mphmesh, mphviewselection
mphgetadj
Return geometry entity indices that are adjacent to each other.
SYNTAX
n = mphgetadj(model,geomtag,returntype,adjtype,adjnumber)
DESCRIPTION
n = mphgetadj(model,geomtag,returntype,adjtype,adjnumber) returns the
indices of the adjacent geometry entities.
returntype is the type of the geometry entities whose index are returned.
The entity type can be one of 'point', 'edge', 'boundary' or 'domain' following
the entity space dimension defined below:
EXAMPLE
Return the indices of the boundaries adjacent to point 2:
model = mphopen('model_tutorial_llmatlab');
SEE ALSO
mphgetcoords, mphselectbox, mphselectcoords
mphgetcoords
Return point coordinates of geometry entities.
SYNTAX
c = mphgetcoords(model,geomtag,entitytype,entitynumber)
DESCRIPTION
c = mphgetcoords(model,geomtag,entitytype,entitynumber) returns the
coordinates of the points that belong to the entity object with the type entitytype
and the index entitynumber.
EXAMPLE
Return the coordinates of points that belong to domain 2:
model = mphopen('model_tutorial_llmatlab');
SEE ALSO
mphgetadj, mphselectbox, mphselectcoords
SYNTAX
expr = mphgetexpressions(modelnode)
DESCRIPTION
expr = mphgetexpressions(modelnode) returns expressions from the node
modelnode as a cell array. expr contains the list of the variable names, the variable
expressions and the variable descriptions.
EXAMPLE
Get the expressions defined in the parameters node
model = mphopen('model_tutorial_llmatlab');
expr = mphgetexpressions(model.param)
SEE ALSO
mphgetproperties, mphgetselection, mphmodel, mphnavigator, mphsearch
mphgetproperties
Get the properties from a model node.
SYNTAX
str = mphgetproperties(modelnode)
[str,allowed] = mphgetproperties(modelnode)
DESCRIPTION
str = mphgetproperties(modelnode) returns the structure str containing the
properties that are defined for the node modelnode.
EXAMPLE
Build the mesh in the model model_tutorial_llmatlab.mph and get the mesh size
properties and their allowed values:
model = mphopen('model_tutorial_llmatlab');
SEE ALSO
mphgetexpressions, mphgetselection, mphmodel, mphnavigator, mphsearch
mphgetselection
Get information about a selection node.
SYNTAX
info = mphgetselection(selnode)
DESCRIPTION
info = mphgetselection(selnode) returns the selection data of the selection node
selnode.
The output info is a MATLAB® structure defined with the following fields:
EXAMPLE
Add a selection node to the model busbar.mph and retrieve its information:
model = mphopen('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
mphgetexpressions, mphgetproperties, mphmodel, mphnavigator, mphsearch
mphgetu
Return a solution vector.
DESCRIPTION
U = mphgetu(model) returns the solution vector U for the default solution data set.
For a time-dependent and parametric analysis type, the last solution is returned by
default. For an eigenvalue analysis type the first solution number is returned by default.
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
Extract the solution vector:
model = mphopen('model_tutorial_llmatlab');
std = model.study.create('std');
std.feature.create('stat','Stationary');
std.run;
U = mphgetu(model);
Extract the solution vectors for the first and the last time step:
model = mphopen('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]);
U = mphgetu(model,'soltag','sol3');
SEE ALSO
mphsolinfo
mphglobal
Evaluate global quantities.
SYNTAX
[d1,...,dn] = mphglobal(model,{e1,...,en},...)
[d1,...,dn,unit] = mphglobal(model,{e1,...,en},...)
DESCRIPTION
[d1,...,dn] = mphglobal(model,{e1,...,en},...) returns the results from
evaluating the global quantities specified in the string expression e1,..., en.
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 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.
EXAMPLE
Evaluate the maximum temperature in the model
model = mphopen('model_tutorial_llmatlab');
model.cpl.create('maxop','Maximum','geom1').selection.all;
std = model.study.create('std');
std.feature.create('stat','Stationary');
std.run;
maxT = mphglobal(model,'maxop(T)')
maxT = mphglobal(model,'maxop(T)','unit','degC')
Evaluate a global expression at every time step computed with power set to 30:
model = mphopen('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);
std.run;
maxT = mphglobal(model,'maxop(T)','dataset','dset2');
maxT = mphglobal(model,'maxop(T)',dataset','dset2',...
'solnum',[1,5]);
maxT = mphglobal(model,'maxop(T)',dataset','dset2',...
't',20.512);
Evaluate maxop(T) at every time step computed with power set to 90:
maxT = mphglobal(model,'maxop(T)','dataset','dset2',...
'outersolnum',3);
SEE ALSO
mpheval, mphevalglobalmatrix, mphevalpoint, mphevalpointmatrix, mphint2,
mphinterp
SYNTAX
model = mphimage2geom(imagedata,level,...)
DESCRIPTION
model = mphimage2geom(imagedata,level,...) converts the image contained in
imagedata into a geometry which is returned in the model object model.
The contour of the image is defined by the value level. imagedata must be a 2D
matrix.
To add the geometry created with mphimage2geom, specify the geometry node with
property Geom.
EXAMPLE
Create a set of point coordinates:
p = (peaks+7)*5;
Create a geometry object following the contour made with point of value 50:
Create the same geometry object with a scale factor of 1e-3 and add it into an existing
3D model:
model = mphopen('model_tutorial_llmatlab');
wp1 = model.component('comp1').geom('geom1').feature.create('wp1',
'WorkPlane');
wp1.set('quickz', 1e-2);
mphimage2geom(p, 50,'scale',1e-3,wp1.geom);
mphgeom(model)
Create a geometry using MRI data. The geometry object is created following the
contour made with point of value 30 and disregard objects with an area (in pixel) lower
than 2:
mri = load('mri');
im = mri.D(:,:,1,1);
figure(1); image(im);
mphimage2geom(im, 30,'minarea',2);
mphinputmatrix
Add a matrix system for linear solvers.
SYNTAX
mphinputmatrix(model,str,soltag,soltypetag)
soltypetag can only be one of the following solver type: Stationary, Eigenvalue,
Time.
K Stiffness matrix
L Load vector
M Constraint vector
N Constraint Jacobian
A valid structure for a time-dependent/ eigenvalue solver includes the following fields:
TABLE 6-10: PROPERTY/VALUE PAIRS FOR THE MPHINT2 COMMAND.
K Stiffness matrix
L Load vector
M Constraint vector
N Constraint Jacobian
D Damping matrix
E 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.
Note: The system matrices are not stored in the model when it is saved as an
MPH-file or loaded into the COMSOL Desktop.
EXAMPLE
Create a model with a square geometry
Set-up the study and the solver configuration for a stationary problem:
std = model.study.create('std1');
std.create('stat', 'Stationary');
sol = model.sol.create('sol1');
sol.study('std1');
sol.feature.create('st1', 'StudyStep').set('studystep', 'stat');
sol.feature.create('v1', 'Variables');
sol.feature.create('s1', 'Stationary');
str = mphmatrix(model,'sol1','out',{'K','L','M','N'},...
'initmethod','sol','initsol','zero');
str.K = str.K*0.5;
mphinputmatrix(model,str,'sol1','s1')
model.sol('sol1').runAll;
SEE ALSO
mphmatrix, mphxmeshinfo
SYNTAX
[v1,...,v2] = mphint2(model,{e1,...,en},edim,...)
[v1,...,v2,unit] = mphint2(model,{e1,...,en},edim,...)
DESCRIPTION
[v1,...,vn] = mphint2(model,{e1,...,en},...) evaluates the integrals 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, as a string: line,
surface, volume or as an integer value.
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.
Outersolnum is used to select the outer solution number when a parametric sweep
has been used in the study step node.
EXAMPLE
Integrate the normal heat flux across all boundaries:
model = mphopen('model_tutorial_llmatlab');
SEE ALSO
mpheval, mphevalglobalmatrix, mphevalpoint, mphevalpointmatrix, mphint2,
mphinterp, mphparticle, mphray
mphinterp
Evaluate expressions in arbitrary points or data sets.
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 at the coordinates specified in the double matrix coord.
Evaluation is supported only on Solution Data Sets.
[v1,...,vn] = mphinterp(model,{e1,...,en},'dataset',dsettag,...)
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.
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.
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).
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 available
as eigenvalues for eigenvalue problems and as parameter values for parametric
problems, respectively.
The property solnum is used to select the solution number when a parametric,
eigenvalue or time-dependent solver has been used.
The property outersolnum is used to select the outer solution number when a
parametric sweep has been used in the study step node.
EXAMPLE
Evaluate the temperature at given coordinates:
model = mphopen('model_tutorial_llmatlab');
std = model.study.create('std');
std.feature.create('stat','Stationary');
std.run;
coord = [0,0,1e-2;0,0,1e-2;0,1e-2,1e-2];
T = mphinterp(model,'T','coord',coord);
[T,tfluxMag] = mphinterp(model,{'T','ht.tfluxMag'},...
'coord',coord);
Evaluate the temperature and evaluation point global coordinates on boundary 7 using
local coordinates:
Modify the extrapolation distance for point coordinates outside of the geometry:
coord = [5e-2;5e-2;1.1e-2];
T = mphinterp(model,'T','coord',coord)
Extract data using a cut line data set. First create the cutline data set, then evaluate the
temperature field along the line:
model = mphopen('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;
Evaluate the temperature at every time step computed with power set to 30:
T = mphinterp(model,'T','coord',coord,'dataset','dset2',...
'solnum',5);
T = mphinterp(model,'T','coord',coord,'dataset','dset2',...
't',10.5);
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
mpheval, mphevalglobalmatrix, mphevalpoint, mphevalpointmatrix, mphint2,
mphint2, mphparticle, mphray
mphinterpolationfile
Save data in files readable by the Interpolation feature.
DESCRIPTION
mphinterpolationfile(filename,type,data) saves the NxM matrix data into
the text file filename with the format type. The interpolation coordinates are vectors
with values from 1 to N and 1 to M.
EXAMPLE
Create random 10x10 interpolation data to file using grid format:
data = cumsum(0.1*randn(size(10)));
mphinterpolationfile('datagrid.txt','grid',data);
t = 0:0.05:2*pi;
z = sin(cos(t)*4)+sin(51*t)*0.05;
mphinterpolationfile('dataspread.txt','spreadsheet',z,t);
SEE ALSO
mphquad2tri, mphreadstl, mphsurf, mphwritestl
mphlaunch
Launch COMSOL Desktop, connect it to the running server and import an
application.
DESCRIPTION
mphlaunch launches a COMSOL Multiphysics Client and connect it to the same
server as MATLAB® is connected to. Then it imports the model on the server into the
COMSOL Multiphysics Client.
mphlaunch(model) does the same as above, but uses the model argument to select
which model is imported.
mphlaunch ModelTag uses the model with the tag 'ModelTag' in the server to be
imported. This can also be done using the syntax: mphlaunch('ModelTag')
mphlaunch(..., tms) uses the timeout tms (in milliseconds) to force MATLAB to
wait until the COMSOL server is free again. The default timeout value is 500. A
negative value results in no timeout.
EXAMPLE
Load the file model_tutorial_llmatlab.mph:
model = mphopen('model_tutorial_llmatlab');
Launch a COMSOL Multiphysics Client, connect it with the running server, import
the model defined as model:, and set a timeout of 1s.:
mphlaunch(model,1000);
mphload
Load a COMSOL Multiphysics model MPH-file.
SYNTAX
model = mphload(filename)
model = mphload(filename, mtag)
model = mphload(filename, mtag, '-history')
model = mphload(filename, mtag, pwd)
[model, filename] = mphload(filename, ...)
DESCRIPTION
model = mphload(filename) loads a COMSOL model object saved with the name
filename and assigns the default tag Model in the COMSOL server. If a model with
model = mphload(filename, mtag, pwd) loads the COMSOL model object saved
with the name filename protected with the password pwd.
The model tag mtag and the password pwd are defined as string.
If the model tag 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.
mphload does not look for lock file when opening a model in the COMSOL server.
EXAMPLE
Load the file model_tutorial_llmatlab.mph:
model = mphload('model_tutorial_llmatlab');
Load the file model_tutorial_llmatlab.mph and set the model name in the
COMSOL server to Model2:
model = mphload('model_tutorial_llmatlab','Model2');
SEE ALSO
mphopen, mphsave
SYNTAX
str = mphmatrix(model,soltag,'Out',...)
DESCRIPTION
str = mphmatrix(model,soltag,'Out',{'A'},...) returns a MATLAB®
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.
The load vector is assembled using the current solution available as linearization point
unless the initmethod property is provided. In case of the presence of a solver step
node in the solver sequence, the load vector correspond then to the residual of the
problem.
The function mphmatrix does not solve the problem as the assembly is performed
before the solver node in the solution sequence. You can specify the solution feature
node after which to assemble the system matrices with the property extractafter.
This is useful if you need to compute the solution before extracting the matrices or if
you have a solution sequence using different solver sequences and you want to extract
the matrices for a specific one.
The Advanced section in the COMSOL Multiphysics Reference Manual, describes the
functionality corresponding to the properties complexfun, nullfun, and rowscale.
EXAMPLE
Evaluate the system matrices of a stationary problem
model = mphopen('model_tutorial_llmatlab');
std = model.study.create('std1');
std.feature.create('stat', 'Stationary');
std.run;
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 Jacobian and compute the
total load applied in the matrix system:
subplot(2,1,1); spy(str.K);subplot(2,1,2);spy(str.N)
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:
Evaluate the eliminated load vector using the current solution as linearization point:
str = mphmatrix(model,'sol1','out',{'Lc'},'initmethod','sol');
model = mphopen('model_tutorial_llmatlab');
std = model.study.create('std1');
time = std.feature.create('time', 'Transient');
time.set('tlist', 'range(0,1,25)');
std.run;
str = mphmatrix(model,'sol1','out',{'E','D','K','L','M','N'});
str = mphmatrix(model,'sol1','out',{'Ec','Dc','Kc','Lc','M','N'});
str = mphmatrix(model,'sol1','out',{'K'},...
'initmethod','sol','initsol','sol1','solnum',15);
str = mphmatrix(model,'sol1','out',{'K'},...
'initmethod','sol','initsol','zero');
SEE ALSO
mphstate, mphxmeshinfo, mphinputmatrix
mphmax
Perform a maximum of expressions.
SYNTAX
[v1,...,vn] = mphmax(model,{e1,...,en},edim,...)
[v1,...,vn,unit] = mphmax(model,{e1,...,en},edim,...)
DESCRIPTION
[v1,...,vn] = mphmax(model,{e1,...,en},edim,...) evaluates the maximum
of the string expressions e1,...,en and returns the result in N matrices v1,...,vn
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 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.
The property outersolnum is used to select the outer solution number when a
parametric sweep has been used in the study step node.
If the matrix property is set to off the output is cell arrays of length P containing cell
arrays of length M.
EXAMPLE
Evaluate the maximum temperature in the model domain:
model = mphopen('model_tutorial_llmatlab');
std = model.study.create('std');
std.feature.create('stat','Stationary');
std.run;
maxT = mphmax(model,'T','volume');
maxT = mphmax(model,'T','surface','selection',9);
model = mphopen('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;
Evaluate the maximum of the temperature at every time step computed with power set
to 30:
maxT = mphmax(model,'T','volume','dataset','dset2');
maxT = mphmax(model,'T','volume','dataset','dset2',...
'solnum',5);
Evaluate the maximum of the temperature at 10.5 sec and 15.2 sec:
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:
SEE ALSO
mphmean, mphmin
mphmean
Perform a mean of expressions.
SYNTAX
[v1,...,vn] = mphmean(model,{e1,...,en},edim,...)
[v1,...,vn,unit] = mphmean(model,{e1,...,en},edim,...)
DESCRIPTION
[v1,...,vn] = mphmean(model,{e1,...,en},edim,...) evaluates the means 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.
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.
The property solnum is used to select the solution number when a parametric,
eigenvalue or time-dependent solver has been used.
The property outersolnum is used to select the outer solution number when a
parametric sweep has been used in the study step node.
If the matrix property is set to off the output is cell arrays of length P containing cell
arrays of length M.
EXAMPLE
Evaluate the mean temperature in the model domain:
model = mphopen('model_tutorial_llmatlab');
std = model.study.create('std');
std.feature.create('stat','Stationary');
std.run;
maxT = mphmean(model,'T','volume');
maxT = mphmean(model,'T','surface','selection',9);
model = mphopen('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;
Evaluate the mean of the temperature at every time step computed with power set to
30:
maxT = mphmean(model,'T','volume','dataset','dset2');
maxT = mphmean(model,'T','volume','dataset','dset2',...
'solnum',5);
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
mphmesh
Plot a mesh in a MATLAB® figure window.
SYNTAX
mphmesh(model)
mphmesh(model,meshtag,...)
pd=mphmesh(model,meshtag,...)
DESCRIPTION
mphmesh(model) plots the mesh case in a MATLAB figure.
EXAMPLE
Plot the mesh case
model = mphopen('model_tutorial_llmatlab');
model.component('comp1').mesh.run;
mphmesh(model)
Create a second mesh case with an “extra fine” default mesh settings and plot it:
mesh = model.component('comp1').create('mesh2');
mesh.autoMeshSize(2);
mesh.run;
mphmesh(model,'mesh2','meshcolor','r');
Plot data can be returned from mphmesh. This can be used to create the plot later or
to extract information used to create the plot for further analysis
pd = mphmesh(model, 'mesh1');
mphplot(pd)
SEE ALSO
mphgeom, mphmeshstats, mphplot
mphmeshstats
Return mesh statistics and mesh data information.
SYNTAX
stats = mphmeshstats(model)
stats = mphmeshstats(model, meshtag, ...)
[stats,data] = mphmeshstats(model, meshtag, ...)
DESCRIPTION
stats = mphmeshstats(model) returns mesh statistics of the model mesh case in the
structure str.
FIELD DESCRIPTION
FIELD DESCRIPTION
FIELD DESCRIPTION
EXAMPLE
Get the mesh statistics:
model = mphopen('model_tutorial_llmatlab');
model.component('comp1').mesh.run;
stats = mphmeshstats(model)
bar(linspace(0,1,20),stats.qualitydistr)
[stats,data] = mphmeshstats(model);
numedgeelem = stats.numelem(strcmp(stats.types,'edg'))
SEE ALSO
mphmesh
mphmin
Perform a minimum of expressions.
DESCRIPTION
[v1,...,vn] = mphmin(model,{e1,...,en},edim,...) evaluates the 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.
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
The property solnum is used to select the solution number when a parametric,
eigenvalue or time-dependent solver has been used.
The property outersolnum is used to select the outer solution number when a
parametric sweep has been used in the study step node.
If the matrix property is set to off the output is cell arrays of length P containing cell
arrays of length M.
EXAMPLE
Evaluate the minimum temperature in the model domain:
model = mphopen('model_tutorial_llmatlab');
std = model.study.create('std');
std.feature.create('stat','Stationary');
std.run;
maxT = mphmin(model,'T','volume');
maxT = mphmin(model,'T','surface','selection',9);
model = mphopen('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;
Evaluate the minimum of the temperature at every time step computed with power set
to 30:
maxT = mphmin(model,'T','volume','dataset','dset2');
maxT = mphmin(model,'T','volume','dataset','dset2',...
Evaluate the minimum of the temperature at 10.5 sec and 15.2 sec:
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
mphmodel
Return tags for the nodes and subnodes in the COMSOL model object.
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 = mphopen('busbar')
mphmodel(model)
mphnavigator
Graphical user interface (GUI) for viewing the COMSOL Multiphysics model object.
SYNTAX
mphnavigator
mphnavigator(modelv)
DESCRIPTION
mphnavigator opens the Model Object Navigator which is a graphical user 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 object is stored in a variable in the base
workspace (at the MATLAB® command prompt) with the name model.
mphnavigator(model) opens the model object defined with the name model in
Model Object Navigator.
mphopen busbar
Navigate the model object that is accessible with the variable model
mphnavigator
eff_diff = mphopen('effective_diffusivity');
Navigate the model object that is accessible with the variable eff_diff
mphnavigator(eff_diff)
SEE ALSO
mphgetexpressions, mphgetproperties, mphgetselection, mphmodel,
mphsearch, mphshowerrors
mphopen
Graphical user interface (GUI) to open recent model files.
SYNTAX
mphopen
mphopen -dir dirpath
mphopen -clear
model = mphopen(filename)
model = mphopen(filename, mtag)
model = mphopen(filename, mtag, '-nostore')
model = mphopen(filename, mtag, '-history')
model = mphopen(filename, mtag, pwd)
[model, filenameloaded] = mphopen(filename,...)
DESCRIPTION
mphopen starts a GUI with the recent opened files list.
mphopen -dir dirpath starts a GUI with a list of the files in the specified directory
dirpath. If dirpath is not specified the working directory is taken by default.
model = mphopen(filename) loads a COMSOL model object saved with the name
filename and assigns the default tag Model in the COMSOL server. If a model with
model = mphopen(filename, mtag, pwd) loads the COMSOL model in the file
protected with the password pwd.
The model tag mtag and the password pwd are defined as string.
If the model tag 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.
mphopen turns off the model history recording by default, unless the property
'-history' is used.
mphopen does not look for lock file when opening a model in the COMSOL server.
mphparticle
Evaluate expressions on particle and ray trajectories.
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 data set.
FIELD CONTENT
Note: mphparticle only evaluates expressions using particle and ray data sets.
EXAMPLE
Load the model trapped_protons from the Applications Libraries:
model = mphopen('trapped_protons');
Extract the particle positions and particle velocities along the computed trajectories at
every time steps stored in the model:
pd = mphparticle(model)
Evaluate the mirror point latitude (Lm) and the particle equatorial pitch angle (Ea) at
t = 0.7 sec., extract only the data:
pd = mphparticle(model,'dataset','dset2',...
'expr',{'Lm','Ea*180/pi'},'t',0.7,'dataonly','on')
SEE ALSO
mpheval, mphevalpoint, mphint2, mphinterp, mphray
SYNTAX
mphplot(model)
mphplot(model,pgtag,...)
pd = mphplot(model,pgtag,...)
mphplot(pd,...)
DESCRIPTION
mphplot(model) opens a figure window and adds a menu where it is possible to
switch between all the different result plots in a model as well as any geometry and
mesh plots. A toolbar is added to the figure that allows the user to control the use of
views, lights, and camera settings.
mphplot(model,pgtag,...) renders the plot group tagged pgtag from the model
object model in a figure window in MATLAB®.
mphplot(pd,...) makes a plot using the post data structure pd that is generated
using the function mpheval. Plots involving points, lines and surfaces are supported.
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.
The property createplot is useful when extracting plot data structure on machines
without a graphics display.
The data fields returned by mphplot are subject to change. The most important fields
are:
• p, the coordinates for each point that are used for creating lines or triangles.
• n, the normals in each point for the surfaces. These are not always available.
• t, contains the indices to columns in p of a simplex mesh, each column in t
representing a simplex.
• d, the data values for each point.
• rgb, the color values (red, green and blue) entities at each point.
EXAMPLE
Display the plot settings pg using a MATLAB figure
model = mphopen('model_tutorial_llmatlab');
std = model.study.create('std');
std.feature.create('stat','Stationary');
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)
mphplot(model,'pg','server','on')
model = mphopen('model_tutorial_llmatlab');
std = model.study.create('std');
std.feature.create('stat','Stationary');
std.run;
pd = mpheval(model,{'T','ht.tfluxMag'},'selection',2);
mphplot(pd,'index',1,'colortable','Thermal','rangenum',1)
SEE ALSO
colortable, mpheval
mphquad2tri
Convert plot data quad mesh into simplex mesh.
SYNTAX
pdout = mphquad2tri(pdin)
DESCRIPTION
pdout = mphquad2tri(pdin) converts the plot data stored in the structure pdin into
the structure pdout using a simplex mesh.
The input and output structures, respectively pdin and pdout, are structures with
fields p, d, t, rgb and expr.
EXAMPLE
Generate 3D surf data
[x,y] = meshgrid(-0.1:0.2:1.1,-0.4:0.2:0.4);
z = cumsum(0.1*randn(size(x)));
pd = mphsurf(x,y,z);
pd = mphquad2tri(pd);
mphplot(pd)
SEE ALSO
mphsurf, mphreadstl, mphwritestl
mphray
Evaluate expressions on particle and ray trajectories.
SYNTAX
pd = mphray(model)
pd = mphray(model,'expr',{e1,...,en},...)
DESCRIPTION
pd = mphray(model) returns particle position and particle velocity at all time steps
stored in the first particle data set.
Note: mphray only evaluates expressions using particle and ray data sets.
SEE ALSO
mpheval, mphevalpoint, mphevalpoint, mphint2, mphinterp, mphparticle
mphreadstl
Read an STL file and return the data into a plot data structure.
SYNTAX
pd = mphreadstl(filename)
DESCRIPTION
pd = mphreadstl(filename) reads the STL file filename and returns the data into
the plot data structure pd.
• The field name contains the name of the file the data come from.
• The field ref contains the header of the file.
• The field rgb contains the color model data at each vertices. The columns
correspond to node point coordinates in columns in p.
• The field expr contains the data description.
• The field d1 contains the data value at each vertices. The columns correspond to
node point coordinates in columns in p.
SEE ALSO
mphquad2tri, mphsurf, mphwritestl
mphreduction
Return reduced order state space matrices for a model.
SYNTAX
data = mphreduction(model, ...)
DESCRIPTION
data = mphreduction(model, ...) calculates reduced order state-space matrices
for a model based on a time dependent model and a training study. These studies may
already exist in the model or new studies may be added by mphreduction.
mphreduction will by default delete all added studies upon completion. The property
keepfeature may be used to change that, which makes it possible to work further on
already added studies since mphreduction does not support all settings that are
possible for model reduction.
MR = mphreduction(model, ...
'out', {'MA' 'MB' 'A' 'B' 'C' 'D'}, ...
'controls', {'Qin'}, ...
'controlvals', [1], ...
'output', 'comp1.intop1(T)', ...
'unreducedstudy', 'std1', ...
'trainingstudy', 'std2')
SEE ALSO
mphstate
mphsave
Save a COMSOL Multiphysics model.
SYNTAX
mphsave(model)
mphsave(model,filename,...)
DESCRIPTION
mphsave(model) saves the COMSOL model object model.
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®.
Note: Model created with older version than COMSOL 5.3 cannot be saved using
the component syntax.
SEE ALSO
mphopen, mphload
mphsearch
Graphical user interface (GUI) for searching expressions in the COMSOL model
object.
SYNTAX
mphsearch(model)
DESCRIPTION
mphsearch(model) opens a graphical user interface that can be used to search
expressions in the model object model. Search using a text available in the name,
expression or description of the variable.
mphselectbox
Select geometric entity using a rubberband/box.
SYNTAX
n = mphselectbox(model,geomtag,boxcoord,entity,...)
DESCRIPTION
n = mphselectbox(model,geomtag,boxcoord,entity,...) returns the indices of
the geometry entities that are inside the rubberband 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, where
N is the geometry space dimension.
entity can be one of point, edge, boundary or domain following the entity space
dimension defined below:
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 domains using a box selection:
model = mphopen('model_tutorial_llmatlab');
n = mphselectbox(model,'geom1',coordBox,'boundary');
Find the boundaries inside the selection box that are adjacent to domain number 1:
n = mphselectbox(model,'geom1',coordBox,'boundary',...
'adjnumber',1);
model = mphopen('model_tutorial_llmatlab');
geom = model.component('comp1').geom('geom1');
geom.feature('fin').set('action','assembly');
geom.run('fin');
coordBox = [-1e-3,51e-3;-1e-3,51e-3;9e-3,11e-3];
n = mphselectbox(model,'geom1',coordBox,'boundary');
n = mphselectbox(model,'geom1',coordBox,'boundary',...
'adjnumber',2);
SEE ALSO
mphgetadj, mphgetcoords, mphselectcoords, mphviewselection
mphselectcoords
Select a geometric entity using point coordinates.
SYNTAX
n = mphselectcoords(model,geomtag,coord,entity,...)
DESCRIPTION
n = mphselectcoords(model,geomtag,coord,entity,...) finds geometry
entity numbers based on their vertex coordinates.
One or more coordinates can be provided. The function searches for vertices near
these coordinates using a tolerance radius. The list of the entities that are adjacent to
such vertices is returned.
entity can be one of point, edge, boundary or domain following the entity space
dimension defined below:
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.
EXAMPLE
Find geometry entity number
model = mphopen('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:
Return the indices of the edges that have a vertex within the search radius from all
points:
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');
model = mphopen('model_tutorial_llmatlab');
geom = model.component('comp1').geom('geom1');
geom.feature('fin').set('action', 'assembly');
geom.run('fin');
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
mphgetadj, mphgetcoords, mphselectbox, mphviewselection
mphshowerrors
Show the messages in error nodes in the COMSOL Multiphysics model.
SYNTAX
mphshowerrors(model)
list = mphshowerrors(model)
list = mphshowerrors(model) returns the error and warning messages stored in the
model and where they are located in the Nx3 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, the second column contain the error message and the third column
contains a cell arrays of the model tree nodes that contain the error information, which
can help for automated processing of error and warning conditions.
mphsolinfo
Get information about a solution object.
SYNTAX
info = mphsolinfo(model,...)
info = mphsolinfo(model,'solname',soltag,...)
DESCRIPTION
info = mphsolinfo(model,...) returns information about the solution object.
FIELD CONTENT
FIELD CONTENT
EXAMPLE
Get the information about the default solution object:
model = mphopen('model_tutorial_llmatlab');
std = model.study.create('std');
std.feature.create('stat','Stationary');
std.run;
solinfo = mphsolinfo(model)
model = mphopen('model_tutorial_llmatlab');
std = model.study.create('std');
param = std.feature.create('param','Parametric');
time = std.feature.create('time','Transient');
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
mphgetu, mphxmeshinfo, mphsolutioninfo
mphsolutioninfo
Get information about solution objects and data sets containing given parameters.
SYNTAX
info = mphsolutioninfo(model)
info = mphsolutioninfo(model,'parameters',{{ei,vi,toli},...},...)
DESCRIPTION
info = mphsolutioninfo(model) returns information about all solution object and
solution data set combinations in model.
FIELD CONTENT
FIELD CONTENT
EXAMPLE
Load model_tutorial_llmatlab.mph:
model = mphopen('model_tutorial_llmatlab');
std = model.study.create('std');
param = std.feature.create('param','Parametric');
time = std.feature.create('time','Transient');
std.run;
info = mphsolutioninfo(model,'parameters',{'power',30,0})
info = mphsolutioninfo(model,'parameters',{{'power',90,0},...
{'t',10.4,0.5}})
dset = info.sol2.dataset
solnum = info.sol2.map(end-1)
outersolnum = info.sol2.map(end)
SEE ALSO
mphgetu, mphxmeshinfo, mphsolinfo
mphstart
Connect MATLAB® to a COMSOL server.
SYNTAX
mphstart
mphstart(port)
mphstart(ipaddress, port)
mphstart(ipaddress, port, username, password)
mphstart(ipaddress, port, comsolpath)
mphstart(ipaddress, port, comsolpath, username, password)
DESCRIPTION
mphstart creates a connection with a COMSOL server using the default port number
(which is 2036).
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.
Once MATLAB is connected to the server, import the COMSOL class in order to use
the ModelUtil commands. To import the COMSOL class enter:
import com.comsol.model.*
import com.comsol.model.util.*
EXAMPLE
Connect manually MATLAB to a COMSOL Multiphysics Server and create a model:
mphstart
import com.comsol.model.*
import com.comsol.model.util.*
mphstart('192.168.0.1',2037)
mphstate
Get state space matrices for a dynamic system.
SYNTAX
str = mphstate(model,soltag,'Out',{'SP'})
str = mphstate(model,soltag,'Out',{'SP1','SP2',...})
DESCRIPTION
®
str = mphstate(model,soltag,'out',{'SP'}) returns a MATLAB 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.
·
M C x = M C Ax + M C Bu
y = Cx + Du
where x are the state variables, u are the input variables, and y are the output variables.
y = ( D – C ( M C A ) – 1 M C B )u
U = Nullx + ud + u 0
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 MCA are produced by the same algorithms that do the
finite-element assembly and constraint elimination in COMSOL Multiphysics. MC and
MCA 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 MCB 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).
EXAMPLE
Load model_tutorial_llmatlab.mph:
model = mphopen('model_tutorial_llmatlab');
comp1 = model.component('comp1');
comp1.mesh('mesh1').autoMeshSize(9);
std = model.study.create('std');
M = mphstate(model,'sol1','out',{'A','B','C','D'},...
'input','power','output','comp1.ppb1');
G = M.D-M.C*(inv(M.A))*M.B;
y = full( G*power );
y = y + T0
mphsurf
Create plot data structure from surf data.
SYNTAX
pd = mphsurf(x,y,z)
pd = mphsurf(z)
pd = mphsurf(z) creates the plot data structure pd from surf data z. A unit scale is
assumed for the x and y coordinates.
EXAMPLE
Create random height data
[x,y] = meshgrid(-0.1:0.2:1.1,-0.4:0.2:0.4);
z = cumsum(0.1*randn(size(x)));
pd = mphsurf(x,y,z);
mphplot(pd)
SEE ALSO
mphquad2tri, mphreadstl, mphwritestl
mphtable
Get table data.
SYNTAX
info = mphtable(model,tabletag)
DESCRIPTION
info = mphtable(model,tabletag) returns the structure info containing the data
with the tabletag tag and its headers.
FIELD CONTENT
EXAMPLE
Load model_tutorial_llmatlab.mph, add a stationary study and compute the
solution for different power values:
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;
str = mphtable(model,'tbl');
tbl_data = str.data
SEE ALSO
mpheval, mphevalpoint, mphglobal, mphint2, mphinterp, mphmax, mphmean,
mphmin
mphtags
Get tags and names for nodes in a COMSOL Multiphysics model.
SYNTAX
mphtags(model)
mphtags(node)
mphtags(model, type)
[tags,labels,displaystrings] = mphtags(...)
mphtags
mphtags -show
[tags,filename,fullfilename] = mphtags
DESCRIPTION
mphtags is used to retrieve tags from nodes in a COMSOL Multiphysics model or tags
from models that are loaded on the server.
When mphtags is called with a model or node variable the tags are returned form the
model. mphtags also be called using a model variable and a type, where type can be
one of these strings: result, dataset, table, numerical, and export to give
If mphtags is called with output arguments it is possible to get both the tags as well as
labels and display names used for the nodes. For example,
[tags,labels,displaystrings] = mphtags(model.geom)
If mphtags is called with the root model node as argument, the filename of the model
can be returned:
[tag,filename,displaystring] = mphtags(model)
mphtags can be used to return a list of files currently loaded on the server. For
example,
[tags,filename,fullfilename] = mphtags
In order to see this information quickly it is possible to call mphtags like this:
mphtags -show
mphthumbnail
Set or get model thumbnail.
SYNTAX
mphthumbnail(model,filename)
mphthumbnail(model,image)
mphthumbnail(model,fig)
mphthumbnail(model,'')
[image,imagefilename] = mphthumbnail(model)
DESCRIPTION
mphthumbnail sets or gets the model thumbnail for model loaded on the server. In
order to update the model thumbnail on disk the model must be saved.
mphthumbnail(model,image) sets the thumbnail using the image data image. image
is either a NxM or a NxMx3 matrix. The preferred size of the image is 280 by 210
pixels.
EXAMPLE
Load model_tutorial_llmatlab.mph:
model = mphopen('model_tutorial_llmatlab');
im = mphthumbnail(model);
imshow(im)
filename = fullfile(tempdir,'imagefile.png');
print(filename,'-dpng','-r48')
mphthumbnail(model,filename)
SEE ALSO
mphload, mphsave
mphversion
Return the version number for COMSOL Multiphysics.
SYNTAX
v = mphversion
[v,vm] = mphversion(model)
DESCRIPTION
v = mphversion returns the COMSOL Multiphysics version number that MATLAB
is connected to as a string.
EXAMPLE
Load model_tutorial_llmatlab.mph:
model = mphopen('model_tutorial_llmatlab');
SEE ALSO
mphload, mphsave
mphviewselection
Display a geometric entity selection in a MATLAB® figure.
SYNTAX
mphviewselection(model,geomtag,number,entity,...)
mphviewselection(model,seltag,...)
DESCRIPTION
mphviewselection(model,geomtag,number,entity,...) displays the geometric
entity number of type entity in MATLAB figure including the representation of the
geometry geomtag.
EXAMPLE
Plot boundary 6 using yellow color:
model = mphopen('model_tutorial_llmatlab');
mphviewselection(model,'geom1',6,'boundary',...
'facecolorselected',[1 1 0],'facealpha',0.5)
mphviewselection(model,'geom1',1:8,'edge',...
'edgecolorselected',[0 1 0])
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:
SEE ALSO
mphgeom, mphselectbox, mphselectcoords
mphwritestl
Export plot data as an STL file.
SYNTAX
mphwritestl(filename, pd)
mphwritestl(filename, pd, '-binary')
DESCRIPTION
mphwritestl(filename, pd) exports data in the plot data structure pd as the STL
file filename.
Other fields in the plot data structure are not considered to generate the surface mesh.
model = mphopen('vacuum_flask_llmatlab')
pd = mphplot(model, 'pg1')
pd2stl = pd{2}{1};
mphwritestl('vacuum_flask.stl', pd2stl)
model = mphopen('model_tutorial_llmatlab');
model.component('comp1').mesh('mesh1').run;
[s,d] = mphmeshstats(model, 'mesh1');
idx = strcmp(s.types, 'tri');
pdmesh.p = d.vertex;
pdmesh.t = d.elem{idx};
mphwritestl('mesh2geom.stl', pdmesh);
SEE ALSO
mphquad2tri, mphreadstl, mphsurf
mphxmeshinfo
Extract information about the extended mesh.
SYNTAX
info = mphxmeshinfo(model, ...)
DESCRIPTION
info = mphxmeshinfo(model,...) extracts extended mesh information from the
active solution object.
FIELD DESCRIPTION
EXAMPLE
Extract xmesh information:
model = mphopen('model_tutorial_llmatlab.mph');
std = model.study.create('std');
std.feature.create('stat', 'Stationary');
std.run;
info = mphxmeshinfo(model)
dofs = info.ndofs
coords = info.dofs.coords;
idx = info.elements.tet.dofs
model = mphopen('model_tutorial_llmatlab.mph');
comp1 = model.component('comp1');
ec = comp1.physics.create('ec','ConductiveMedia','geom1');
ec.feature.create('gnd1','Ground',2).selection.set(3);
pot = ec.feature.create('pot','ElectricPotential',2);
pot.selection.set(7);
pot.set('V0',1,'50[mV]');
hs = comp1.physics('ht').feature('hs1');
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.dofsinds(idx_dofs);
idx_dofnames = find(strcmp(info.dofs.dofnames,'comp1.V'))-1;
idx = find(idx_names==idx_dofnames)
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:
mphgetu, mphmatrix, mphsolinfo, mphsolutioninfo
building 3D geometries 58
INDEX| 347
data sets syntax 143 data 153, 180
data, extracting 180 eliminated matrices 190
defining matrices 199
materials 116 mesh information 107
MATLAB functions 242 plot data 139
selections 122 solution vectors 215
settings 120 system matrices 186
Delaunay method 80 extruding meshes 88, 90
derivative recovery 157
F floating network license (FNL) 29
difference operation 54
free meshing 92
directory path, MATLAB function 245
free quad mesh, example 82
disabling model history 235
free triangle mesh, example 80
disconnecting MATLAB 30
function derivatives 247
displaying
function inputs/outputs 246
geometries 50
functions
meshes 75
interpolation 120
plot groups 138
MATLAB 151
selections 128
MATLAB, adding 240
documentation 18
G geometry
dofs, xmesh 219
creating 66
E element, xmesh 219
displaying 50
emailing COMSOL 21
parameterized 62
enabling model history 235
parametrization, example 182
entity, geometry 51
retrieve information 60
equations, modifying 116
sequence 49
errors 231
global equations 118
evaluating
global expressions 174
data 144
global matrix 178
expressions 167
H Hankel function 244
global expressions 174
history, model 42
global matrix 178
integrals 162 I image data conversion, example 70
explicit selections 122 image data, create geometry 68
exporting importing
data 146 meshes 101
expression average 164 imread (MATLAB function) 68
extended mesh 218 inner solution 212
extracting integrals, evaluating 162
348 | I N D E X
internet resources 18 methods 38
interpolation curve 66 methods, mphnavigator 226
interpolation functions 120 Microsoft Windows 26
minimum of expressions 157
J Java 38
model examples 17
Java heap size 233
model expressions 227
job sequences 134
model features 234
K knowledge base, COMSOL 21
model history 42, 235
L linear matrix 192 model object
linearization points 187, 200 calling 151
Linux 26 create custom GUI 236
list model object 40 information 226
load model 41 methods 39
loops 181, 235 navigating 221
Model Tree 224
M Mac OS X 26
models, running in loops 181
mass matrix 198
ModelUtil method 39
materials 116
modifying equations 116
MATLAB desktop 24
mpheval 167–170
MATLAB feature node 246
mphevalglobalmatrix 178
MATLAB functions 151, 240
mphevalpoint 170–172
MATLAB functions, plot 243
MPH-files 20
matrices, state-space 198
mphgetexpressions 230
maximum of expression 160
mphgetproperties 228–229
measuring, mesh quality 103
mphgetselection 230
memory requirements 235
mphgetu 215–216
mesh
mphglobal 174, 176
boundary layers 93
mphinputmatrix 192–193
converting 100
mphint2 162–164
copying 96
mphinterp 153–155, 157
data 107
mphmatrix 186–187, 190
displaying 75
mphmax 160–161
element size, controlling 76
mphmean 164–166
importing 101
mphmin 157–159
quality 103
mphmodel 226
refining 96
mphnavigator 221, 223–226
resolution 77
mphparticle 173–174
sequence 74
mphray 173
statistics 104
INDEX| 349
mphsearch 227 running, models in loops 181
mphshowerrors 231
S save model object 44
mphsolinfo 210–211
selecting, linearization points 187
mphsolutioninfo 212–214
selections
mphstate 198–201
defining 122
mphtable 180
displaying 128
mphxmeshinfo 195, 218, 220
sequences of operations 38
myscript 184
sequences, solvers 133
N NASTRAN 101 set method 150
node points 167 set operations 54
nodes, xmesh 219 set the feature property 50
numerical node syntax 144 setindex method 151
setting
O ODE problem, example 119
linear matrix system 192
outer solution 212
linearization points 200
P parameterized geometries 62
simplex elements 96
parametric jobs 134
solid modeling 58
parametric sweep 134
solution information 210, 212
particle trajectories 173
solution object 210
Physics Builder 121
solution vector 215
physics interfaces 112–113
solutions, specifying 216
plot data, extracting 139
solver configurations syntax 132
plot groups 137–138
solving, ODE problems 119
plot while solving 135
squeezed singleton 172
plotting data, example 141
state-space export 198
port number 24
statistics, mesh 104
preferences 32
structured meshes 83
prism mesh 90
study syntax 131
progress bar 40
sweeping meshes 88
Q quadrilateral mesh, example 83 swept meshing 92
syntax
R ray trajectories 173
data sets 143
refining meshes 96
materials 116
remove model object 39
numerical node 144
resolution, mesh 77
physics interfaces 112
results evaluation 144
plot groups 137
revolved prism mesh, example 88
solver configurations 132
revolving face meshes 88
studies 131
run solver sequences 133
350 | I N D E X
system matrices 186
W warnings 231
weak form equation, example 117
web sites, COMSOL 21
X xmesh 218
xterm 184–185
INDEX| 351
352 | I N D E X