Sie sind auf Seite 1von 193

LiveLink

for Matlab
Users Guide

VERSION 4.2

TM

Benelux

India

United Kingdom

COMSOL BV
Rntgenlaan 37
2719 DX Zoetermeer
The Netherlands
+31 (0) 79 363 4230
+31 (0) 79 361 4212
info@comsol.nl
www.comsol.nl

COMSOL Multiphysics Pvt. Ltd.


Esquire Centre,
C-Block, 3rd Floor
No. 9, M. G. Road
Bangalore 560001
Karnataka
+91-80-4092-3859
+91-80-4092-3856
info@comsol.co.in
www.comsol.co.in

COMSOL Ltd.
UH Innovation Centre
College Lane
Hatfield
Hertfordshire AL10 9AB
+44-(0)-1707 636020
+44-(0)-1707 284746
info.uk@comsol.com
www.uk.comsol.com

Denmark
COMSOL A/S
Diplomvej 381
2800 Kgs. Lyngby
+45 88 70 82 00
+45 88 70 80 90
info@comsol.dk
www.comsol.dk

Finland
COMSOL OY
Arabiankatu 12
FIN-00560 Helsinki
+358 9 2510 400
+358 9 2510 4010
info@comsol.fi
www.comsol.fi

France
COMSOL France
WTC, 5 pl. Robert Schuman
F-38000 Grenoble
+33 (0)4 76 46 49 01
+33 (0)4 76 46 07 42
info@comsol.fr
www.comsol.fr

Germany
COMSOL Multiphysics GmbH
Berliner Str. 4
D-37073 Gttingen
+49-551-99721-0
+49-551-99721-29
info@comsol.de
www.comsol.de

United States
Italy
COMSOL S.r.l.
Via Vittorio Emanuele II, 22
25122 Brescia
+39-030-3793800
+39-030-3793899
info.it@comsol.com
www.comsol.it

Norway
COMSOL AS
Postboks 5673 Sluppen
Sndre gate 7
NO-7485 Trondheim
+47 73 84 24 00
+47 73 84 24 01
info@comsol.no
www.comsol.no

Sweden
COMSOL AB
Tegnrgatan 23
SE-111 40 Stockholm
+46 8 412 95 00
+46 8 412 95 10
info@comsol.se
www.comsol.se

Switzerland
COMSOL Multiphysics GmbH
Technoparkstrasse 1
CH-8005 Zrich
+41 (0)44 445 2140
+41 (0)44 445 2141
info@ch.comsol.com
www.ch.comsol.com

COMSOL, Inc.
1 New England Executive Park
Suite 350
Burlington, MA 01803
+1-781-273-3322
+1-781-273-6603
COMSOL, Inc.
10850 Wilshire Boulevard
Suite 800
Los Angeles, CA 90024
+1-310-441-4800
+1-310-441-0868
COMSOL, Inc.
744 Cowper Street
Palo Alto, CA 94301
+1-650-324-9935
+1-650-324-9936
info@comsol.com
www.comsol.com
For a complete list of
international representatives,
visit
www.comsol.com/contact

Home Page

www.comsol.com

COMSOL User Forums

www.comsol.com/
community/forums

LiveLink for MATLAB Users Guide


20092011 COMSOL
Protected by U.S. Patents 7,519,518; 7,596,474; and 7,623,991. Patents pending.
This Documentation and the Programs described herein are furnished under the COMSOL Software
License Agreement (www.comsol.com/sla) and may be used or copied only under the terms of the license
agreement.
COMSOL, COMSOL Desktop, COMSOL Multiphysics, and LiveLink are registered trademarks or trademarks of COMSOL AB. MATLAB is a registered trademark of The MathWorks, Inc.. Other product or
brand names are trademarks or registered trademarks of their respective holders.
Version:
Part No. CM020008

May 2011

COMSOL 4.2

C o n t e n t s
Contents 2

Chapter 1: Introduction
About Using this Guide

Where Do I Access the Documentation and the Model Library? . . . . . 7


Typographical Conventions . . . . . . . . . . . . . . . . . . . 9
Getting Started

11

Quick Start . . . . . . . . . . . . . . . . . . . . . . . . . 11
The Client/Server Connection . . . . . . . . . . . . . . . . . . 12
Basics on Working with a Model Object . . . . . . . . . . . . . . 13
Loading and Saving a Model . . . . . . . . . . . . . . . . . . . 14
Importing and Exporting a Model . . . . . . . . . . . . . . . . . 15
COMSOL 3.5a Model Conversion. . . . . . . . . . . . . . . . . 17
Calling External MATLAB Functions in the COMSOL Desktop . . . . . . 19
User-Defined GUIs . . . . . . . . . . . . . . . . . . . . . . 19
Startup of COMSOL with MATLAB . . . . . . . . . . . . . . . . 20
Running COMSOL with MATLAB in Batch Mode . . . . . . . . . . . 20
Getting More Information . . . . . . . . . . . . . . . . . . . . 20

Chapter 2: Building Models


The Model Object

23

Model Object Methods . . . . . . . . . . . . . . . . . . . . . 23


Information About the Model Object . . . . . . . . . . . . . . . 25
A Simple Model Example . . . . . . . . . . . . . . . . . . . . 26
Utility Functions . . . . . . . . . . . . . . . . . . . . . . . 29
Using the On-Line Documentation . . . . . . . . . . . . . . . . 30
Using MATLAB Functions in COMSOL Multiphysics . . . . . . . . . . 30
Running the Model in a Loop

35

Running a Loop within the COMSOL Model Object . . . . . . . . . . 35


Running a Model in a Loop Using MATLAB Tools . . . . . . . . . . . 37

Chapter 3: Creating Geometries


Geometry Sequences

41

The Geometry Sequence Syntax . . . . . . . . . . . . . . . . . 41


Working with Geometry Sequences . . . . . . . . . . . . . . . . 42
Exchanging Geometries with the COMSOL Desktop . . . . . . . . . 48
Importing and Exporting Geometries and CAD Models from File . . . . . 49
Retrieving Geometry Information . . . . . . . . . . . . . . . . . 49
Modeling with a Parameterized Geometry . . . . . . . . . . . . . 51
Images and Interpolation Data . . . . . . . . . . . . . . . . . . 53

Chapter 4: Modeling Physics


Physics Interfaces

57

The Physics Interface Syntax . . . . . . . . . . . . . . . . . . . 57


Using Physics Interfaces

. . . . . . . . . . . . . . . . . . . . 58

The Material Syntax . . . . . . . . . . . . . . . . . . . . . . 58


Using Materials . . . . . . . . . . . . . . . . . . . . . . . . 59
Modifying the Equations . . . . . . . . . . . . . . . . . . . . 59
Adding Global Equation

. . . . . . . . . . . . . . . . . . . . 60

Chapter 5: Creating Meshes


Meshing Sequences

63

The Meshing Sequence Syntax . . . . . . . . . . . . . . . . . . 63


Mesh Creation Functions . . . . . . . . . . . . . . . . . . . . 64
Importing External Meshes and Mesh Objects . . . . . . . . . . . . 81
Getting Mesh Information . . . . . . . . . . . . . . . . . . . . 82
Getting and Setting Mesh Data . . . . . . . . . . . . . . . . . . 83

Chapter 6: Creating Studies


The Study

87

The Study Syntax . . . . . . . . . . . . . . . . . . . . . . . 87


Using the Study. . . . . . . . . . . . . . . . . . . . . . . . 87
The Solver Configuration Syntax . . . . . . . . . . . . . . . . . 88

3 |

CHAPTER :

Using Solver Configurations . . . . . . . . . . . . . . . . . . . 88


Evaluating System Matrices . . . . . . . . . . . . . . . . . . . 89
Exporting State-Space Models . . . . . . . . . . . . . . . . . . 93
Retrieve Xmesh Information . . . . . . . . . . . . . . . . . . . 96
Creating Solution . . . . . . . . . . . . . . . . . . . . . . . 97

Chapter 7: Analyzing Results


Results

103

The Plot Group Syntax . . . . . . . . . . . . . . . . . . . . 103


Using Plot Groups. . . . . . . . . . . . . . . . . . . . . . 104
The Data Set Syntax . . . . . . . . . . . . . . . . . . . . . 109
Evaluating Data . . . . . . . . . . . . . . . . . . . . . . . 111
Evaluating Global Data . . . . . . . . . . . . . . . . . . . . 113
Integrating Expressions . . . . . . . . . . . . . . . . . . . . 113
Interpolating Data . . . . . . . . . . . . . . . . . . . . . . 113
Generating Reports . . . . . . . . . . . . . . . . . . . . . 114

Chapter 8: COMSOL 3.5a Compatibility


Converting M-Files

119

M-File Conversion. . . . . . . . . . . . . . . . . . . . . . 119


M-File Conversion, Including a For Loop . . . . . . . . . . . . . 126
Converting Postprocessing Sequences . . . . . . . . . . . . . . 129
Unsupported Functions in COMSOL Multiphysics 4.2 . . . . . . . . 135

Chapter 9: Command Reference


Summary of Commands

139

Commands Grouped by Function

140

5 |

CHAPTER :

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 Java API Reference Guide provides
additional documentation of the API.
In this chapter:
About Using this Guide
Getting Started

About Using this Guide


In this section:
Where Do I Access the Documentation and the Model Library?
Typographical Conventions

Where Do I Access the Documentation and the Model Library?


A number of Internet resources provide more information about COMSOL
Multiphysics, including licensing and technical information. The electronic
documentation, Dynamic Help, and the Model Library are all accessed through the
COMSOL Desktop.

Note: If you are working directly from a PDF on your computer, the blue links do
not work to open a model or documentation referenced in a different user guide.
However, if you are using the online help desk in COMSOL Multiphysics, these links
work to other modules, model examples, and documentation sets.

THE DOCUMENTATION

The COMSOL Multiphysics Users Guide and COMSOL Multiphysics Reference


Guide describe all the interfaces included with the basic COMSOL license. These
guides also have instructions about how to use COMSOL Multiphysics, and how to
access the documentation electronically through the COMSOL Multiphysics help
desk.
To locate and search all the documentation, in COMSOL Multiphysics:
Click the buttons on the toolbar or
Select Help>Documentation (

) or Help>Dynamic Help (

) from the main menu

and then either enter a search term or look under a specific module in the
documentation tree.
THE MODEL LIBRARY

Each model comes with a theoretical background and step-by-step instructions to


create the model. The models are available in COMSOL as MPH-files that you can

7 |

CHAPTER 1: INTRODUCTION

open for further investigation. Use both the step-by-step instructions and the actual
models as a template for your own modeling and applications. SI units are used to
describe the relevant properties, parameters, and dimensions in most examples, but
other unit systems are available.
To open the Model Library, select View>Model Library (
) from the main menu, and
then search by model name or browse under a Module folder name. If you also want
to review the documentation explaining how to build a model, select the model and
) to reach the PDF or HTML version,
click Model PDF or the Dynamic Help button (
respectively. Alternatively, select Help>Documentation in COMSOL and search by name
or browse by Module.
If you have feedback or suggestions for additional models for the library (including
those developed by you), feel free to contact us at info@comsol.com.
COMSOL WEB SITES

Main corporate web site: http://www.comsol.com/


Worldwide contact information: http://www.comsol.com/contact/
Online technical support main page: http://www.comsol.com/support/
COMSOL Support Knowledge Base, your first stop for troubleshooting assistance,
where you can search for answers to any COMSOL questions:
http://www.comsol.com/support/knowledgebase/
Product updates: http://www.comsol.com/support/updates/
CONT ACT ING COMSOL BY EMAIL

For general product information, contact COMSOL at info@comsol.com.


To receive technical support from COMSOL for the COMSOL products, please
contact your local COMSOL representative or send your questions to
support@comsol.com. An automatic notification and case number is sent to you by
email.
COMSOL COMMUNITY

On the COMSOL web site, you find a user community at http://www.comsol.com/


community/. The user community includes a discussion forum, a model exchange,
news postings, and a searchable database of papers and presentations.

ABOUT USING THIS GUIDE

Typographical Conventions
All COMSOL user guides use a set of consistent typographical conventions that should
make it easy for you to follow the discussion, realize what you can expect to see on the
screen, and know which data you must enter into various data-entry fields.
In particular, you should be aware of these conventions:
Click text highlighted in blue to go to other information in the PDF. When you are
using the online help desk in COMSOL Multiphysics, these links also work to other
Modules, model examples, and documentation sets.
A boldface font of the shown size and style indicates that the given word(s) appear
exactly that way on the COMSOL Desktop (or, for toolbar buttons, in the
) is often
corresponding tooltip). For example, the Model Builder window (
referred to and this is the window that contains the model tree. As another example,
), and this boldface
the instructions might say to click the Zoom Extents button (
font means that you can expect to see a button with that label (when you hover over
the button with your mouse) on the COMSOL Desktop.
The names of other items on the COMSOL Desktop that do not have direct labels
contain a leading uppercase letter. For instance, we often refer to the Main toolbar
the horizontal bar containing several icons that are displayed on top of the user
interface. However, nowhere on the COMSOL Desktop, nor the toolbar itself,
includes the word Main.
The forward arrow symbol > indicates selecting a series of menu items in a specific
order. For example, Options>Results is equivalent to: From the Options menu, select
Results.
A Code (monospace) font indicates you are to make a keyboard entry in the user
interface. You might see an instruction such as Enter (or type) 1.25 in the Current
density edit field. The monospace font also is an indication of programming code.
or a variable name. An italic Code (monospace) font indicates user inputs and parts
of names that can vary or be defined by the user.
An italic font indicates the introduction of important terminology. Expect to find
an explanation in the same paragraph or in the Glossary. The names of other user
guides in the COMSOL documentation set also have an italic font.

The Difference Between Nodes, Buttons, and Icons


Node: A node is located in the Model Builder and has an icon image to the left of it.
Right-click a node to open a Context Menu and to perform actions.

9 |

CHAPTER 1: INTRODUCTION

Button: Click a button to perform an action. Usually located on a toolbar (the Main
toolbar or the Graphics window toolbar, for example), or in the upper right corner
of a Settings window.
Icon: An icon is an image that displays on a window (for example, the Model Wizard
or Model Library) or displays in a Context Menu when a node is right-clicked.
Sometimes selecting an icon from a nodes Context Menu adds a node with the
same image and name, sometimes it simply performs the action indicated (for
example, Delete, Enable, or Disable).

ABOUT USING THIS GUIDE

10

Getting Started
In this section:
Quick Start
The Client/Server Connection
Basics on Working with a Model Object
Loading and Saving a Model
Importing and Exporting a Model
COMSOL 3.5a Model Conversion
Calling External MATLAB Functions in the COMSOL Desktop
User-Defined GUIs
Startup of COMSOL with MATLAB
Running COMSOL with MATLAB in Batch Mode
Getting More Information

Quick Start
The easiest way to get started with LiveLink for MATLAB is to make a model in
COMSOL Multiphysics, save it as a Model M-file, and load it in MATLAB.
1 From the File menu, select Open Model Library.
2 Navigate to COMSOL Multiphysics>Equation-based Models and double-click
shell_diffusion to open it.
3 From the File menu, select Save As Model M-file and save it as shell_diffusion in

a folder called models.


To load the model in MATLAB, start COMSOL with MATLAB:
Windows: choose COMSOL 4.2 with MATLAB from the Start Menu.
Linux and Mac OS X: run the command comsol server matlab.
Once COMSOL starts with MATLAB, set your MATLAB path to point to the folder
where the M-file is saved. Use the addpath command in MATLAB to add this folder
to the path, for example,
addpath C:\users\myself\models

11 |

CHAPTER 1: INTRODUCTION

Then run the Model M-file by entering its name:


shell_diffusion

Or open the M-file in the MATLAB editor by entering


edit shell_diffusion

For example, change the parameter definitions in the model object. They are available
under model.param (see lines 2528 in the M-file) in the model object. Then run the
file again.

The Client/Server Connection


The LiveLink interface is based on a client/server modeMATLAB is the client,
where users enter commands that are run in the COMSOL server. When starting
COMSOL with MATLAB only MATLAB and the COMSOL server are started. The
COMSOL server is visible in a separate terminal window.
The COMSOL model object is only available in the COMSOL server, you can create
a link in MATLAB in order to edit, modify or solve the model object.
It is possible to change clients for the COMSOL server and alternate between
MATLAB and a COMSOL Desktop to be connected to the COMSOL server. It is
then possible to access the model object between the COMSOL graphical user
interface (GUI) and the MATLAB prompt.
M A N U A L L Y C O N N E C T M AT L A B T O T H E C O M S O L S E R VE R

It is also possible to explicitly connect MATLAB to an existing COMSOL server. To


continue with this step, open both MATLAB and a COMSOL server.
To start a COMSOL server:
On Windows go to the start menu All Programs>COMSOL 4.2> Client Server>COMSOL
Multiphysics 4.2 server.
On Mac OS X/Linux enter comsol server at a terminal window in the COMSOL
installation directory.
1 In MATLAB, set the path of the folder COMSOL42/mli where the file mphstart.p is

stored.
2 Connect MATLAB to the COMSOL server. Enter the command:
mphstart(portnumber)

GETTING STARTED

12

Where portnumber is the number of the port to use the COMSOL server. If the
COMSOL server is listening on the default port number (2036) you dont need to
specify the port number in mphstart.
3 Import the COMSOL class and start implementing a model:
import com.comsol.model.*
import com.comsol.model.util.*
model = ModelUtil.create('Model');
D I S C O N N E C T M AT L A B F RO M T H E C O M S O L S E R VE R

Once MATLAB is connected to the COMSOL server, disconnect from the server by
entering:
ModelUtil.disconnect;

To reconnect to the server, use methods from the ModelUtil package:


ModelUtil.connect('localhost', 2036);
model = ModelUtil.create('Model');

Basics on Working with a Model Object


Before starting to work with a model object, you need to create it. Create it by
entering:
model = ModelUtil.create('Model');

The above command create a model object in the COMSOL server and a MATLAB
link that can access the function of the COMSOL model object. The COMSOL model
object is defined as Model while the MATLAB link is defined by model.
In addition to creating models, you can list the model object available in the COMSOL
server:
list = ModelUtil.tags;

Create a MATLAB link to a specific model object <ModelName> available in the


COMSOL server:
model = ModelUtil.model(<ModelName>);

Remove the model object <ModelName> from the COMSOL server:


ModelUtil.remove(<ModelName>);

You can also set a path in the COMSOL server. This is very useful if you need to use
external file in the COMSOL model (for instance geometry, mesh or data file):

13 |

CHAPTER 1: INTRODUCTION

ModelUtil.path(<path>);

By default the progress bar is not displayed during the mesh and solve operation. It is
possible to activate the progress bar with the command:
ModelUtil.showProgress(true);

To deactivate the prgres bar use the command:


ModelUtil.showProgress(false);

Loading and Saving a Model


To load an existing model saved as a mph-file you can use the function mphload. For
example to load the busbar model from the Model Library enter at the MATLAB
prompt:
model = mphload('busbar.mph');

This create a model object Model in the COMSOL server that is accessible using the
MATLAB object model.
When using the function mphload, the model history is automatically disabled, this is
to prevent large amount of history recording when running the model in loop. If you
want to keep the model history you can use the function mphload, as following:
model = mphload('busbar.mph','-history');

You can also use the command:


model = ModelUtil.load('Model', ...
['<COMSOL>\models\COMSOL_Multiphysics\' ...
'Multiphysics\busbar.mph']);

Here, <COMSOL> is your COMSOL installation directory.


You can save models on the MPH format in the working directory by entering
model.save('shell_diffusion2');

If you want to save the model in a specified directory enter:


model.save('path\shell_diffusion2');

A file on the MPH format can be loaded by the COMSOL Desktop. In addition you
can save your model as a Model M-file by entering
model.save('shell_diffusion2','m');

GETTING STARTED

14

When saving the model as a M-file, the file contains the syntax of the entire sequence
history. If you want only to get the sequence corresponding to the set up of the model
object, you need to reset it first. You can use the reset method as:
model.reset;

You can run a Model M-file in MATLAB by entering its name


model = shell_diffusion2

Note: The models are not automatically saved between MATLAB sessions.

Importing and Exporting a Model


It is possible to alternate between the MATLAB scripting interface and the COMSOL
graphical user interface in order to edit and/or modify the model object. When using
COMSOL with MATLAB, the model object is stored in the COMSOL server. You can
directly load the model object in the COMSOL Desktop or the opposite export the
model object available in the COMSOL Desktop to the COMSOL server.
EXPORTING A MODEL TO MATLAB FROM THE COMSOL DESKTOP

In the COMSOL Desktop you can use the option Export to Server from the File menu
in order to send the model object to the COMSOL server that is connected with
MATLAB. Once you have the model object in the COMSOL server you need to create
a link in the MATLAB prompt.
1 From the File menu, select Open Model Library.
2 Navigate to COMSOL Multiphysics>Equation-based Models and double-click
shell_diffusion to open it.
3 From the File menu, select Client server > Export Model to Server.
4 The Server and the Port to use have to be specified (default values are localhost

and 2036). In order to connect to the server you need to enter the Username and a
Password; these are defined the first time you connect to the COMSOL server.

15 |

CHAPTER 1: INTRODUCTION

Finally you can define the name of the model object to export (default name is
Model).

5 Click OK.
6 In MATLAB, create a link to the model object in the COMSOL server by entering

the command:
model = ModelUtil.model('Model');

Note: If the model object is exported to the COMSOL server with a different name,
replace Model with the name of the model exported to the COMSOL server. It is
possible to obtain the list of the model object available in the COMSOL server with
the command: ModelName = ModelUtil.tags

I M P O R T I N G A M O D E L I N T H E C O M S O L D E S K T O P F RO M M AT L A B

To import a model defined in a COMSOL server to the COMSOL Desktop, use the
Import Model from Server from the File menu. This window is similar to the Client
server>Export Model to Server window.

GETTING STARTED

16

Note: You can have several model objects on a server, which is why the name of the
model to import is mandatory for the import procedure.

COMSOL 3.5a Model Conversion


This section describes how to convert COMSOL 3.5a Model M-files to the version 4
format.
S T A R T I N G M AT L A B I N C O M P A T I B I L I T Y M O D E

To support the conversion from COMSOL 3.5a there is a separate launcher available,
which lets you run models represented in 3.5a syntax along with version 4 models
using the LiveLink interface. To start MATLAB in compatibility mode, use the
following:
Windows: Select COMSOL with MATLAB (COMSOL 3.5a Compatibility) under COMSOL 4.2
from the Windows Start menu.
Linux and Mac OS X: Start COMSOL with MATLAB with the command
comsol matlab -compat -c35aroot <COMSOL 3.5a root directory>

After starting MATLAB in this way, you have access to all documented functionality in
COMSOL 3.5a from MATLAB as well as the functionality in the LiveLink interface.
If you are using a recent version of MATLAB, make sure that all necessary updates of
COMSOL 3.5a are applied. Go to the COMSOL web site http://www.comsol.com/
support/updates to check for updates.
You find more information regarding the conversion process in the section M-File
Conversion.
CONVERTING MODELS

There are two ways you can migrate your models. This can be done with the command
mphv4 when running COMSOL with MATLAB (3.5a compatibility).
The mphv4 command converts the COMSOL 3.5a FEM structure to a COMSOL 4.2
model object. External operations done with the FEM structure are not converted.

17 |

CHAPTER 1: INTRODUCTION

To convert your M-file, run it one of two ways:


Run the 3.5a M-file. Save the resulting FEM structure as an MPH-file using 3.5a
Java functionality. Use the mphv4 utility to convert the model. This should restore
all fields from the FEM structure in the model object.
% Run old model
fem=...
% Convert model
model=mphv4(fem);

Modify the 3.5a M-file to create a @femgui object instead of a FEM structure. Run
the M-file. Use the mphv4 utility to convert the model. This restores all fields from
the FEM structure as well as meshing, solving, and postprocessing settings.
fem=femgui;
% Run rest of old model
fem=...
% Convert model
model=mphv4(fem);

After converting your model to a model object, save it both as an MPH file and as an
M-file.
CORRESPONDING WRAPPER FUNCTIONS IN 3.5A

Some wrapper functions are available to work directly with the COMSOL 4.2 model
object. The table below shows the correspondence between equivalent 3.5a and 4.2
functions:
TABLE 1-1: CORRESPONDING WRAPPER FUNCTIONS IN 3.5A AND 4.2
COMSOL 3.5A

COMSOL 4.2

posteval

mpheval

geomplot

mphgeom

postglobal

mphglobal

postint

mphint

postinterp

mphinterp

assemble

mphmatrix

meshplot

mphmesh

femstate

mphstate

GETTING STARTED

18

Calling External MATLAB Functions in the COMSOL Desktop


You can use external MATLAB functions in the COMSOL Desktop. Start a COMSOL
Desktop and MATLAB automatically starts to evaluate the functions. MATLAB
requires the function directory path, and then results are available in the COMSOL
Desktop.
On Windows, COMSOL uses the latest installed MATLAB to evaluate MATLAB
functions.
On Linux and Mac OS X, COMSOL needs to be started with the option -mlroot
as comsol -mlroot MATLAB_ROOT. This is normally set up during installation, but
you may need to specify this manually, for example, if you have not specified the
correct MATLAB path during installation. On Linux, you need to put the MATLAB
executable in the path as well.

User-Defined GUIs
You can use the MATLAB GUIDE functionality to generate a user-defined GUI
combined with a COMSOL model, such as in the following figure:

A MATLAB M-file can be used to set up the GUI components and update the model
object. See the GUIDE help in MATLAB for more information.

19 |

CHAPTER 1: INTRODUCTION

Startup of COMSOL with MATLAB


When COMSOL is started with MATLAB using the icon (on Windows or Mac) or
using the commend line (on all platforms)
comsol server matlab

A few files are used to set things up properly. In the directory <COMSOLINSTALLDIR>/
mli/startup you can find two files.
java.opts is used to control the amount of memory that is reserved for Java inside
of MATLAB. This amount has to be increased from its default values in order to
accommodate large models and large amounts of that sometimes is transferred
between MATLAB and COMSOL. You can increase the number even further if you
often run out of memory (Java heap space). Notice that increasing the values too
much leaves less memory to perform calculations in MATLAB.
startup.m is a file that is run by MATLAB once every time it starts. By default, this
file does only writes some welcome text on the screen, or add your own commands
at the end. However, the preferred way to add commands to the startup procedure
is to create a file called comsolstartup.m in your home directory or in a directory
on the MATLAB path.

Running COMSOL with MATLAB in Batch Mode


Run COMSOL with MATLAB in batch mode with the command:
comsol server matlab myscript

where myscript is the script to run at the MATLAB prompt.


To run COMSOL with MATLAB in batch without the MATLAB Java desktop and
without the MATLAB splash, run the command:
comsol server matlab myscript -nodesktop -mlnosplash

Getting More Information


There are several sources to find more information about the LiveLink interface.
Access the on-line documentation with the command mphdoc.
This user guide describes the different parts of the model object and how these are
accessed from MATLAB.

GETTING STARTED

20

The COMSOL Java API Reference Guide contains reference documentation that
describes the methods in the Model object.
The section Command Reference describes additional utilities available for use with
LiveLink for MATLAB.

21 |

CHAPTER 1: INTRODUCTION

Building Models
This chapter gives an overview of the model object and provides an introduction
to building models using the LiveLink interface.
In this chapter:
The Model Object
Running the Model in a Loop

22

The Model Object


While working with the LiveLink interface in MATLAB you access models through the
model object. You use methods to create, modify, and access your model.
The model object includes the following parts:
All algorithms and data structures for the COMSOL 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 for setting up and running sequences of
operations to create geometry, meshes, and for solving your model.
LiveLink for MATLAB uses the COMSOL Java API, which is a Java-based
programming interface to COMSOL. In addition, the product includes a number of
M-file utility functions.
In this section:
Model Object Methods
Information About the Model Object
A Simple Model Example
Utility Functions
Using the On-Line Documentation
Using MATLAB Functions in COMSOL Multiphysics

Model Object Methods


The model object provides a large number of methods. The methods are structured in
a tree-like way, much similar to the nodes in the model tree in the Model Builder
window on the COMSOL Desktop. The top-level methods just return references that
support further methods. At a certain level the methods perform actions, such as

23 |

CHAPTER 2: BUILDING MODELS

adding data to the model object, performing computations, or returning data. The
following list outlines the use of the model objects top-level methods:
TABLE 2-1: TOP-LEVEL METHODS IN THE MODEL OBJECT
FUNCTION

PURPOSE

model.batch

Run several jobs in a sequence automatically

model.coeff

Manipulate coefficient form contributions

model.constr

Manipulate constraints

model.coordSystem

Manipulate coordinate systems

model.cpl

Manipulate coupling variables

model.elem

Manipulate elements

model.field

Manipulate fields

model.frame

Manipulate frames

model.func

Manipulate functions

model.geom

Manipulate geometry

model.intRule

Manipulate integration orders

model.init

Manipulate initial values

model.material

Manipulate materials

model.mesh

Manipulate meshes

model.modelNode

Manipulate model nodes

model.ode

Manipulate global equation

model.opt

Manipulate optimization

model.pair

Manipulate pairs

model.param

Manipulate model parameters

model.physics

Manipulate physics interfaces

model.probe

Manipulate probes

model.result

Manipulate result objects

model.selection

Manipulate domain selections

model.shape

Manipulate shape functions

model.sol

Manipulate solutions

model.study

Manipulate studies

model.unitSystem

Manipulate units

model.variable

Manipulate variables

model.weak

Manipulate weak form contributions

THE MODEL OBJECT

24

You find detailed documentation of model object methods in the COMSOL Java API
Reference Guide.

Information About the Model Object


You can inspect data in the model object by entering a method name and an optional
argument without ending the command with a semicolon. As a result, the program
prints information about the data stored in the model object. Enter the following
simple model with a square geometry and look at the information about the model:
model = ModelUtil.create('Model');
model.geom.create('geom1', 2);
model.geom('geom1').feature.create('sq1', 'Square');
model.geom('geom1').run;

To display information about the root node of the model, return a reference to the
model, for example, by entering a variable name without ending the command with a
semicolon:
>> model
COMSOL Model Object
Name: Untitled.mph
Tag: Model
Identifier: root

The name of the root node is the file name associated with the model. The tag of the
root node is the same name when the model object is created. The node identifier is
used to refer to the root scope in multiphysics expressions. Determine the geometries
of your model by entering:
>> model.geom
Type: List
Child tags: geom1

To get a Java array of the geometry tags, enter


>> model.geom.tags
java.lang.String[]:
'geom1'

The printout lists the tags of the geometry nodes. The single geometry node is the
geometry that was just created. To display more information about the geometry,
enter:
>> model.geom('geom1')

25 |

CHAPTER 2: BUILDING MODELS

Type: Geometry
Tag: geom1
Dimension: 2
Current child: sq1
Child nodes: sq1, fin

The geometry node is of type Geometry. You specified its tag when you create the
geometry. It does not have an identifier because you cannot use the node in
expressions. The printout also contains the dimension of the geometry, the geometrys
current node, and the child nodes. You can also obtain its child nodes by entering:
>> model.geom('geom1').feature
Type: List
Child tags: sq1, fin

To get a Java array the tags of the geometry features, enter


>> model.geom('geom1').feature.tags
java.lang.String[]:
'sq1'
'fin'

The printout lists the tags of the feature nodes in the geometry sequence. Its child
nodes are the square that we just created and the default finalize node. List information
about the square by entering:
>> model.geom('geom1').feature('sq1')
Type: Square
Tag: sq1
Identifier: sq1
Operation: Square
Status: built

The Square feature is built. You can also determine the tag of the node and its
identifier.
Note that you can also define the tag as a JAVA string object:
tags=model.geom('geom1').feature.tags;
model.geom('geom1').feature(tags(1));

A Simple Model Example


Lets start with a simple model that solves an electrostatics problem on a square. The
lower boundary is grounded and add a charge distribution is set on the right side
boundary.

THE MODEL OBJECT

26

Start by initializing the root model.


model = ModelUtil.create('Model');

Enter the following commands to create a 2D geometry node with a square node.
% Create the geometry
model.geom.create('geom1', 2);
model.geom('geom1').feature.create('sq1', 'Square');
model.geom('geom1').run;

Display the geometry in a MATLAB figure with the mphgeom command.


mphgeom(model,'geom1')

Continue by meshing the geometry with a free triangular mesh.


% Create the mesh
model.mesh.create('mesh1', 'geom1');
model.mesh('mesh1').feature.create('fre1', 'FreeTri');
model.mesh('mesh1').run;

Examine the mesh by entering


model.mesh('mesh1')

Which results in the output:


Type: Mesh
Tag: mesh1
Current child node: fre1
Number of child nodes: 2

You can also display the mesh in a MATLAB figure with the mphmesh command.
mphmesh(model,'mesh1')

Now set up the physics. First manually set the relative permittivity r in the default
Charge conservation node (defined with the tag ccn1). Then ground the lower
boundary and add a charge distribution on the right boundary. You can use a
temporary variable es to make the lines shorter.
% Setup physics
model.physics.create('es', 'Electrostatics', 'geom1');
model.physics('es').feature('ccn1').set('epsilonr_mat', 1,
'userdef');
model.physics('es').feature.create('gnd1', 'Ground', 1);
model.physics('es').feature('gnd1').selection.set([2]);
model.physics('es').feature.create('sfcd1',
'SurfaceChargeDensity', 1);
model.physics('es').feature('sfcd1').selection.set([4]);
model.physics('es').feature('sfcd1').set('rhoqs', 1, '1e-10');

27 |

CHAPTER 2: BUILDING MODELS

The study helps you set up solver defaults. Just run the study to set up the defaults and
solve the model.
% Create the study
model.study.create('std1');
model.study('std1').feature.create('stat1', 'Stationary');
model.study('std1').run;

Set up a plot group and plot.


% Create a plot group
model.result.create('pg1', 2);
model.result('pg1').set('data', 'dset1');
model.result('pg1').feature.create('surf1', 'Surface');
mphplot(model,'pg1');

To get the plot with the color range use mphplot(model,'pg1','rangenum',1).


Save the model on file and continue modeling in the COMSOL Desktop:
model.save('model1');

as well as saving the model on M-file format:


model.save('model1','m');

You can reduce the syntax by creating a MATLAB object:


pg1 = model.result.create('pg1', 2);

The node can then be manipulated with the variable pg1:


pg1.set('data', 'dset1');

You can also do the same with a subfeature:


surf1 = pg1.feature.create('surf1', 'Surface');

THE MODEL OBJECT

28

If the feature already exists in the model object you can also assign a shortcut variable
name:
std1 = model.study('std1');
std1.feature.create('stat1', 'Stationary');

In this user guide the reduced syntax is used. When saving a model as an M-file the full
syntax is always provided.

Utility Functions
In addition to the methods in the model object, LiveLink for MATLAB includes the
following M-file utility functions.
TABLE 2-2: M-FILE UTILITY FUNCTIONS
NAME

PURPOSE

mphdoc

Return HTML help of a specified function

mpheval

Evaluate expressions on node points

mphgeom

Plot a geometry in a MATLAB figure

mphgetadj

Return geometry entities that are adjacent to other

mphgetcoords

Return point coordinates of geometry entities

mphgetp

Obtain information about a solution

mphgetu

Return solution vector

mphglobal

Evaluate global quantities

mphint

Perform integration of expressions

mphinterp

Evaluate expressions in arbitrary points or data sets

mphload

Load a COMSOL model file (mph)

mphmatrix

Get model matrices

mphmesh

Plot mesh in a MATLAB figure window

mphselectbox

Select geometric entity using a rubberband/box

mphselectcoords

Select geometric entity using point coordinates

mphplot

Render a plot group in a figure window

mphstart

Connect MATLAB to a COMSOL server

mphstate

Get state-space matrices for dynamic systems

mphv4

Convert a FEM structure or FEMGUI object to model object

You find more information about these functions in the Command Reference.

29 |

CHAPTER 2: BUILDING MODELS

Using the On-Line Documentation


For the model object, there is a utility function mphdoc to help you browse the
documentation of the model object in the MATLAB help browser. Assuming you have
entered the example from the section above, A Simple Model Example, you can enter
mphdoc
mphdoc
mphdoc
mphdoc
mphdoc

model;
model.geom;
model.geom('geom1');
model.geom('geom1').feature;
model.geom('geom1').feature('sq1');

and
mphdoc
mphdoc
mphdoc
mphdoc

model.physics;
model.physics('es');
model.physics('es').feature;
model.physics('es').feature('glm1');

You can also access subfeature documentation with the following syntax
mphdoc model Rectangle
mphdoc model Sphere
mphdoc model FreeTri

All these commands provide useful information about the different parts of the model
object in the MATLAB help browser.
To get help with the M-file utility functions in the product, use the MATLAB help
command, for example,
help mphplot

Alternatively find more information about the functions in Command Reference.

Using MATLAB Functions in COMSOL Multiphysics


Use MATLAB M-function in the COMSOL model to define model settings such as
parameters, material properties, boundary conditions, and so forth. To be able to
evaluate these functions you need to declare them in the COMSOL model using the
MATLAB feature node available with the Global Definitions.

THE MODEL OBJECT

30

Note: To call a MATLAB function from within the model object you do not need to
start COMSOL with MATLAB, starting the COMSOL Desktop is sufficient. The
MATLAB process starts automatically to evaluate the function.

D E F I N E A N EX T E R N A L M AT L A B F U N C T I O N I N T H E C O M S O L M O D E L

To evaluate a MATLAB M-function from within the COMSOL model you need to
add a MATLAB node in the model object where you define the function name, the list
of the arguments and, if required, the function derivatives.
The Settings window of the MATLAB node consists of a table where the function
name and the list of the arguments are entered.
If necessary you can expand the Derivatives section to define the derivatives of the
function with respect to the function arguments.
For example, to define assume that you want to use MATLABs Bessel function of the
third kind (Hankel function) in COMSOL Multiphysics define the following settings:
FUNCTION NAME

ARGUMENTS

EXPRESSION

DERIVATIVES

besselh

nu,x

besselh(nu,x)

0,(besselh(nu-1,x)
-besselh(nu+1,x))/2

bessel

besselh(1,x)

(besselh(0,x)
-besselh(2,x))/2

1 Under the Functions section, enter besselh in the Function column and nu, x in

the Arguments column.


2 Enter bessel in the second line of the Function column and x in the corresponding
Arguments column.
3 Under the Derivatives section, enter besselh in the column and nu in the Argument

column,
4 Define the partial derivative value: enter 0 in the Partial derivative column.
5 Proceed the same way with second partial derivative. Enter besselh in the Function

column, x in the Argument column and (besselh(nu-1,x) -besselh(nu+1,x))/


2 in the Partial derivative column.
6 Define the derivative of bessel with respect to x, enter bessel in the Function

column, x in the Argument column and in the (besselh(0,x) -besselh(2,x))/


2 Partial derivative column.

31 |

CHAPTER 2: BUILDING MODELS

With this definition, COMSOL can evaluate the functions. When the function value is
requested, a MATLAB process automatically starts and evaluates the function, the
values are then returned to the COMSOL model.
Note that the function path needs to be known by MATLAB. In you are calling a user
defined M-function, you can either set the path in MATLAB before running the
COMSOL model, or save the M-functions at the same location where the COMSOL
model mph-file is saved. An alternative is to define the system environment variable
COMSOL_MATLAB_PATH with the path of the user defined function.
USING THE COMMAND LINE

When running COMSOL with MATLAB, you can directly define a parameter with an
M-function by declaring the parameters with the function. Do NOT include it within
quotes '', for example, assume that the parameter E0 is defined with the M-function
my_fun.m, and then define it with the command line:
model.param.set('E0',my_fun(a,b));

where a and b are MATLAB variables available in the MATLAB workspace.

THE MODEL OBJECT

32

If you want to call the M-function with variables defined from within the COMSOL
model object, then add a MATLAB node in the model, for example:
model.func.create('extm1', 'MATLAB');
model.func('extm1').setIndex('funcs', 'my_fun', 0, 0);
model.func('extm1').setIndex('funcs', 'x, y', 0, 1);

model.param.set('E0', 'my_fun(x,y)');

With these commands, the parameter E0 is defined with the function my_fun using
COMSOL variables x and y as arguments.
FUNCTION INPUT/OUTPUT CONSIDERATIONS

The functions called from COMSOL must support vector arguments of any length.
COMSOL calls your MATLAB function using vector arguments because the number
of expensive calls from COMSOL to MATLAB can be reduced this way. All common
MATLAB functions such as sin, abs, and other mathematical functions support
vector arguments.
When you write your own functions for specifying inhomogeneous materials, logical
expressions, time-dependent sources, or other model properties, 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. Values can be real or complex.
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

This function looks good at first but it does not work in COMSOL Multiphysics
because the input x is a matrix.
You must use element-by-element multiplication, division, and power, that is, the
operators .*, ./, and .^. Replace expressions such as x/1.6 and x^2+0.3 with x./
1.6 and x.^2+0.3, respectively.
The comparison x 0.6 returns a matrix with ones (true) for the entries where the
expression holds true and zeros (false) where it is false. The function evaluates the
conditional statement if and only if all the entries are true (1).

33 |

CHAPTER 2: BUILDING MODELS

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 . All in all,
the function could look like this:
function c = func2(x)
c = (x./1.6).*(x>0.6) + (x.^2+0.3).*(x<=0.6);

THE MODEL OBJECT

34

Running the Model in a Loop


You can also run the model in a loop and automatically change the value of one or
several parameters within the model. You can run a loop from within the model object
using the COMSOL functionality or run the loop outside the model object using
MATLAB tools.
In this section:
Running a Loop within the COMSOL Model Object
Running a Model in a Loop Using MATLAB Tools

Running a Loop within the COMSOL Model Object


For a stationary or frequency domain study step you can add a parametric feature to
the solver configuration. In the parametric feature definitions, set one or several
parameters and define the value to solve the model for.
To add a parametric feature to a solver study step, enter the command:
model.sol(<solname>).feature(<fname>).feature.create('p1',
'Parametric');

Define the parameter to update in the Parametric feature and set the value to solve for:
model.sol(<solname>).feature(<fname>).feature('p1').set('pname',
<pname>);
model.sol(<solname>).feature(<fname>).feature('p1').set('plist',
<plist>);

To automatically vary the value of geometry settings or to combine a parametric


analysis with a time-dependent or eigenfrequency study, create a batch node that
contains a parametric feature.
To create a batch node enter the command:
model.batch.create('p1', 'Parametric');

Define the parameter to update in the Parametric feature and set the value to solve for:
model.batch('p1').set('pname', {<pname>});
model.batch('p1').set('plist', <plist>);

Link the batch node to the study and set the solution to store:
model.batch('p1').study('std1');

35 |

CHAPTER 2: BUILDING MODELS

model.batch('p1').feature.create('so1', 'Solutionseq');
model.batch('p1').feature('so1').set('seq', <solname>);
model.batch('p1').feature('so1').set('store', 'on');

Create a second solution which includes the solution for each batch parameter value:
model.sol.create('sol2');
model.sol('sol2').study(<stdname>);
model.batch('p1').feature('so1').set('psol', 'sol2');

To solve the batch node run the command:


model.batch('p1').run;
EXAMPLE

This example illustrates how to set up a continuation feature to an existing solver study
step and compute for solution for several parameter values.
% Load the busbar model from the Model library:
model = mphload('busbar');
% Create a link to the stationary study step 's1':
s1 = model.sol('sol1').feature('s1');
% Add a Parametric feature to the study step 's1':
p1 = s1.feature.create('p1', 'Parametric');
% Set the parameter name to use in the study step 's1':
p1.set('pname', {'Vtot'});
% Set the parameter value:
p1.set('plist', '20[mV] 40[mV]');
% Run the solver node 'sol1':
model.sol('sol1').run

Evaluate the temperature at (0.1,-2.5e-2, 5.1e-2) corresponding to both electric


potential values:
Temp = mphinterp(model,'T','coord',[0.1;-2.5e-2;5.1e-2])

This should return:


Temp =
326.5389
426.7054

Add a parametric sweep to the study node and define the width variable of the busbar
wbb as parameter to update and set two values in the parameter list.
% Add a batch node to the model:
p1 = model.batch.create('p1', 'Parametric');
% Set the parameter name to use:
p1.set('pname', {'wbb'});
% Set the parameter values:
p1.set('plist', '5[cm] 10[cm]');

RUNNING THE MODEL IN A LOOP

36

% Create a solution sequence:


so1 = p1.feature.create('so1', 'Solutionseq');
p1.feature('so1').set('seq', 'sol1');
so1.set('store', 'on');
% Create a second solver node and attach the study std1 to it:
sol2 = model.sol.create('sol2');
sol2.study('std1');
% Set the solution sequence with the solution copmputed by sol2
so1.set('psol', 'sol2');
% Run the bqatch node
p1.run

The model contains a parametric study: one for the electric potential and one for the
geometry. For each geometry the solution is available as an outer solution.
To evaluate the temperature at (0.1,-2.5e-2, 5.1e-2) for the first geometry case (wbb
is set to 5 cm), enter the command:
Temp = mphinterp(model,'T','coord',[0.1;-2.5e-2;5.1e-2],...
'dataset','dset2','outersolnum',1);

Which returns the values:


Temp =
326.5389
426.7054

To evaluate the temperature at (0.1,-2.5e-2, 5.1e-2) for the second geometry case
(wbb is set to 10 cm), enter the command:
Temp = mphinterp(model,'T','coord',[0.1;-2.5e-2;5.1e-2],...
'dataset','dset2','outersolnum',2);

Which returns the values:


Temp =
309.3729
358.0418

Running a Model in a Loop Using MATLAB Tools


As an alternative to the COMSOL parametric feature, you can run models in a loop
using MATLAB tools. For example, use the FOR loop to parametrize your model. The
set method support MATLAB variable as input, so you only need to modify the model
according to your requirements.

37 |

CHAPTER 2: BUILDING MODELS

Note: You do not need to run the entire M-file in the loop that sets up the model
object. It is sufficient to load the model object and only modify the parameter that
needs to be changed.

EXAMPLE

In this example use the busbar model from the Model Library and change some
parameters in a loop. The modified parameters are the geometry width and the electric
potential. Then evaluate the temperature at (0.1,-2.5e-2, 5.1e-2) for each cases.
% Load the model:
model = mphload('busbar');
Temp = {};
% Start the loop for the geometry parameter:
for width = [5e-2 10e-2]
% Start the loop for the electric potential:
for V = [20e-3 40e-3]
% Update the parameter values:
model.param.set('wbb',width);
model.param.set('Vtot',V);
% Compute the solution:
model.sol('sol1').run;
% Evaluate the temperature:
Temp = [Temp
mphinterp(model,'T','coord',[0.1;-2.5e-2;5.1e-2])];
end
end

The variable Temp contains the temperature for each case:


Temp =
[326.5389]

[426.7054]

[309.3729]

[358.0418]

RUNNING THE MODEL IN A LOOP

38

39 |

CHAPTER 2: BUILDING MODELS

Creating Geometries
This section introduces you to Geometry Sequences and how to build them using
the LiveLink interface.

40

Geometry Sequences
This section describes how to set up and run a geometry sequence. For additional
information on geometry modeling, see the section Geometry Modeling and CAD
Tools in the COMSOL Multiphysics Users Guide.
You find reference information on geometry operations in Geometry API in the
COMSOL Java API Reference Guide.
In this section:
The Geometry Sequence Syntax
Working with Geometry Sequences
Exchanging Geometries with the COMSOL Desktop
Importing and Exporting Geometries and CAD Models from File
Retrieving Geometry Information
Modeling with a Parameterized Geometry
Images and Interpolation Data

The Geometry Sequence Syntax


Create a geometry sequence by using the syntax
model.geom.create(<tag>,<sdim>);

where <tag> is a string that you use to refer to the geometry. The integer <sdim>
specifies the space dimension of the geometry.
To add an operation to a geometry sequence, use the syntax
model.geom(<tag>).feature.create(<ftag>,operation);

where <tag> is the string you defined when creating the geometry. The string <ftag>
is a string that you use to refer to the operation. To set a property to a value in an
operation, enter
model.geom(<tag>).feature(<ftag>).set(property,<value>);

where <ftag> is the string you defined when creating the operation.
Finally to build the geometry sequence, enter
model.geom(<tag>).run;

41 |

CHAPTER 3: CREATING GEOMETRIES

You find further details on available operations and properties in the geometry
sequence in Geometry API in the COMSOL Java API Reference Guide.
You can plot the geometry in MATLAB using the function mphgeom:
mphgeom(model,<tag>);

that plots the geometry tagged <tag> at its current state.

Working with Geometry Sequences


This section shows how to create geometry sequences in different space dimensions
using the syntax outlined in The Geometry Sequence Syntax.
CREATING A 1D GEOMETRY

For more information about 1D geometry modeling in COMSOL Multiphysics, see


Creating a 1D Geometry Model in the COMSOL Multiphysics Users Guide. From
the MATLAB command prompt, create a 1D geometry model by adding a geometry
sequence, add geometry features, and run the sequence using the run method.
Remember, before starting you need to create a model object using
model = ModelUtil.create('Model');

For example, the commands


geom1 = model.geom.create('geom1',1);
i1=geom1.feature.create('i1','Interval');
i1.set('intervals','many');
i1.set('p','0,1,2');
geom1.run;

create a geometry sequence with a 1D solid object consisting of vertices at x = 0, 1, and


2, and edges joining the vertices adjacent in the coordinate list.
entering
p1=geom1.feature.create('p1','Point');
p1.set('p',0.5);
geom1.run;

adds a 1D point object located at x = 0.5 to the 1D geometry.


To plot the result, enter

GEOMETRY SEQUENCES

42

mphgeom(model,'geom1','vertexmode','on')

CREATING A 2D GEOMETRY USING SOLID MODELING

For more information about 2D geometry modeling in COMSOL Multiphysics, see


Creating a 2D Geometry Model in the COMSOL Multiphysics Users Guide. You can
set up the geometry discussed in that example using Boolean operations from the
command line.

Creating Composite Objects


First, create a rectangle with a hole in it. Make sure you have a model object with a 2D
geometry.
model = ModelUtil.create('Model');
geom2 = model.geom.create('geom2',2);

Continue by creating a rectangle object with side length of 2 and centered at the
origin:
sq1 = geom2.feature.create('sq1','Square');
sq1.set('size',2);
sq1.set('base','center');

The property size describes the side lengths of the rectangle, and the property pos
describes the positioning. The default is to position the rectangle about its lower left
corner. Use the property base to control the positioning.
Create a circular hole with a radius of 0.5 centered at (0, 0):
c1 = geom2.feature.create('c1','Circle');
c1.set('r',0.5);
c1.set('pos',[0 0]);

43 |

CHAPTER 3: CREATING GEOMETRIES

The property r describes the radius of the circle, and the property pos describes the
positioning. The property pos could have been left out because the default position is
the origin. The default is to position the circle about its center.
Drill a hole in the rectangle by subtracting the circle from it:
co1 = geom2.feature.create('co1','Compose');
co1.selection('input').object('geom2');
co1.selection('input').set({'c1' 'sq1'});
co1.set('formula','sq1-c1');

A selection object is used to refer to the input object. The operators +, *, and correspond to the set operations union, intersection, and difference, respectively.
This example shows how to use the Compose operation and a set formula. Alternatively,
you can use the Difference operation instead of Compose.
If you have already added the above compose operation, you need to disable it first
before adding the Difference operation.
co1.active(false)
dif1 = geom2.feature.create('dif1','Difference');
dif1.selection('input').object('geom2');
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');

GEOMETRY SEQUENCES

44

Trimming Solids
To remove the corners and replace with rounded corners, add a fillet operation to the
sequence:
fil1 = geom2.feature.create('fil1','Fillet');
fil1.selection('point').object('geom2',0);
fil1.selection('point').set('dif1', [1 2 7 8]);
fil1.set('radius','0.5');

Run the sequence again:


geom2.run;

The geometry sequence is updated with rounded corners. To view the result, enter
mphgeom(model,'geom2');

CREATING A 2D GEOMETRY USING BOUNDARY MODELING

Use the following commands to create six open curve segments that together form a
closed curve.
model = ModelUtil.create('Model');
g1 = model.geom.create('g1',2);
w=1/sqrt(2);
c1 = g1.feature.create('c1','BezierPolygon');
c1.set('type','open');
c1.set('degree',2);
c1.set('p',[-0.5 -1 -1;-0.5 -0.5 0]);
c1.set('w',[1 w 1]);
c2 = g1.feature.create('c2','BezierPolygon');
c2.set('type','open');
c2.set('degree',2);
c2.set('p',[-1 -1 -0.5;0 0.5 0.5]);

45 |

CHAPTER 3: CREATING GEOMETRIES

c2.set('w',[1 w 1]);
c3 = g1.feature.create('c3','BezierPolygon');
c3.set('type','open');
c3.set('degree',1);
c3.set('p',[-0.5 0.5; 0.5 0.5]);
c4 = g1.feature.create('c4','BezierPolygon');
c4.set('type','open');
c4.set('degree',2);
c4.set('p',[0.5 1 1; 0.5 0.5 0]);
c4.set('w',[1 w 1]);
c5 = g1.feature.create('c5','BezierPolygon');
c5.set('type','open');
c5.set('degree',2);
c5.set('p',[1 1 0.5; 0 -0.5 -0.5]);
c5.set('w',[1 w 1]);
c6 = g1.feature.create('c6','BezierPolygon');
c6.set('type','open');
c6.set('degree',1);
c6.set('p',[0.5 -0.5; -0.5 -0.5]);

Convert the curve segments to a solid by the following conversion command.


csol1 = g1.feature.create('csol1','ConvertToSolid');
csol1.selection('input').object('g1');
csol1.selection('input').set({'c1' 'c2' 'c3' 'c4' 'c5' 'c6'});

Then issue a final run command.


g1.run;
mphgeom(model,'g1');

The last command displays the geometry in a MATLAB figure window.

GEOMETRY SEQUENCES

46

The objects c1, c2, c3, c4, c5, and c6 are all curve2 objects. The vector [1 w 1]
specifies the weights for a rational Bzier curve that is equivalent to a quarter-circle arc.
The weights are adjusted to create elliptical or circular arcs.
CREATING 3D GEOMETRIES USING SOLID MODELING

For more information about 3D geometry modeling, see Creating a 3D Geometry


Model in the COMSOL Multiphysics Users Guide. This section demonstrates the use
of Boolean operations on solid objects from the command line.
Create a 3D geometry with an xy work plane at z = 0:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 3);
wp1 = geom1.feature.create('wp1', 'WorkPlane');
wp1.set('planetype', 'quick');
wp1.set('quickplane', 'xy');

Add a rectangle to the work plane, then add fillets to all its corners:
r1 = wp1.geom.feature.create('r1', 'Rectangle');
r1.set('size',[1 2]);
geom1.run
fil1 = wp1.geom.feature.create('fil1', 'Fillet');
fil1.selection('point').set('r1', [1 2 3 4]);
fil1.set('radius', '0.125');
geom1.runCurrent;
ext1 = geom1.feature.create('ext1', 'Extrude');
ext1.set('distance', '0.1');

Add another yz work plane, at x = 0.5:


wp2 = geom1.feature.create('wp2', 'WorkPlane');
wp2.set('planetype', 'quick');
wp2.set('quickplane', 'yz');
wp2.set('quickx', '0.5');
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'});
wp2.geom.feature.create('csol1', 'ConvertToSolid');
wp2.geom.feature('csol1').selection('input').set({'b1'});

Revolve the triangle from the yz work plane:


rev1 = geom1.feature.create('rev1', 'Revolve');
rev1.selection('input').set({'wp2'});
rev1.setIndex('pos', '1', 0);

47 |

CHAPTER 3: CREATING GEOMETRIES

Add the difference operation that computes the final 3D geometry.


dif1 = geom1.feature.create('dif1', 'Difference');
dif1.selection('input2').object('geom1');
dif1.selection('input').object('geom1');
dif1.selection('input').set({'ext1'});
dif1.selection('input2').set({'rev1'});

To run the sequence, enter


model.geom('geom1').run;

To view the geometry enter


mphgeom(model,'geom1');

Exchanging Geometries with the COMSOL Desktop


EXCHANGING A GEOMETRY FROM COMSOL DESKTOP

To transfer a geometry from COMSOL Desktop to the LiveLink interface in


MATLAB use one of the following methods:
Export the geometry as a COMSOL Multiphysics binary (.mphbin) file from the
COMSOL Desktop. Right-click geometry sequence and select Export to File. Create
a geometry import feature from MATLAB
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 3);
imp1 = geom1.feature.create('imp1','Import');
imp1.set('filename','geometryfile.mphbin');
imp1.importData;

GEOMETRY SEQUENCES

48

geom1.run;

Create a model with the geometry sequence. Save the model from the COMSOL
Desktop. Create a model object from MATLAB and load the file into it.

Importing and Exporting Geometries and CAD Models from File


With COMSOL Multiphysics, you can import and export geometries in a variety of file
formats. Below is a short summary of the various file formats.
COMSOL MULTIPHYSICS FILES

A natural choice for storing geometries in 1D, 2D, and 3D is the native file format of
COMSOLs geometry kernel (.mphtxt, .mphbin).

Note: This file format is only used for geometry and mesh objects. It is not the same
as a Model MPH-file (.mph).

2D CAD FORMATS

COMSOL Multiphysics supports import and export for the DXF file format, a data
interchange format of the CAD system AutoCAD . You can also import files in the
neutral GDS format.
3D CAD FORMATS

It is possible to import surface meshes in the STL and VRML formats. COMSOL also
provides a CAD Import Module, which supports import of most 3D CAD file formats:
Parasolid, ACIS (SAT), STEP, IGES, Pro/ENGINEER, Autodesk Inventor ,
and SolidWorks . The CAD Import Module Users Guide discusses these file formats
in detail.

Retrieving Geometry Information


To retrieve the detailed information about your geometry, see Geometry Object
Information in the COMSOL Java API Reference Guide.
Start by creating a simple 3D geometry:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 3);
geom1.feature.create('blk1','Block');

49 |

CHAPTER 3: CREATING GEOMETRIES

geom1.feature.create('con1','Cone');
geom1.run;

To visualize the geometry in a MATLAB figure window enter:


mphgeom(model,'geom1')

There are general geometry information methods. For example, to determine the
space dimension of the geometry, enter:
geom1.getSDim

There are also methods for determining the number of geometrical entities; for
example, inquire about the number of domains, and the number of boundaries:
geom1.getNDomains
geom1.getNBoundaries

Another group of geometry information methods concerns adjacency properties of the


geometric entities, for example, the number of up and down domain information on
each boundary:
geom1.getUpDown

There are also methods for evaluating properties, like coordinate values and curvatures
on faces and edges. This example evaluates coordinates and derivatives on face 1 for
parameter values (0.5, 0.5)
geom1.faceX(1,[[0.5,0.5]])
geom1.faceDX(1,[[0.5;0.5]])

To get the parameter length of edge number N you can use the edgeParamRange(N)
function, for instance to get the length of edge number 3 you just need to enter:

GEOMETRY SEQUENCES

50

geom1.edgeParamRange(3)

To get the coordinate and the curvature data along a specified edge:
geom1.edgeX(2,0.5)
geom1.edgeCurvature(2,0.5)

There are also methods for getting information about the geometry internal
representation, for example, the coordinates of the geometry vertices:
geom1.getVertex

In addition, you can fetch geometry information from elements in the geometry
sequence. To do this, you can, for example, enter
geom1.object('blk1').getNBoundaries

Modeling with a Parameterized Geometry


COMSOL has built-in support for parameterized geometries. Parameters can be used
in most geometry operations. To exemplify parameterizing a geometry, the following
script studies the movement of a circular source through two adjacent rectangular
domains:
model = ModelUtil.create('Model');
model.param.set('a','0.2');
geom1 = model.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'});
geom1.run;

51 |

CHAPTER 3: CREATING GEOMETRIES

mphgeom(model,'geom1');

Change the position of the circle by setting parameter a to another MATLAB value,
and re-run the geometry sequence:
model.param.set('a','0.5');
geom1.run;
mphgeom(model,'geom1');

Make a loop that changes the position of the circle.


for a=0.2:0.1:0.5
model.param.set('a',a);
geom1.run;
end

Create a mesh:

GEOMETRY SEQUENCES

52

model.mesh.create('mesh1', 'geom1');

Add a Weak Form PDE interface:


w = model.physics.create('w', 'WeakFormPDE', 'geom1');
w.feature('wfeq1').set('weak', 1, '-test(ux)*ux-test(uy)*uy');
dir1 = w.feature.create('dir1', 'DirichletBoundary', 1);
dir1.selection.set([1 2 3 6 7]);
src1 = w.feature.create('src1', 'SourceTerm', 2);
src1.set('f', 1, '1');
src1.selection.set([3]);

Then, create a stationary study step:


std1 = model.study.create('std1');
stat1 = std1.feature.create('stat1', 'Stationary');

Create a parametric sweep feature:


p1 = model.batch.create('p1','Parametric');
p1.set('pname', 'a');
p1.set('plist','range(0.2,0.1,0.8)');
p1.run;

Alternatively, you can run the parametric sweep using a MATLAB control statement:
for a=0.2:0.1:0.8
model.param.set('a',a);
std1.run;
end

Images and Interpolation Data


Unlike in version 3.5a, the LiveLink interface in version 4.2 does not contain geometry
editing based on image import or spline interpolation.
It is, however, possible to combine a COMSOL 3.5a geometry and a COMSOL 4.2
model object. COMSOL with MATLAB (3.5a compatibility) enables you to have both
COMSOL 3.5a and COMSOL 4.2 running with the same MATLAB prompt.
EXAMPLE: CREATING A GEOMETRY USING SPLINE INTERPOLATION

The following illustrates how to use COMSOL 3.5a function to create a geometry for
a COMSOL 4.2 model object:
1 Start COMSOL 4.2 with MATLAB (3.5a Compatibility). On Windows go to the start

menu All programs > COMSOL 4.2 > COMSOL 4.2 with MATLAB (3.5a Compatibility). On
Linux/Mac enter at a terminal window the command
comsol server matlab -compat -c35aroot=<dir>/COMSOL35a

53 |

CHAPTER 3: CREATING GEOMETRIES

Where <dir> is the home directory where COMSOL Multiphysics 3.5a is installed.
2 Create a circle data, 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)];

3 Add some noise to the data points.


randn('state',17)
p = p+0.01*randn(size(p));

4 Use the command geomspline with a uniform parameterization technique.


c = geomspline(p,'splinemethod','uniform','closed','on');

5 Create a square geometry object and create a composite geometry with the two

geometry objects available at the command prompt:


s = rect2(3,3,'pos',[-1.5;-1.5]);
geom = geomcsg({c,s});

6 Create a FEM structure with the geometry and convert it to a model object with

the mphv4 command:


fem.geom = geom;
model = mphv4(fem);

7 You can plot the geometry with the mphplot command:


mphplot(model,'geom1');

GEOMETRY SEQUENCES

54

8 Continue the implementation of the model using COMSOL 4.2 syntax:


mesh1 = model.mesh.create('mesh1', 'geom1');
mesh1.feature.create('ftri1', 'FreeTri');
mesh1.run;
ht = model.physics.create('ht', 'HeatTransfer', 'geom1');
ht.feature('solid1').set('k_mat', 'userdef');
ht.feature('solid1').set('k', {'400'});
ht.feature('solid1').set('rho_mat', 'userdef');
ht.feature('solid1').set('rho', '8700');
ht.feature('solid1').set('Cp_mat', 'userdef');
ht.feature('solid1').set('Cp', '385');
hs1 = ht.feature.create('hs1', 'HeatSource', 2);
hs1.set('Q', '1e5');
hs1.selection.set([2]);
temp1 = ht.feature.create('temp1', 'TemperatureBoundary', 1);
temp1.set('T0', '273.15');
temp1.selection.set([1 2 3 4]);
std1 = model.study.create('std1');
std1.feature.create('stat1', 'Stationary');
std1.run
model.result.dataset('dset1').set('geom', 'geom1');
pg1 = model.result.create('pg1', 2);
surf1 = pg1.feature.create('surf1', 'Surface');
pg1.set('data', 'dset1');
surf1.set('descr', 'T');

To create geometry with image files and MRI data you can follow the procedure
provided in the COMSOL 3.5a MATLAB Interface Guides section Geometry
Objects and Images under Images, Interpolation, and MRI Data. Once the
geometry is created with the COMSOL 3.5a commands you can convert it with this
procedure.

55 |

CHAPTER 3: CREATING GEOMETRIES

Modeling Physics
This chapter contains an introduction to modeling Physics Interfaces using
LiveLink for MATLAB.

56

Physics Interfaces
This section describes how to set up a physics interface. The physics interface defines
the equations that COMSOL solves. You find additional information on the physics
interfaces in Overview of the Physics Interfaces and the following sections in the
COMSOL Multiphysics Users Guide.
In this section:
The Physics Interface Syntax
Using Physics Interfaces
The Material Syntax
Using Materials
Modifying the Equations
Adding Global Equation

The Physics Interface Syntax


Create a physics interface instance using the syntax
model.physics.create(<tag>,<physint>,<gtag>);

where <tag> is a string that you use to refer to the physics interface. The string
<physint> is the constructor name of the physics interface. The string <gtag> is the
geometry where you want to specify the interface.
To add a feature to a physics interface, use the syntax
model.physics(<tag>).feature.create(<ftag>,<operation>);

where <tag> is the string you defined when creating the physics interface. The string
<ftag> is a string that you use to refer to the operation. To set a property to a value
in a operation, enter
model.physics(<tag>).feature(<ftag>).set(property,<value>);

where <ftag> is the string you defined when creating the operation.
There are alternate syntaxes available. Consult the reference documentation for details.
You find further details on available physics interface constructors and physics interface
feature constructors in model.physics() in the COMSOL Java API Reference
Guide.

57 |

CHAPTER 4: MODELING PHYSICS

The following sections contain examples of working with physics interfaces.

Using Physics Interfaces


Please go back and have a look at the introductory example in section A Simple Model
Example. This section examines the steps performed by setting up the physics
interfaces.
The initial command creates the interface.
es= model.physics.create('es', 'Electrostatics', 'geom1');

The tag of the interface is es. The physics interface constructor is Electrostatics.
The physics is set up on geometry geom1.
The physics interface creates a number of default features immediately. Examine these
by entering:
>> model.physics('es').feature
Type: List
Child tags: ccn1, zc1, init1

The first feature, ccn1, is the charge conservation equation. Establish this by entering:
>> model.physics('es').feature('ccn1')
Type: Charge Conservation
Tag: ccn1
Operation: ChargeConservation

To set the property epsilonr_mat in the Electrostatics in Charge


conservation feature to the default value (1), enter:
es.feature('ccn1').set('epsilonr_mat', 1, 'userdef');

To create a Ground boundary condition on boundary 2, enter:


es.feature.create('gnd1', 'Ground', 1);
es.feature('gnd1').selection.set([2]);

To create a Surface charge density boundary condition on boundary 4, enter


es.feature.create('sfcd1', 'SurfaceChargeDensity', 1);
es.feature('sfcd1').selection.set([4]);
es.feature('sfcd1').set('rhoqs',1,'1');

The Material Syntax


Create a material using the syntax

PHYSICS INTERFACES

58

model.material.create(<tag>);

where <tag> is a string that you use to refer to the physics interface.
To add a material model, use the syntax
mm=model.material(<tag>).materialmodel.create(<mtag>,<descr>);

where <tag> is the string you defined when creating the material. The string <mtag>
is a string that you use to refer to the material model. The string <descr> is a
description of the material model. To set a property to a value in a operation, enter
mm.set(property,<value>);

You find further details on available physics interface constructors and physics interface
feature constructors in model.material() in the COMSOL Java API Reference
Guide.
The following sections contain examples of working with physics interfaces and
materials.

Using Materials
As an addition to the introductory model the section Using Physics Interfaces,
consider using a material to define the air in the model.
mat1=model.material.create('mat1');

The material automatically creates a material model, def, which you can use to set up
basic properties. Use it to define the relative permittivity:
mat1.materialmodel('def').set('relpermittivity', {'1'});

To use the defined material in your model, you must modify the Electrostastics
in Charge conservation feature with tag ccn1 to use the material.
es.feature('ccn1').set('epsilonr_mat', 1, 'from_mat');

You can then resolve the model using the material instead of the user-defined property:
model.study.create('std1');
model.study('std1').run;

Modifying the Equations


The equation used in the physics node can be edited and modified with the
featureInfo('info') method applied to the desired feature of the physics node

59 |

CHAPTER 4: MODELING PHYSICS

physics(<phys>).feature(<tag>), where <phys> is the physics tag name and


<tag> is the feature tag name.
Info = model.physics('es').feature('ccn1').featureInfo('info');

The getInfoTable(<type>) method returns the list of the table defined for the weak
type ('Weak'), the constraint type ('Constraint'), or the expression type
('Expression').
To get the equations corresponding to the physics node <phys>:
Weak = Info.getinfoTable('Weak');

This returns a java.lang.string variable that contains both the name of the weak
equation variable and the equation of the physics implemented in the weak form. In
this example the following results:
list = weak(:)
list=
java.lang.String[]:
'(-es.Dx*test(Vx)-es.Dy*test(Vy))*es.d'
'root.mod1.es.weak$1'

Where root.mod1.es.weak$1 is the name of the field to modify if you want to modify
the governing equation. This can be done with the lock method, for instance:
Info.lock('root.mod1.es.weak$1',
{'(-es.Dx*test(Vx)-es.Dy*test(Vy))*1e-3'});

The above command changes the thickness of the material from the variable name
es.d to a constant value 1e-3.

Adding Global Equation


A global equation can be added to the physics node phys:
ge1 = phys.feature.create('ge1', 'GlobalEquations', -1);

To define the name of the variable to be solved by the global equation, enter
ge1.set('name', 1, 'u');

Set the expression of the global equation with


ge1.set('equation', 1, 'ut-u+1');

Initial value and initial velocity can be set with


ge1.set('initialValueU', 2, 'u0');
ge1.set('initialValueUt', 2, 'u0t');

PHYSICS INTERFACES

60

61 |

CHAPTER 4: MODELING PHYSICS

Creating Meshes
This section introduces you to Meshing Sequences and how to build them using
the LiveLink interface.

62

Meshing Sequences
This section describes how to set up and run meshing sequences to create your meshes.
For additional information on meshing, see Creating Meshes in the COMSOL
Multiphysics Users Guide.
You find reference information in Meshing API in the COMSOL Java API Reference
Guide.

The Meshing Sequence Syntax


Create a meshing sequence by using the syntax
model.mesh.create(<tag>,<gtag>);

where <tag> is a string that you use to refer to the sequence. The tag <gtag> specifies
the geometry.
To add an operation to a sequence, use the syntax
model.mesh(<tag>).feature.create(<ftag>,<operation>);

where <tag> is the string you defined when creating the sequence. The string <ftag>
is a string that you use to refer to the operation. To set a property to a value in a
operation, enter
model.mesh(<tag>).feature(<ftag>).set(property,<value>);

where <ftag> is the string you defined when creating the operation.
Finally to build the sequence, enter
model.mesh(<tag>).run;

See Meshing API in the COMSOL Java API Reference Guide for more details on
available operations and properties in the sequence.
To plot the mesh in MATLAB with Handle Graphics, use the command
mphmesh(model,<tag>);

The following sections contain examples of working with sequences.

63 |

CHAPTER 5: CREATING MESHES

Mesh Creation Functions


MESH SIZING PROPERTIES

The Size attribute provides a number of input properties that you can use to control,
for example:
The maximum mesh size and curvature mesh size
The growth rate for the mesh size (away from small details)
The resolution of narrow regions
These properties are available both globally and locally.
There are nine predefined settings you can use to set a suitable combination of values
for many properties. To select one of these settings, use the property hauto and pass
an integer from 1 to 9 as its value to describe the mesh resolution:
Extremely fine (1)
Extra fine (2)
Finer (3)
Fine (4)
Normal (5)
Coarse (6)
Coarser (7)
Extra coarse (8)
Extremely coarse (9)
The default value is 5, that is, the Normal mesh settings. See the COMSOL
Multiphysics Reference Guide entry on Size for details about the mesh size values
for the predefined settings and all other properties.

ExampleCreating a 2D Mesh with Triangular Elements


Generate a triangular mesh of a unit square:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1',2);
geom1.feature.create('r1','Rectangle');
mesh1 = model.mesh.create('mesh1','geom1');
mesh1.feature.create('ftri1','FreeTri');
mesh1.run;

MESHING SEQUENCES

64

mphmesh(model,'mesh1');

Figure 5-1: Default mesh on a unit square.


The default size feature is generated with the property hauto set to 5, that is,
mesh1.feature('size').set('hauto','5');

You can override this behavior by setting hauto to another integer. You can also
override 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,'mesh1');

65 |

CHAPTER 5: CREATING MESHES

This value corresponds to 1/50 of the largest axis-parallel distance, whereas the default
value is 1/15.

Figure 5-2: Fine mesh (maximum element size = 0.02).


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

MESHING SEQUENCES

66

mphmesh(model,'mesh1');

Figure 5-3: Nonuniform mesh.

The Free Meshing Method


The default method for generating free triangle meshes in 2D is based on an advancing
front algorithm. It is possible to use instead a Delaunay algorithm. To use the
Delaunay method, specify the property method as del:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1',2);
geom1.feature.create('r1','Rectangle');
c1 = geom1.feature.create('c1','Circle');
c1.set('r','0.5');
co1=geom1.feature.create('co1','Compose');
co1.selection('input').object('geom1');
co1.selection('input').set({'c1' 'r1'});
co1.set('formula','r1-c1');
geom1.runAll;
mesh1 = model.mesh.create('mesh1','geom1');
ftri1 = mesh1.feature.create('ftri1','FreeTri');
ftri1.set('method','del');
mesh1.run;

67 |

CHAPTER 5: CREATING MESHES

mphmesh(model,'mesh1')

Figure 5-4: Mesh created with the Delaunay method.

ExampleCreating a 2D Mesh with Quadrilateral Elements


To create an unstructured quadrilateral mesh on a unit circle:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1',2);
geom1.feature.create('c1','Circle');
mesh1 = model.mesh.create('mesh1','geom1');
mesh1.feature.create('ftri1','FreeQuad');
mesh1.run;
mphmesh(model,'mesh1')

Figure 5-5: Free quad mesh.

MESHING SEQUENCES

68

CREATING STRUCTURED MESHES

To create a structured quadrilateral mesh in 2D, use the Map operation. This operation
uses a mapping technique to create the quadrilateral mesh. For each domain, the
algorithm generates a logical mesh on a block geometry and then maps it onto the real
geometry by transfinite interpolation. The input geometry object must meet the
following criteria for the mapping technique to work:
Each domain must be bounded by one connected boundary component only.
Each domain must be bounded by at least four boundary segments.
The geometry must not contain isolated vertices or boundary segments.
The shape of each domain must not differ too much from a rectangular shape.
Use the EdgeGroup attribute to group the edges (boundaries) into four edge groups,
one for each edge of the logical mesh. Using the Distribution attribute you can also
control the edge element distribution, which determines the overall mesh density.

ExampleCreating a Structured Quadrilateral Mesh


Create a structured quadrilateral mesh on a geometry where the domains are bounded
by more than four edges:
model = ModelUtil.create('Model');
geom1 = model.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 = model.mesh.create('mesh1','geom1');
map1 = mesh1.feature.create('map1','Map');
eg1 = map1.feature.create('eg1', 'EdgeGroup');
eg1.selection.set(1);
eg1.selection('edge1').set([1 3]);
eg1.selection('edge2').set(2);
eg1.selection('edge3').set(8);
eg1.selection('edge4').set(4);
eg2 = map1.feature.create('eg2', 'EdgeGroup');
eg2.selection.set(2);
eg2.selection('edge1').set(4);
eg2.selection('edge2').set([6 9 10]);
eg2.selection('edge3').set(7);
eg2.selection('edge4').set(5);

69 |

CHAPTER 5: CREATING MESHES

mesh1.run;
mphmesh(model,'mesh1');

Figure 5-6: Structured quadrilateral mesh (right) and its underlying geometry.
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.
BUILDING A MESH INCREMENTALLY

You can create meshes in a step-by-step fashion by creating selections for the parts of
the geometry that you want to mesh in each step. The following example illustrates the
procedure:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1',2);
geom1.feature.create('r1','Rectangle');
geom1.feature.create('c1','Circle');
uni1 = geom1.feature.create('uni1', 'Union');
uni1.selection('input').object('geom1');
uni1.selection('input').set({'c1' 'r1'});
geom1.runCurrent;
del1 = geom1.feature.create('del1', 'Delete');
del1.selection('input').object('geom1', 1);
del1.selection('input').set('uni1', 8);
geom1.run('del1');
mesh1 = model.mesh.create('mesh1','geom1');
dis1 = mesh1.feature.create('dis1', 'Distribution');
dis1.selection.set([2 4]);
dis1.set('type', 'predefined');
dis1.set('method', 'geometric');
dis1.set('elemcount', '20');
dis1.set('reverse', 'on');
dis1.set('elemratio', '20');
dis2 = mesh1.feature.create('dis2', 'Distribution');

MESHING SEQUENCES

70

dis2.selection.set([1 3]);
dis2.set('type', 'predefined');
dis2.set('method', 'geometric');
dis2.set('elemcount', '20');
dis2.set('elemratio', '20');
map1 = mesh1.feature.create('map1','Map');
map1.selection.geom('geom1', 2);
map1.selection.set(2);
mesh1.feature.create('frt1','FreeTri');
mesh1.run;
mphmesh(model,'mesh1');

The final mesh appears in Figure 5-7. Also note the effect of the Distribution
feature, with which you can control the distribution of vertex elements along geometry
edges.

Figure 5-7: Incrementally generated mesh (right).


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;

Note that to get the FreeQuad feature before the FreeTri feature you need to
position the current point to point on the dis1 feature, and then insert the FreeQuad
feature.
Alternatively, you can selectively remove parts of a mesh by using the Delete feature.
For example, to remove the structured mesh from domain 2 along with the adjacent
edge mesh on edges 3 and 4, and replace it with an unstructured quad mesh, enter
these commands:

71 |

CHAPTER 5: CREATING MESHES

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;

As usual, for further details on the various commands and their properties consult the
COMSOL Java API Reference Guide.
REVOLVING A MESH BY SWEEPING

Using the Sweep feature you can create 3D volume meshes by extruding and revolving
face meshes. Depending on the 2D mesh type, the 3D meshes can be hexahedral
(brick) meshes or prism meshes.

ExampleRevolving Mesh
Create and visualize a revolved prism mesh as follows:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 3);
wp1 = geom1.feature.create('wp1', 'WorkPlane');
wp1.set('planetype', 'quick');
wp1.set('quickplane', 'xy');
c1 = wp1.geom.feature.create('c1', 'Circle');
c1.set('pos', [2, 0]);
rev1 = geom1.feature.create('rev1', 'Revolve');
rev1.set('angle2', '60').set('angle1', '-60');
rev1.selection('input').set({'wp1'});
geom1.run('rev1');
mesh1 = model.mesh.create('mesh1', 'geom1');
mesh1.feature.create('ftri1', 'FreeTri');
mesh1.feature('ftri1').selection.geom(2);
mesh1.feature('ftri1').selection.set(2);
mesh1.runCurrent;
swe1 = mesh1.feature.create('swe1', 'Sweep');
swe1.selection.geom(3);
swe1.selection.add(1);
mesh1.run;
mphmesh(model,'mesh1')

MESHING SEQUENCES

72

To obtain a torus, leave the angles property unspecified; the default value gives a
complete revolution.

Figure 5-8: 3D prism mesh created with the Sweep feature.


EXTR UDING A MESH BY SWEEPING

To generate a 3D prism mesh from the same 2D mesh by extrusion and then plot it,
enter the following commands:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 3);
wp1 = geom1.feature.create('wp1', 'WorkPlane');
wp1.set('planetype', 'quick');
wp1.set('quickplane', 'xy');
c1 = wp1.geom.feature.create('c1', 'Circle');
c1.set('pos', [2, 0]);
ext1 = geom1.feature.create('ext1', 'Extrude');
ext1.selection('input').set({'wp1'});
geom1.runAll;
mesh1 = model.mesh.create('mesh1', 'geom1');
ftri1 = mesh1.feature.create('ftri1', 'FreeTri');
ftri1.selection.geom('geom1', 2);
ftri1.selection.set(3);
dis1 = mesh1.feature.create('dis1', 'Distribution');
dis1.selection.set(1);
dis1.set('type', 'predefined');
dis1.set('elemcount', '20');
dis1.set('elemratio', '100');
swe1 = mesh1.feature.create('swe1', 'Sweep');
swe1.selection('sourceface').geom('geom1', 2);
swe1.selection('targetface').geom('geom1', 2);
mesh1.run;
mphmesh(model,'mesh1');

73 |

CHAPTER 5: CREATING MESHES

The result appears in Figure 5-9. With the properties elemcount and elemratio you
control the number and distribution of mesh element layers in the extruded direction.
See Distribution in the COMSOL Java API Reference Guide.

Figure 5-9: Extruded 3D prism mesh.


COMBINING UNSTRUCTURED AND STRUCTURED MESHES

You can combine swept meshing with free meshing. Just specify selections for the
meshing. In this case, start by free meshing domain 2, then sweep the resulting surface
mesh through domain 1.
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 3);
cone1 = geom1.feature.create('cone1', 'Cone');
cone1.set('r', '0.3');
cone1.set('h', '1');
cone1.set('ang', '9');
cone1.set('pos', [ 0 0.5 0.5]);
cone1.set('axis', [-1 0 0]);
geom1.feature.create('blk1', 'Block');
mesh1 = model.mesh.create('mesh1', 'geom1');
ftet1 = mesh1.feature.create('ftet1', 'FreeTet');
ftet1.selection.geom('geom1', 3);
ftet1.selection.set(2);
swe1 = mesh1.feature.create('swe1', 'Sweep');
swe1.selection('sourceface').geom('geom1', 2);
swe1.selection('targetface').geom('geom1', 2);
mesh1.run;

MESHING SEQUENCES

74

mphmesh(model,'mesh1');

Figure 5-10: Combined structured/unstructured mesh.


Note that the left-hand side figure is obtained with the following command:
mphgeom(model,'geom1','facemode','off','facelabels','on')
CREATING BOUNDARY LAYER MESHES

For 2D and 3D geometries it is also possible to create boundary layer meshes using the
BndLayer feature. A boundary layer mesh is a mesh with dense element distribution
in the normal direction along specific boundaries. This type of mesh is typically used
for fluid flow problems to resolve the thin boundary layers along the no-slip
boundaries. In 2D, a layered quadrilateral mesh is used along the specified no-slip
boundaries. In 3D, a layered prism mesh or hexahedral mesh is used depending on if
the corresponding boundary layer boundaries contain a triangular or a quadrilateral
mesh.
If you start 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 the procedure in 2D:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 2);
r1 = geom1.feature.create('r1', 'Rectangle');
r1.set('size', [10, 5]);
c1 = geom1.feature.create('c1', 'Circle');
c1.set('pos', [3.5 2.5]);
dif1 = geom1.feature.create('dif1', 'Difference');
dif1.selection('input2').object('geom1');
dif1.selection('input').object('geom1');
dif1.selection('input').set({'r1'});
dif1.selection('input2').set({'c1'});

75 |

CHAPTER 5: CREATING MESHES

geom1.runAll;
mesh1 = model.mesh.create('mesh1', 'geom1');
bl1 = mesh1.feature.create('bl1', 'BndLayer');
bl1.feature.create('blp1', 'BndLayerProp');
bl1.feature('blp1').selection.set([2 3 5 6 7 8]);
mesh1.run;
mphmesh(model,'mesh1');

Boundary layer mesh based on an unstructured triangular mesh.


It is also possible to insert boundary layers in an existing mesh. Use the following
meshing sequence with the geometry sequence of the previous example:
bq1.active(false);
fq1 = mesh1.feature.create('fq1', 'FreeQuad');
fq1.selection.set([1]);
mphmesh(model,'mesh1')
bl1 = mesh1.feature.create('bl2', 'BndLayer');
bl1.feature.create('blp2', 'BndLayerProp');
bl1.feature('blp2').selection.set([2 3 5 6 7 8]);
mesh1.run;
mphmesh(model,'mesh1');

Initial unstructured quad mesh (left) and resulting boundary layer mesh (right).

MESHING SEQUENCES

76

MEASURING MESH QUALITY

Use the stat method on the meshing sequence to get information on the mesh
quality. The quality measure is a scalar quantity, defined for each mesh element, where
0 represents the lowest quality and 1 represents the highest quality.
The following commands illustrate how to visualize the mesh quality for a mesh on the
unit circle:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 2);
geom1.feature.create('c1', 'Circle');
geom1.runAll;
mesh1 = model.mesh.create('mesh1', 'geom1');
mesh1.feature.create('ftri1', 'FreeTri');
mesh1.run;
meshdset1 = model.result.dataset.create('mesh1', 'Mesh');
meshdset1.set('mesh', 'mesh1');
pg1 = model.result.create('pg1', 2);
meshplot1 = pg1.feature.create('mesh1', 'Mesh');
meshplot1.set('data', 'mesh1');
meshplot1.set('filteractive', 'on');
meshplot1.set('elemfilter', 'quality');
meshplot1.set('tetkeep', '0.25');
mphplot(model,'pg1');
meshplot1.set('elemfilter','qualityrev');
meshplot1.run;
mphplot(model,'pg1');

These commands display the worst 25% and the best 25% elements in terms of mesh
element quality. Notice in Figure 5-11 how the triangular mesh elements in the plot
to the right are more regular than those in the left plot; this reflects the fact that a
quality measure of 1 corresponds to a uniform triangle, while 0 means that the triangle
has degenerated into a line.

Figure 5-11: Visualizations of the mesh quality: worst 25% (left) and best 25% (right).

77 |

CHAPTER 5: CREATING MESHES

REFINING MESHES

Given a mesh consisting only of simplex elements (lines, triangles, and tetrahedra) you
can create a finer mesh using the feature Refine. Thus
mesh1.feature.create('ref1', 'Refine');

refines the mesh.


By specifying the property tri, either as a row vector of element numbers or a 2-row
matrix, you can control which elements are to be refined. 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 have the option of using adaptive
mesh refinement at the solver stage by using the solver step adaption, see Adaption
in the COMSOL Java API Reference Guide.
COPYING BOUNDARY MESHES

Use the CopyEdge feature in 2D and the CopyFace feature in 3D to copy a mesh
between boundaries. It is only possible to copy meshes between boundaries that have
the same shape. However, a scaling factor between the boundaries is allowed. The
following example demonstrates how to copy a mesh between two boundaries in 3D
and then create a swept mesh on the domain.
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 3);
wp1 = geom1.feature.create('wp1', 'WorkPlane');
wp1.set('planetype', 'quick');
wp1.set('quickplane', 'xy');
c1 = wp1.geom.feature.create('c1', 'Circle');
c1.set('r', 0.5);
c1.set('pos', [1, 0]);
rev1 = geom1.feature.create('rev1', 'Revolve');
rev1.set('angle1', '0').set('angle2', '180');
rev1.selection('input').set({'wp1'});

MESHING SEQUENCES

78

geom1.run('wp1');
mesh1 = model.mesh.create('mesh1', 'geom1');
size1 = mesh1.feature.create('size1', 'Size');
size1.selection.geom('geom1', 1);
size1.selection.set(18);
size1.set('hmax', '0.06');
ftri1 = mesh1.feature.create('ftri1', 'FreeTri');
ftri1.selection.geom('geom1', 2);
ftri1.selection.set(10);
cpf1 = mesh1.feature.create('cpf1', 'CopyFace');
cpf1.selection('source').geom('geom1', 2);
cpf1.selection('destination').geom('geom1', 2);
cpf1.selection('source').set(10);
cpf1.selection('destination').set(1);
sw1 = mesh1.feature.create('sw1', 'Sweep');
sw1.selection('sourceface').geom('geom1', 2);
sw1.selection('targetface').geom('geom1', 2);
mesh1.run;
mphmesh(model,'mesh1');

The algorithm automatically determines how to orient the source mesh on the target
boundary, and the result looks like this:

You can explicitly control the orientation of the copied mesh by using the EdgeMap
attribute. The command sequence
em1 = cpf1.feature.create('em1', 'EdgeMap');
em1.selection('srcedge').set(18);
em1.selection('dstedge').set(2);
mesh1.feature.remove('sw1');
mesh1.feature.create('ftet1', 'FreeTet');
mesh1.run;
mphmesh(model,'mesh1');

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

79 |

CHAPTER 5: CREATING MESHES

meshed by the free mesh, resulting in the mesh shown in the next figure. Note that 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.

CONVER TING MESH ELEMENTS

Using the Convert feature it is possible to convert meshes containing quadrilateral,


hexahedral, or prism elements into triangular meshes and tetrahedral meshes. In 2D,
the function splits each quadrilateral element into either two or four triangles. In 3D,
it converts each prism into three tetrahedral elements and each hexahedral element
into five, six, or 28 tetrahedral elements. You can control the method used to convert
the elements using the property splitmethod. The default value is diagonal, which
results in two triangular elements in 2D and five or six tetrahedral elements in 3D. See
the entry for Convert in the COMSOL Java API Reference Guide for additional
properties supported. The example below demonstrates how to convert a quad mesh
into a triangle mesh:
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 2);
geom1.feature.create('c1', 'Circle');
geom1.feature.create('r1', 'Rectangle');
int1 = geom1.feature.create('int1', 'Intersection');
int1.selection('input').object('geom1');
int1.selection('input').set({'c1' 'r1'});
mesh1 = model.mesh.create('mesh1', 'geom1');
mesh1.feature.create('fq1', 'FreeQuad');
mesh1.runCurrent;
mesh1.feature.create('conv1', 'Convert');
mesh1.run;
mphmesh(model,'mesh1');

MESHING SEQUENCES

80

The result looks like this:

Importing External Meshes and Mesh Objects


It is possible to import meshes to the workspace and to COMSOL Multiphysics using
the following formats:
COMSOL Multiphysics text files (extension .mphtxt)
COMSOL Multiphysics binary files (extension .mphbin)
NASTRAN files (extension .nas or .bdf)
For a description of the text file format see the COMSOL Multiphysics Reference
Guide.
IMPORTING MESHES TO THE COMMAND LINE

To import a mesh stored in a supported format use the Import feature. The following
commands import and plot a NASTRAN mesh for a crankshaft:
model = ModelUtil.create('Model');
model.geom.create('geom1', 3);
mesh1 = model.mesh.create('mesh1', 'geom1');
imp1 = mesh1.feature.create('imp1', 'Import');
imp1.set('filename','<dir>\\COMSOL42\\models\\
COMSOL_Multiphysics\\Structural_Mechanics\\crankshaft.nas');
mesh1.feature('imp1').importData;
mesh1.run;
mphmesh(model,'mesh1');

81 |

CHAPTER 5: CREATING MESHES

Where <dir> is the path of root directory where COMSOL Multiphysics 4.2 is
installed

Figure 5-12: NASTRAN mesh imported into MATLAB.


The linearelem property uses linear elements in the COMSOL Multiphysics mesh
object and ignores extended node points; here it serves to make a smaller mesh for
visualization purposes. See the entry for Import in the COMSOL Java API
Reference Guide for additional properties supported.

Getting Mesh Information


The stat method on the meshing sequence returns mesh statistics information for the
entire mesh case or for a specific mesh type.
model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 2);
geom1.feature.create('sq1', 'Square');
mesh1 = model.mesh.create('mesh1', 'geom1');
mesh1.feature.create('ftri1', 'FreeTri');
mesh1.run('ftri1');

You can access the model mesh statistics with the mphmeshstats function:
stats = mphmeshstats(model,'mesh1');

stats is a MATLAB structure that contains the following field:


isactive, indicate if the mesh node is active (1) or not (0).
hasproblem, indicate if the mesh has problem (1) or not (0).
iscomplete, indicate if the entire geometry has a mesh.

MESHING SEQUENCES

82

sdim, indicates the mesh space dimension.


types, list the mesh type available in the mesh node.
numelem, contains the element number for each mesh types.
minquality, contains the minimum element quality value.
meanquality, contains the mean element quality value.
qualitydistr, contains the distribution of the mesh quality.
minvolume, contains the minimum element volume value.
maxvolume, contains the maximum element volume value.
volume, contains the mesh volume value.

Getting and Setting Mesh Data


The data in the mesh object can be accessed and changed.
model = ModelUtil.create('Model');
model.modelNode.create('mod1');
geom1 = model.geom.create('geom1', 2);
geom1.feature.create('sq1', 'Square');
geom1.run;
mesh1 = model.mesh.create('mesh1', 'geom1');
mesh1.feature.create('ftri1', 'FreeTri');
mesh1.run('ftri1');

To get the number of mesh vertices, you can use


NumVertex = mesh1.getNumVertex;

To get the coordinates of the mesh vertices as a matrix data where each column
corresponds to a vertex mesh, you can use
Vertex = mesh1.getVertex;

To get the number of triangle elements ('tri') and the elements, you can use
NumElemTri = mesh1.getNumElem('tri');
Elem = mesh1.getElem('tri');

It is also possible to set mesh data via the data method. Using this method you access
a temporary object (MeshData) storing mesh data. When you use the data method the
first time, the MeshData object is empty. You can fill it with mesh data either by using
various set method or by transferring mesh data from the mesh of the meshing
sequence. Call the data.createMesh method to construct a complete mesh from the
MeshData object and store it in the meshing sequence. If the geometry is not empty,
the new mesh is checked to ensure that it matches the geometry. Thus, to create an

83 |

CHAPTER 5: CREATING MESHES

arbitrary mesh you need to create an empty geometry sequence and a corresponding
empty meshing sequence and construct the mesh on the empty meshing sequence.
The following example creates a triangular mesh on a square, extracts the vertices and
the triangle. Then the vertices are transformed (the coordinates values are divided by
2) and inserted into a new meshing sequence:
model = ModelUtil.create('Model');
model.modelNode.create('mod1');
geom1 = model.geom.create('geom1', 2);
geom1.feature.create('sq1', 'Square');
geom1.run;
mesh1 = model.mesh.create('mesh1', 'geom1');
mesh1.feature.create('ftri1', 'FreeTri');
mesh1.run('ftri1');
mphmesh(model,'mesh1');

vtx = mesh1.getVertex;
tri = mesh1.getElem('tri');
for k = 1:length(vtx)
vtx(:,k)=vtx(:,k)*0.5;
end
geom2 = model.geom.create('geom2', 2);
mesh2 = model.mesh.create('mesh2', 'geom2');
mesh2.data.setElem('tri',tri);
mesh2.data.setVertex(vtx);
mesh2.data.createMesh;

MESHING SEQUENCES

84

mphmesh(model,'mesh2');

85 |

CHAPTER 5: CREATING MESHES

Creating Studies
This section introduces you to setting up and running studies for solving models
using the LiveLink interface.

86

The Study
This section describes how to set up and run a study. The study contains basic solver
settings. COMSOL uses the physics interfaces and the study to automatically
determine solver settings. You find additional information on the study in Solvers and
Study Types in the COMSOL Multiphysics Users Guide. Reference information is
described in Solver API in the COMSOL Java API Reference Guide.

The Study Syntax


Create a study by using the syntax
model.study.create(<tag>);

where <tag> is a string that you use to refer to the study sequence.
To add a study step to a study, use the syntax
model.study(<tag>).feature.create(<ftag>,<operation>);

where <tag> is the string you defined when creating the study. The string <ftag> is a
string that you use to refer to the study step. To set a property to a value in a study
step, enter
model.study(<tag>).feature(<ftag>).set(property,<value>);

where <ftag> is the string you defined when creating the operation.
To run the study, enter
model.study(<tag>).run

See also model.study() in the COMSOL Java API Reference Guide.

Using the Study


Getting back to our simple example, the following command creates the study
std1 = model.study.create('std1');

The study is initially empty. The study needs to know the type of analysis that you want
to perform. For example, create a Stationary study step to specify a stationary analysis.
std1.feature.create('stat1', 'Stationary');

To run a study, enter:

87 |

CHAPTER 6: CREATING STUDIES

std1.run;

This automatically generates a solver sequence and runs it. The solver sequence can be
set up automatically from the study or be created manually.
Alternatively, create a time-dependent study running from 0 to 10 with a step of 1 by
entering
time1 = std1.feature.create('time1', 'Transient');
time1.set('tlist', 'range(0,1,10)');
std1.run;

The Solver Configuration Syntax


Create a solver configuration manually by using the syntax
model.sol.create(<tag>);

where <tag> is a string that you use to refer to the solver configuration.
To add a solver operation, use the syntax
model.sol(<tag>).feature.create(<ftag>,<operation>);

where <tag> is the string you defined when creating the operation. The string <ftag>
is a string that you use to refer to the study step. To set a property to a value in a study
step, enter
model.sol(<tag>).feature(<ftag>).set(<property>,<value>);

where <ftag> is the string you defined when creating the operation.
To run the solver configuration, enter
model.sol(<tag>).run

See also Solver API in the COMSOL Java API Reference Guide.

Using Solver Configurations


Running a study sets up a solver configuration automatically. A saved Model M-file
contains the commands that were used by the study to set up the solver configuration.
You can use a saved Model M-file to get acquainted with it.
The solver configuration should always include a study step, a variables step, and a
solver step, for example,
sol1 = model.sol.create('sol1');
st1 = sol1.feature.create('st1', 'StudyStep');

THE STUDY

88

sol1.feature.create('v1', 'Variables');
sol1.feature.create('s1', 'Stationary');

The StudyStep should be associated with a study, that is,


st1.set('study', 'std1');

The study determines what equation form (stationary, time-dependent, and so on) to
use for generating the equations that you solve.
The variables step automatically determines the available variables. You might want to
specify the variables solved for in the variables step.
The solution steps can be of different types, for example, stationary to indicate that you
solve for a stationary solution.
The solver configuration needs to be attached to its study.
sol1.attach(true);

Evaluating System Matrices


The Assemble feature assembles the stiffness matrix, right-hand side, mass matrix,
damping matrix, and constraints of a PDE problem using a finite element
discretization. You can output all these matrices or one or more selected matrices. For
a time-dependent problem, for example, the assembled system is the following system
of ODEs:

T
0 = L(U U U t) N(U t)
0 = M(U t)
where:
L is the residual vector
M is the constraint residual vector
U is the solution vector
is the Lagrange multiplier vector
The linearization of this system results in the following matrices:
L
K = ------U

89 |

CHAPTER 6: CREATING STUDIES

L
D = -------
U

L
E = ------
U

M
N = -------U

where:
K is the stiffness matrix
D is the damping matrix
E is the mass matrix
Nis the constraint Jacobian matrix
All these matrices can depend on the solution vector U. The matrices K, D, and E can
also depend on the time derivatives of U.
G E T T I N G T H E S Y S T E M M A T R I C E S I N M AT L A B

The matrices system can be extracted in MATLAB with the command mphmatrix. You
only need to define the solver node Solname to use and the list Out of the system
matrices to extract (defined as a cell array):
dat = mphmatrix(model,Solname,'Out',Out);

See the following list of the matrices that you can extract with the mphmatrix
command:
EXPRESSION

DESCRIPTION

Stiffness matrix

Load vector

Constraint vector

Constraint Jacobian

Damping matrix

Mass matrix

NF

Constraint force Jacobian

NP

Optimization constraint Jacobian (*)

MP

Optimization constraint vector (*)

MLB

Lower bound constraint vector (*)

MUB

Upper bound constraint vector (*)

Kc

Eliminated stiffness matrix

Lc

Eliminated load vector

Dc

Eliminated damping matrix

Ec

Eliminated mass matrix

Null

Constraint null-space basis

Nullf

Constraint force null-space matrix

THE STUDY

90

EXPRESSION

DESCRIPTION

ud

Particular solution ud

uscale

Scale vector

(*) Require the Optimization Module.

For instance, in the introductory example in section A Simple Model Example extract
the stiffness matrix and the eliminated stiffness matrix with the following commands:
MA = mphmatrix(model,'sol1','as1','Out',{'K','L'});

The stiffness matrix and the residual are available using MA.K and MA.L. If the solution
has been computed you can verify that the residual is close to zero.
Note that the assembly of the eliminated matrices uses the current solution vector as
scaling. If you have a solver step in your solver configuration
You can get the unscaled matrices by removing setting the scaling method to none in
the variables step of the solver configuration, for instance:
model.sol('sol1').feature('v1').set('scalemethod','none');
MA = mphmatrix(model,'sol1','as1','Out',{'Kc'});

If you want to extract the system matrices and the load vector you need to make sure
that no solver step node is added to the solver configuration node. If you have one you
can disable it with the command:
model.sol('sol1').feature('s1').active(false);
MA = mphmatrix(model,'sol1','as1','Out',{'Kc' 'Lc'});
SOLVING A SIMPLE PROBLEM IN THE MATRIX LEVEL

The following example illustrate how to use the mphmatrix command to extract the
eliminated system matrices and solve the stationary problem at the MATLAB prompt.
The problem studied here is a linear heat transfer problem solved on a unit square with
a surface heat source and temperature constraint.
% Create a new model object
model = ModelUtil.create('Model');
% Create a square geometry
geom1 = model.geom.create('geom1', 2);
geom1.feature.create('sq1', 'Square');
geom1.run;
% Setup material properties
mat1 = model.material.create('mat1');
def = mat1.materialModel('def');
def.set('thermalconductivity',{'4e2'});
def.set('density',{'8e3'});

91 |

CHAPTER 6: CREATING STUDIES

def.set('heatcapacity',{'2e3'});
% Define the physics settings
ht = model.physics.create('ht', 'HeatTransfer', 'geom1');
hs1 = ht.feature.create('hs1','HeatSource',2);
hs1.selection.set(1);
hs1.set('Q',1,'1e5');
temp1 = ht.feature.create('temp1','TemperatureBoundary',1);
temp1.selection.set([1 2]);
% Create a mapped mesh
mesh1 = model.mesh.create('mesh1','geom1');
dis1 = mesh1.feature.create('dis1','Distribution');
dis1.selection.set([1 2]);
dis1.set('numelem','2');
mesh1.feature.create('map1','Map');
mesh1.run;
% Solve the problem
std1 = model.study.create('std1');
std1.feature.create('stat','Stationary');
std1.run;

You can extract the solution vector with the mphgetu function:
U = mphgetu(model);

In order to extract the residual without using the final solution as linearization point
we need to deactivate the solver step node. Not doing this operation results in an
almost null residual:
model.sol('sol1').feature('s1').active(false);

Extract the eliminated system include the Null space-basis, the scale vector and the
particular solution:
MA =
mphmatrix(model,'sol1','Out',{'Kc','Lc','Null','ud','uscale'});

Solve for the eliminated solution vector using the extracted system:
Uc = MA.Null*(MA.Kc\MA.Lc);

Combine the eliminated solution vector and the particular vector:


U0 = Uc+MA.ud;

Scale back the solution vector:


U1 = (1+U0).*MA.uscale;

Now compare both solution vector U and U1 computed by COMSOL and by the
matrix operation respectively.

THE STUDY

92

Exporting State-Space Models


Use state-space export to create a linearized state-space model corresponding to a
COMSOL Multiphysics model. You can export the matrices of the state-space form
directly to the MATLAB workspace with the command mphstate.
THE STATE-SPACE FORM

The vector x is called the state vector. The state-space form of the model is
dx
------- = Ax + Bu
dt
y = Cx + Du

where A, B, C, and D are constant matrices. The constraints (Dirichlet boundary


conditions) are eliminated by writing the solution vector U as
U = Nullx + U 0
where U0 is the linearization point, and Null is the null-space matrix for the
constraints. The input linearization point is stored in the sequence after the state space
feature is run.
Export the system on the following equivalent form:

dx
M C ------- = M A x + M B u
dt

y = Cx + Du

This form is more suitable for large systems because the matrices MC and MA usually
become much more sparse than A.
If the mass matrix MC is small, it is possible to approximate the dynamic state-space
model with a static model, where M = 0:
0 = McAx + McBu

y = Cx + Du

Equivalently, y = Hu, where H = DC(McA)1McB is the transfer matrix.

93 |

CHAPTER 6: CREATING STUDIES

EVALUATING STATE-SPACE MATRICES FROM MODELS

To get the state-space matrices of a given model, use the mphstate function with the
following syntax:
dat = mphstate(model,Solname, 'Out',Out,'input',...
input_param,'output',output_expr);

Where Solname is the tag of the solver sequence to use for the matrices evaluation.
input_param is the list of the input variables defined as parameters in the model.
output_expr is the list of expressions to use as output in the state-space system. Out
is the list of the matrices you wish assemble, see below the list of the matrices that can
be extracted with the mphstate command:'
EXPRESSION

DESCRIPTION

MA

McA matrix

MB

McB matrix

C matrix

D matrix

Mc

Mc matrix

Null

Null matrix

ud

ud vector

x0

x0 vector

Two optional properties are also available with the mphstate function:
keepfeature, mphstate leave the state-space feature node in the solver sequence
when keepfeature property is set to on. The default value is off.
sparse, mphstate assemble sparse matrices when the sparse property is set to on.
The default value is off.
EXAMPLE

To illustrate how to use the mphstate function to extract the state-space matrices of
the model described in A Simple Model Example. The surface charge density defines
the input of the state-space system, the electric potential at point (0.8;0.9) defines the
output of the system.
1 To create the model, the geometry and the mesh enter the following command at

the MATLAB prompt:


model = ModelUtil.create('Model');
geom1 = model.geom.create('geom1', 2);
geom1.feature.create('sq1', 'Square');

THE STUDY

94

geom1.run;
mesh1 = model.mesh.create('mesh1', 'geom1');
mesh1.feature.create('fre1', 'FreeTri');

2 Add a parameter rhos with the command below:


model.param.set('rhos', '1e-10[C/m^2]');

3 Add an electrostatics physics interface and set-up the physics problem:


es = model.physics.create('es', 'Electrostatics', 'geom1');
es.feature('ccn1').set('epsilonr_mat', 1, 'userdef');
gnd1 = es.feature.create('gnd1', 'Ground', 1);
gnd1.selection.set(2);
sfcd1 = es.feature.create('sfcd1', 'SurfaceChargeDensity', 1);
sfcd1.selection.set(4);
sfcd1.set('rhoqs', 1, 'rhos');

4 Create a point probe at (0.8; 0.9):


pdom1 = model.probe.create('pdom1', 'DomainPoint');
pdom1.model('mod1');
pdom1.setIndex('coords2', '0.8', 0, 0);
pdom1.setIndex('coords2', '0.9', 0, 1);

The default expression of the probe being the electric potential V, you dont need to
redefine it.
5 Create the study and define the solver sequence:
std1 = model.study.create('std1');
stat1 = std1.feature.create('stat1', 'Stationary');
sol1 = model.sol.create('sol1');
sol1.study('std1');
sol1.feature.create('st1', 'StudyStep');
sol1.feature.create('v1', 'Variables');
sol1.feature.create('s1', 'Stationary');

6 To extract the state space matrices use the mphstate function as described below:
M = mphstate(model,'sol1','Out',{'MA','MB','C','D'},...
'input','rhos','output','mod1.ppb1');

The mphstate function runs the entire solver sequence sol1 and returns a structure
M containing the state-space matrices available at the following fields: M.MA, M.MB, M.C,
and M.D.
The matrices are assembled using the current solution vector as linearization point. If
you do not want to run the problem again when evaluating the state space matrices or
if you want to use a specific solution as linearization point you can create a new solver
sequence.

95 |

CHAPTER 6: CREATING STUDIES

The example below shows how to create a new solver sequence in order to extract the
state space system using the previous model already solved.
7 Enter the command below to create an new solver:
sol2 = model.sol.create('sol2');

You need then to attach the solver sequence to the existing study and a Variables
feature, this is done by entering the following commands:
sol2.feature.create('st1','StudyStep');
sol2.study('std1');
v1 = sol2.feature.create('v1','Variables');

Set the linearization point using the solution computed by the solver sequence sol1:
v1.set('initmethod','sol');
v1.set('initsol','sol1');

Extract the state space matrices using the mphstate function as the following:
M = mphstate(model,'sol2','Out',{'A','B','C','D'},...
'input','rhos','output','mod1.ppb1');

Note: In the case where the solver sequence solution sol1 is stored for several
parameter value, as for a time-dependent problem. You can set the linearization point
for a specific parameter value. This is possible with the command:
model.sol(<solname>).feature(<VarTag>).set(solnum,<sol_num>)

Retrieve Xmesh Information


The mphxmeshinfo function provide information about the numbering of elements,
nodes, and degrees of freedom (DOF) in the extended mesh and in the matrices
returned by assemble and the solvers.
Use the xmpeshinfo on a specified solver node:
info = mphxmeshinfo(model,'sol1',<solname>);

or a specified study step node:


info =
mphxmeshinfo(model,'sol1',<solname>,'studystep',<studystepname>);
info is a MATLAB structure that contains the following field:

ndofs, the number of degrees of freedom.

THE STUDY

96

fieldnames, the list of the dependent variable names.


fieldndofs, the number of degrees of freedom for each dependent variables.
meshtypes, the list of element type in use.
dofs, nodes and elements, information at specified levels.
The information at the DOF level consists in the geometry number (geomnums field),
the coordinates of each DOF (coords field), the nodes index (nodes field), the names
(dofnames field) and the name index (nameinds field).
The information at the nodes level consists in the coordinates of the nodes (coords
field), the name of the DOF (dofnames field) and the name index at each node (dofs
field).
For each type of element you can access the following element information: the local
node coordinate within the element (localcoords field), the local DOF coordinates
within the element (localdofcoords field), the local DOF names (localdofnames
field), the nodes and the DOF index (respectively nodes and dofs fields).

Creating Solution
You can use the createSolution method available for the solver feature in order to
create a new solution vector.
To create a proper solution vector, include both parameter values and the solution
vector, to proceed use the method setPVals and setU respectively:
model.sol(<solname>).setPVals(PVals);
model.sol(<solname>).setU(U);

Where <solname> is the solver tag, PVals the list of parameter values and U the
solution vector to use.
Finally create the solution vector with the createSolution method:
model.sol(<solname>).createSolution;
EXAMPLE: COMBINE SOLUTION VECTORS

This example illustrate how you can combine two transient solution vectors into one.
Each solution vector contains the solutions of a transient heat transfer problem for a
different set of time. The command illustrates how to combine the two solution
vectors in order to access the solution at all time steps directly from within the same
solution vector. Set up a basic 2D transient heat transfer problem, solve it for 200
seconds and save the model as a MPH file. Then solve for the next 200 seconds and

97 |

CHAPTER 6: CREATING STUDIES

save the second solution in a different file. The heat transfer problem consist of a
quarter of piece of copper with a an internal heat source of 5e5[w/m^3].
1 Run the command below at the MATLAB prompt in order to obtained the two

distinct solution vectors


model = ModelUtil.create('Model');
% create a square geometry with edge length set to 0.1
geom1 = model.geom.create('geom1', 2);
sq1 = geom1.feature.create('sq1', 'Square');
sq1.set('size', '0.1');
geom1.run;
% Set material properties
mat1 = model.material.create('mat1');
mat1.propertyGroup('def').set('thermalconductivity', {'400'});
mat1.propertyGroup('def').set('density', '8e3');
mat1.propertyGroup('def').set('heatcapacity', '2e3');
% Define the physics settings
ht = model.physics.create('ht', 'HeatTransfer', 'geom1');
temp1 = ht.feature.create('temp1', 'TemperatureBoundary', 1);
temp1.selection.set([1 2]);
hs1 = ht.feature.create('hs1', 'HeatSource', 2);
hs1.selection.set(1);
hs1.set('Q', '5e5[W/m^3]');
% Create a mesh case
mesh1 = model.mesh.create('mesh1', 'geom1');
% Create a study and run the model
std1 = model.study.create('std1');
time = std1.feature.create('time', 'Transient');
time.set('tlist', 'range(0,10,200)');
std1.run;
% Create a 1D plot group
pg1 = model.result.create('pg1', 'PlotGroup1D');
ptgr1 = pg1.feature.create('ptgr1', 'PointGraph');
ptgr1.selection.set(4);
% Save the first model as filename1. Include the full file name with
% the directory path.
model.save(filename1)
% Change the time stepping and use the current solution (t=200sec)
% as initial condition for the new calculation and run the study:
time.set('tlist', 'range(200,10,400)');
model.sol('sol1').feature('v1').set('initmethod', 'sol');

THE STUDY

98

model.sol('sol1').feature('v1').set('initsol', 'sol1');
std1.run;
% Save the first model as filename2
model.save('filename2')

2 Now that both solution vectors are created, load the models saved in filename1 and

filename2 as two different model object ('Model1' and 'Model2' respectively)


model1 = mphload('filename1','Model1');
model2 = mphload('filename2','Model2');

3 Compare the solutions by plotting the plot group pg1 for each model object:
mphplot(model1,'pg1')
mphplot(model2,'pg1')

4 Create a new model object 'Model' that contains the new combined solution
model = mphload(fullfile(tempdir,'Model_step1'),'Model');

5 Get the list of the time step for each model


PVals1 = model1.sol('sol1').getPVals;
PVals2 = model2.sol('sol1').getPVals;

6 Create a new list of time step. Note in this example PVals1(end) and PVals2(1) are

the same.
PVals = [PVals1;PVals2(2:end)];

7 Set the first solution vector (available in model1) to the new model object model.

The getU method extract the value of the solution vector, while the setU method
set a vector in a solution vector.
for i = 1:length(PVals1);
U = model1.sol('sol1').getU(i);
model.sol('sol1').setU(i,U);
end

8 Set the second solution vector (available in model2) to the new model object model,

after the existing solution.


n = size(PVals1,1);
for i=2:length(PVals2);
U = model2.sol('sol1').getU(i);
model.sol('sol1').setU(n+i-1,U);
end

99 |

CHAPTER 6: CREATING STUDIES

Note: The first time step of the second solution is disregarded as it is the same as the
last time step of the first solution vector.

9 Set the new time step list


model.sol('sol1').setPVals(PVals);

10 Create a new solution vector


model.sol('sol1').createSolution;

11 Plot the solution in a new MATLAB figure


figure
mphplot(model,'pg1')

THE STUDY

100

101 |

CHAPTER 6: CREATING STUDIES

Analyzing Results
This section introduces you to analyzing results using the LiveLink interface.

102

Results
This chapter describes how to do results analysis and visualization. You find additional
information on meshing in Results Evaluation and Visualization in the COMSOL
Multiphysics Users Guide.
Reference information on the meshing operations in the COMSOL Java API are
described in Results API in the COMSOL Java API Reference Guide 4.2.

The Plot Group Syntax


First create a plot group using the syntax
model.result.create(<tag>,dim);

where <tag> is a string that you use to refer to the plot group, and dim is the space
dimension of the plot group.
To add a plot feature to a plot group, use the syntax
model.result(<tag>).feature.create(<ftag>,<operation>);

where <tag> is the string you defined when creating the plot group. The string <ftag>
is a string that you use to refer to the plot feature. To set a property to a value in a plot
feature, enter
model.result(<tag>).feature(<ftag>).set(property,<value>);

where <ftag> is the string you defined when creating the feature.
Use the mphplot function to render the plot in a figure:
mphplot(model,<tag>)

This renders the plot group in a MATLAB plot using Handle Graphics. See the
reference entry for mphplot for more information.
Alternatively, to plot using a COMSOL plot window, enter
model.result(<tag>).run

This only works if you started COMSOL with the -graphics option.

Note: The plot on server option is not supported on MAC OS.

103 |

CHAPTER 7: ANALYZING RESULTS

You find further details under model.result() in the COMSOL Java API Reference
Guide.
The following sections contain examples of working with plot groups.

Using Plot Groups


Going back to the section A Simple Model Example, the following command creates
the plot group:
model.result.create('pg2',2);

A plot group needs a data set to plot. By default, a solution data set tagged 'dset1'
is created. You need to point the plot group to a data set:
model.result('pg2').set('data', 'dset1');

To add a contour plot feature to the plot group, enter,


cont1 = model.result('pg2').feature.create('cont1', 'Contour');
cont1.set('levels','range(1,1,9)');

Finally, to render the plot group in MATLAB, use the mphplot function:
mphplot(model,'pg2');

This renders the graphics in a MATLAB figure window. To plot the plot group in a
COMSOL graphics window, make sure you have started COMSOL with MATLAB
using the -graphics option and enter

RESULTS

104

mphplot(model,'pg2','server','on');

Note: The plot on server option is not supported on MAC OS.

To get a height plot (for 2D plots only) you can add a Height feature. For instance:
htgh1 =
model.result('pg1').feature('surf1').feature.create('htgh1','Heig
ht');
htgh1.set('heightdata','expr');
htgh1.set('expr','es.normE');

105 |

CHAPTER 7: ANALYZING RESULTS

mphplot(model,'pg1');

You can also define a color expression feature with a Color feature:
col1 = cont1.feature.create('col1','Color');
col1.set('col1','Color');
col1.set('expr','es.normE');
mphplot(model,'pg2');

To filter the color data (for example, to plot data only where x<0.5) you can create a
Filter feature:
filt1 = cont1.feature.create('filt1','Filter');
filt1.set('expr','x<0.5');

RESULTS

106

mphplot(model,'pg2');

To get a deformed plot you can create a Deform feature on the plot feature.
PLOT TYPE LISTINGS

The 1D plot group can be defined with the feature listed in the following table:
TABLE 7-1: FEATURES AVAILABLE FOR 1D PLOT GROUP
FEATURE NAME

DESCRIPTION

LineGraph

1D Line Plot

Global

Global data plot

PointGraph

Point plot

Table

Table plot

The 2D plot group can be defined with the feature listed in the following table:
TABLE 7-2: FEATURES AVAILABLE FOR 1D PLOT GROUP

107 |

FEATURE NAME

DESCRIPTION

ArrrowLine

Arrow plot along line

ArrowSurface

Arrow plot on surface

Contour

Contour plot

CoordSysSurface

Coordinate system plot

Line

2D Line plot

MaxMinLine

Max/min markers on line

MaxMinSurface

Max/min markers on surface

CHAPTER 7: ANALYZING RESULTS

TABLE 7-2: FEATURES AVAILABLE FOR 1D PLOT GROUP


FEATURE NAME

DESCRIPTION

Mesh

Mesh plot

Particle

Particle tracing plot

ParticleMass

Particle tracing with mass plot

PrincipalSurface

Principal stress/principal strain plot

ScatterSurface

Scatter plot

Streamline

Streamline plot

Surface

Surface plot

The 3D plot group can be defined with the feature listed in the following table:
TABLE 7-3: FEATURE AVAILABLE FOR 3D PLOT GROUP
FEATURE NAME

DESCRIPTION

ArrowLine

Arrow plot along line

ArrowSurface

Arrow plot on surface

ArrowVolume

Arrow plot in volume

Contour

Contour plot

CoordSysLine

Coordinate system plot on line

CoordSysSurface

Coordinate system plot on surface

CoordSysVolume

Coordinate system plot in volume

Isosurface

Isosurface plot

Line

Line plot

MaxMinLine

Max/min markers along line

MaxMinSurface

Max/min markers on surface

MaxMinVolume

Max/min markers in volume

Mesh

Mesh plot

Particle

Particle tracing plot

ParticleMass

Particle tracing with mass plot

PrincipalSurface

Principal stress/principal strain plot on surface

PrincipalVolume

Principal stress/principal strain plot in volume

ScatterVolume

Scatter plot in volume

Slice

Slice plot

Streamline

Streamline plot

RESULTS

108

TABLE 7-3: FEATURE AVAILABLE FOR 3D PLOT GROUP


FEATURE NAME

DESCRIPTION

Surface

Surface plot

Volume

Volume plot

PLOT FEATURE OPTIONS

Not all plot feature can have subfeatures (attributes). Below is the a list of subfeatures
for each plot type:
TABLE 7-4: SUBFEATURE LIST FOR PLOT TYPES
SUBFEATURE

PLOT TYPES

Color

ArrowLine, ArrowSurface, ArrowVolume, Contour, Isosurface,


Particle, ParticleMass, PrincipalSurface, PrincipalVolume, Streamline

Deform

ArrowLine, ArrowSurface, ArrowVolume, Contour, CoordSysLine,


CoordSysSurface, CoordSysVolume, Isosurface, Line, Mesh, Particle,
ParticleMass, PrincipalSurface, PrincipalVolume, Slice, Streamline,
Surface, Volume

Height

Surface (2D plots only)

Filter

ArrowLine, ArrowSurface, Contour, CoordSysLine, CoordSysSurface,


Isosurface, Line, Mesh, PrincipalSurface, Slice, Surface, Volume

POLAR PLOT

You can generate a polar plot by adding a polar plot group to the results node:
model.result.dataset.create(<pgname>, 'PolarGroup');

In a polar plot group you can set a Line, Point, Global, or Table plot. And then
define the radial and the angular spacing with the method .set(rspacing,<value>)
and .set(tsapcing,<value>), respectively.

The Data Set Syntax


Create a data set using the syntax
model.result.dataset.create(<tag>,dtype);

where <tag> is a string that you use to refer to the data set and dtype is a data set type.
To set a property to a value in a data set, type
model.result.dataset(<tag>).set(property,<value>);

where <tag> is the string you defined when creating the data set feature.

109 |

CHAPTER 7: ANALYZING RESULTS

USING DATA SETS

Using the simple example in A Simple Model Example, extend the results by showing
a cross-section line plot from the coordinates (0, 0.5) to (1, 0.5). To do this, you can
create a 2D cross section data set and an 1D plot group. Start by creating the data set:
model.result.dataset.create('cln1', 'CutLine2D');
model.result.dataset('cln1').setIndex('genpoints','0.5',0,1);
model.result.dataset('cln1').setIndex('genpoints','0.5',1,1);

Then create the 1D plot group with a line graph feature that uses the data set:
model.result.create('pg3', 1);
model.result('pg3').feature.create('lngr1', 'LineGraph');
model.result('pg3').set('data', 'cln1');

To plot the results, enter


mphplot(model,'pg3');

The following data sets are available:


TABLE 7-5: DATASET LIST
DATA SET NAME

DIMENSION

DESCRIPTION

Solution

All

Solution data set

Mesh

All

Mesh data set

CutPlane

Cross-section plane data set

CutLine3D

Cross-section line 3D data set

CutPoint3D

Cross-section point 3D data set

Edge3D

Edge data set

Isosurface

Isosurface data set

RESULTS

110

TABLE 7-5: DATASET LIST


DATA SET NAME

DIMENSION

DESCRIPTION

ParCurve3D

Parameterized curve 3D data set

ParSurface

Parameterized surface data set

Surface

Surface data set

Contour

Contour data set

CutLine2D

Cross-section line 2D data set

CutPoint2D

Cross-section point 2D data set

Edge2D

Edge data set

Mirror2D

Mirror 2D data set

Parametric2D

Parametric extrusion 2D data set

ParCurve2D

Parameterized curve 2D data set

Revolved2D

Revolution 2D data set

CutPoint1D

Cut point 1D data set

Parametric1D

Parametric extrusion 1D data set

Revolved1D

Revolution 1D data set

Evaluating Data
The function mpheval lets you evaluate the result on domains at the MATLAB
prompt.
For example, using the simple example in section A Simple Model Example, to evaluate
the electrical potential V in the node points of the model, enter
pd = mpheval(model,'V')

This returns a structure pd that contains the evaluated expressions and various other
information:
pd.p contains the node point coordinates information.
pd.t contains the indices to columns in pd.p of a simplex mesh; each column in
pd.t represents a simplex.
pd.ve contains the indices to mesh elements for each node points.
pd.expr contains the value of the expression V at each node points.
pd.unit contains the list of the unit of the expressions.
You can evaluate the expression on different element dimension level using the Edim
property. For instance, evaluate the electric potential on boundary 3:

111 |

CHAPTER 7: ANALYZING RESULTS

pd = mpheval(model,'V','Edim',1,'Selection',3);

It is possible to evaluate the expression on both the outer solution (the one generated
by a parametric sweep) or the inner solution (the one that result of the parametric, time
dependent, or eigenvalue solver). These solution can be accessed with the
Outersolnum and the Solnum property, respectively.
In the above example you can add a parametric step in the solver sequence node in
order to vary the surface charge density. First add a parameter in the model:
model.set.param.set('rhos','1e-10');

Set the surface charge density boundary condition with the new parameter:
sfcd1.set('rhoqs',1,'rhos');

Finally add activate the parametric analysis and set the parameter range to solve for:
std1.feature('stat').set('useparam','on');
std1.feature('stat').set('pname',{'rhos'});
std1.feature('stat').set('plist','range(1e-10,1e-10,10e-10)');

You can then run the study:


std1.run;

To access the electric potential for the third parameter value use:
pd = mpheval(model,'V','solnum',3)

Now you can add a parametric sweep in order to vary the relative permittivity of the
material. First of all define a new parameter for the relative permittivity:
model.set.param.set('mu','1');

Set the relative permittivity with the parameter name:


es.feature('ccn1').set('epsilonr_mat',1,'userdef');
es.feature('ccn1').set('epsilonr',{'mur'});

Add a parametric sweep node:


param = std1.feature.create('param','Parametric');
param.set('pname',{'mur'});
param.set('plist','1 2 3');

Run the study:


std1.run;

You can now evaluate the electric potential for mur=2 and rhos=5e-10 with the
following command:

RESULTS

112

pd = mpheval(model,'V','solnum',5,'outersolnum',2)

Evaluating Global Data


The function mphglobal lets you evaluate global variables data at the MATLAB
prompt. Following the previous example you can create an average operator avop1 to
evaluate the average value of the electric potential V:
model.cpl.create('avop1','Average','geom1');
model.cpl('avop1').selection.set(1);
model.sol('sol1').run;

Evaluate the global expression avop1(V):


V_ave = mphglobal(model,'avop1(V)');

Integrating Expressions
The function mphint lets you to evaluate the integral value of any expression at the
MATLAB prompt.
For instance, integrate the electric potential V over the domain and evaluate the surface
area of the geometry to manually compute the average electric potential:
Int_V = mphint(model,'V');
Surface = mphint(model,'1');
average = Int_V/Surface

Interpolating Data
The function mphinterp lets you interpolate results on domains.
For example, to interpolate the electric potential V at a specified set of coordinates,
enter
V = mphinterp(model,'V','coord',[0 0.1;0.1 0.1])

To extract the electrical potential along boundary 4 enter:


[V,y] = mphinterp(model,{'V','y'},'coord',[0:0.1:1],...
'edim',1,'selection',4);

113 |

CHAPTER 7: ANALYZING RESULTS

plot(y,V)

Generating Reports
The export method allows the user to generate an animation or to export data to an
external file (ASCII format).
ANIMATION EXPORT

You can define an animation 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.
To generate an animation, add an Animation node to the export method:
anim1 = model.result.export.create('anim1', 'Animation');

To change the animation type you can use either the imageseq or movie option as in
the following command:
anim1.set('type', 'imageseq');

To set the filename and run the animation use the following commands:
anim1.set(typefilename,<filenname>);
anim1.run;

With typefilename depending on the type of animation export: 'imagefilename'


for an image sequence, 'giffilename' for a gif animation, 'flashfilename' for a
flash animation, and 'avifilename' for an avi animation.

RESULTS

114

For a movie type it is possible to change the number of frames per second with the
command:
anim1.set('fps','fps_number');

where fps_number is the number of frame per second to use.


For all animation type you can modify the width and the height of the plot:
anim1.set('width','width_px');
anim1.set('height','height_px');

where width_px and height_px are the width and height size (in pixels) respectively
to use for the animation.
DATA EXPOR T

In order to extract data value to an ASCII file, create a Data node to the export
method:
data1 = model.result.export.create('data1', 'Data');

Set the expression and the filename, and run the export:
data1.setIndex('expr', 'T', 0);
data1.set('filename', <filenname>);
data1.run;

The export data structure <datstruct> can be set as spreadsheet or sectionwise:


data1.set('struct',<datstruct>);

The default data structure is spreadsheet, and the format is the following:
% Model:
% Version:
% Date:
% Dimension:
% Nodes:
% Expressions:
% Description:
% x
y
x1
y1
x2
y2

filename.mph
COMSOL 4.0.0.974
Jun 8 2010, 11:17
2
1272
20
data
data1
data2

In case of multiple solution fields (as for a parametric, transient, or eigenvalue analysis)
extra columns are added corresponding to solution data at each parameter, time step,
or eigenvalue.
The sectionwise data structure generates the file in the format below:
% Model:
% Version:

115 |

CHAPTER 7: ANALYZING RESULTS

filename.mph
COMSOL 4.0.0.974

% Date:
% Dimension:
% Nodes:
% Elements:
% Expressions:
% Description:
% Coordinates
x1
y1
x2
y2
...
% Elements (triangles)
node11
node12
node21
node22
...
% Data
data1
data2
...

Jun 8 2010, 11:28


2
1272
424
20

node13
node23

where nodeij is the jth node of the ith element.

RESULTS

116

117 |

CHAPTER 7: ANALYZING RESULTS

COMSOL 3.5a Compatibility


This section illustrates how to convert COMSOL 3.5a M-files to a format
compatible with LiveLink for MATLAB.
In this chapter:
Converting M-Files

118

Converting M-Files
In this section:
M-File Conversion
M-File Conversion, Including a For Loop
Converting Postprocessing Sequences
Unsupported Functions in COMSOL Multiphysics 4.2

M-File Conversion
LAUNCHING THE LIVELINK INTERFACE IN COMPATIBILITY MODE

To support the conversion from COMSOL 3.5a there is a separate launcher available,
which lets you run models represented in 3.5a syntax along with version 4 models. To
start MATLAB in compatibility mode, use the following:
Windows: Select COMSOL with MATLAB (COMSOL 3.5a Compatibility) under COMSOL 4.2
from the Windows Start menu.
Linux and Mac: Start COMSOL with MATLAB with the command
comsol server matlab -compat -c35aroot <COMSOL 3.5a root directory>

Having started MATLAB in this way you should have access to all documented
functionality in COMSOL 3.5a from MATLAB as well as the version 4 functionality
in LiveLink for MATLAB.
The conversion of an M-file from 3.5a to version 4 is based on running your M-file in
the compatibility mode and then using the mphv4 command to create a version 4
model object.
CONVERTING USING THE FEM STRUCTURE

The mphv4 command accepts a COMSOL 3.5a FEM structure as input. However, the
FEM structure does not contain any of the meshing settings, solver settings, nor the
postprocessing settings.
To convert any M-file using a FEM structure.
1 Run the M-file in compatibility mode to create a FEM structure.

119 |

CHAPTER 8: COMSOL 3.5A COMPATIBILITY

2 Run the mphv4 command:


model=mphv4(fem)

3 Save a version 4 M-file


model.save('model','m')

4 Edit the M-file, including settings for meshing, solving, results evaluation, and

visualization.
CONVER TING USING THE FEMGUI OBJECT

The mphv4 command accepts a COMSOL 3.5a FEM structure as input. The FEMGUI
object includes meshing settings, solver settings, and the postprocessing settings.
To convert any M-file using a FEMGUI object.
1 Make sure you have FEMGUI object available instead of a FEM structure:
fem=femgui

2 Run the M-file in compatibility mode to modify the FEMGUI object.


3 Run the mphv4 command:
model=mphv4(fem)

4 Save a version 4 M-file:


model.save('model','m')

5 Edit the M-file, including settings for meshing, solving, results evaluation, and

visualization.
EXAMPLES

This first example illustrates how to convert a Model M-file in 3.5a format to a 4.2
Model M-file. The following M-file is used for the conversion:
fem.geom=rect2(1.6,1,'base','corner','pos',[-0.8,0]);
fem.const={'Q0','1e5'};
fem.mesh=meshinit(fem,'hauto',3);
fem.appl.mode.class = 'HeatTransfer';
fem.appl.sshape = 2;
fem.appl.assignsuffix = '_ht';
fem.appl.bnd.type = {'q0','T'};
fem.appl.bnd.ind = [2,2,1,1];
fem.appl.equ.Q = 'Q0';
fem.appl.equ.ind = [1];
fem=multiphysics(fem);
fem.xmesh=meshextend(fem);

CONVERTING M-FILES

120

fem.sol=femstatic(fem,'solcomp',{'T'},'outcomp',{'T'});
postplot(fem,'tridata',{'T'}, ...
'trimap','Rainbow','axis',[-0.9,0.9,-0.6,1.6]);

1 Start COMSOL 4.2 with MATLAB (3.5a Compatibility) using the shortcut icon from the

Windows start menu, or enter the following command at the terminal prompt:
comsol matlab -compat -c35aroot <COMSOL 3.5a root directory>

If you want to save the mesh, solver, and postprocessing settings it is important to
define the variable fem as a FEMGUI object.
2 Edit the M-files and add the following line at the beginning of the script:
fem = femgui;

3 Save and run the model M-file at the MATLAB prompt. You can see the structure

of the FEMGUI object by typing fem on the command line:


>> fem
*fem =
appl:
shape:
border:
equ:
bnd:
pnt:
const:
geom:
mesh:
geomvalid:
solvalid:
xmesh:
sol:

[1x1 struct]
{'shlag(2,'T')'}
1
[1x1 struct]
[1x1 struct]
[1x1 struct]
{'Q0' '1e5'}
[1x1 rect2]
[1x1 femmesh]
'on'
'on'
[1x1 com.femlab.xmesh.Xmesh]
[1x1 femsol]

The * (asterisk) indicates that the variable fem is a FEMGUI object.


4 To convert the FEMGUI object fem run the mphv4 command:
model = mphv4(fem);

The resulting model object contains both the COMSOL 3.5a mesh object and
solution vector. Because fem is a FEMGUI object, the model also contains the mesh
and solver sequences defined in the M-file. To convert a FEM structure you can
follow the exact same procedure (just skip the second step in the above procedure).
You can get the mesh group information with the following command:
model.mesh.getList
ans =

121 |

CHAPTER 8: COMSOL 3.5A COMPATIBILITY

[Type: Mesh
Tag: mesh1
Current child node: obj
Number of child nodes: 2, Type: Mesh
Tag: mesh2
Current child node: ftri1
Number of child nodes: 2]

The above information indicates that the mesh group mesh1 is a mesh object (the
3.5a mesh object), and the mesh group mesh2 corresponds to the sequence defined
with the FEMGUI object.
To get the solution list:
model.sol.getList
ans =
[Type: Solver
Tag: sol1, Type: Solver
Tag: sol2]

sol1 contains the solver sequence, and sol2 is the 3.5a solution.

The reason of having both the 3.5a mesh and solution object and the corresponding
sequence is to allow you to use the exact same model and solution as in version 3.5a
or to run a sequence set up in version 3.5a.
5 You can work with the model object at the MATLAB prompt or save the model

object on the MPH format or as a M-file:


model.save('PATH/Converted') % Save on MPH format
model.save('PATH/Converted','m') % Save as a M format
PATH is the path of the directory where you want the file to be saved.

Saving the model as an M-file saves the geometry and the mesh object in the binary
files Converted_geom1.mphbin and Converted_mesh1_obj.mphbin. The model
M-file can be run directly.
To run the M-file using the mesh and the solver sequences, the following
modifications are required.
6 Edit the file ConvertedFEM.m, the file should be as the following:
function out = model
%
% Converted.m
%
% Model exported on May 28 2010, 11:05 by COMSOL 4.0.0.967.
import com.comsol.model.*
import com.comsol.model.util.*

CONVERTING M-FILES

122

model = ModelUtil.create('Model');
model.modelPath('Path');
model.param.set('Q0','1e5');
model.modelNode.create('mod1');
model.geom.create('geom1', 2);
model.geom('geom1').feature.create('CO1', 'Rectangle');
model.geom('geom1').feature('CO1').set('pos', '-0.8,0.0');
model.geom('geom1').feature('CO1').set('size', {'1.6' '1'});
model.geom('geom1').setGeom('Converted_geom1.mphbin');
model.physics.create('ht', 'HeatTransfer', 'geom1');
model.physics('ht').feature.create('hs1', 'HeatSource', 2);
model.physics('ht').feature('hs1').selection.set([1]);
model.physics('ht').feature.create('temp1', 'TemperatureBoundary', 1);
model.physics('ht').feature('temp1').selection.set([1 2]);
model.mesh.create('mesh1', 'geom1');
model.mesh('mesh1').feature.create('obj', 'MeshObject');
model.mesh.create('mesh2', 'geom1');
model.mesh('mesh2').feature.create('ftri1', 'FreeTri');
model.physics('ht').feature('solid1').set('k_mat', 'userdef');
model.physics('ht').feature('solid1').set('k', {'400'; '0'; '0'; '0'; '400';
'0'; '0'; '0'; '400'});
model.physics('ht').feature('solid1').set('rho_mat', 'userdef');
model.physics('ht').feature('solid1').set('rho', '8700');
model.physics('ht').feature('solid1').set('Cp_mat', 'userdef');
model.physics('ht').feature('solid1').set('Cp', '385');
model.physics('ht').feature('init1').set('T', '273.15');
model.physics('ht').feature('hs1').set('Q', 'Q0');
model.physics('ht').feature('temp1').set('T0', '273.15');
model.mesh('mesh1').feature('obj').set('filename',
'Converted_mesh1_obj.mphbin');
model.mesh('mesh1').run;
model.mesh('mesh2').feature('size').set('hmax', '0.058667');
model.mesh('mesh2').feature('size').set('hmin', '2.0E-4');
model.mesh('mesh2').feature('size').set('hcurve', '0.25');
model.mesh('mesh2').feature('size').set('hgrad', '1.25');
model.mesh('mesh2').feature('size').set('hauto', '3');
model.mesh('mesh2').feature('size').set('hmax', '0.058667');
model.mesh('mesh2').run;
model.study.create('std1');
model.study('std1').feature.create('stat1', 'Stationary');
model.sol.create('sol1');
model.sol.create('sol2');
model.sol('sol1').feature.create('st1', 'StudyStep');
model.sol('sol1').feature.create('v1', 'Variables');
model.sol('sol1').feature.create('s1', 'Stationary');

123 |

CHAPTER 8: COMSOL 3.5A COMPATIBILITY

model.sol('sol1').feature('s1').feature.create('fc1', 'FullyCoupled');
model.sol('sol1').feature('s1').feature.create('d1', 'Direct');
model.result.dataset('dset1').set('geom', 'geom1');
model.result.dataset('dset2').set('geom', 'geom1');
model.result.create('pg1', 2);
model.result('pg1').feature.create('surf1', 'Surface');
model.study('std1').feature('stat1').set('mesh', {'geom1' 'mesh1'});
model.sol('sol1').feature('st1').name('Compile Equations: Stationary 1');
model.sol('sol1').feature('st1').set('studystep', 'stat1');
model.sol('sol1').feature('v1').set('initsol', 'sol2');
model.sol('sol1').feature('v1').set('notsol', 'sol2');
model.sol('sol1').feature('s1').set('stol', '1e-006');
model.sol('sol1').feature('s1').feature('fc1').set('minstep', '0.0001');
model.sol('sol1').feature('s1').feature('d1').set('errorchk', 'off');
model.sol('sol2').name('COMSOL 3.5a Solution');
model.result('pg1').set('data', 'dset2');
model.result('pg1').feature('surf1').set('descr', 'T');
model.result('pg1').feature('surf1').set('smooth', 'none');
out = model;

7 The lines that correspond to the first mesh case (mesh1) must be removed. The first

mesh case corresponds to the imported mesh object. In the original M-file (see
above) the lines numbers are 30, 31, 45, and 46:
model.mesh.create('mesh1','geom1');
model.mesh('mesh1').feature.create('obj', 'MeshObject');
model.mesh('mesh1').feature('obj').set('filename',
'Converted_mesh1_obj.mphbin');
model.mesh('mesh1').run;

8 Delete the lines that use the 3.5a solution solver sequence. This is the second solver
sol2. In the original M-file (see above) the line numbers are 59, 75, 76, and 80:
model.sol.create('sol2');
model.result.dataset('dset2').set('geom','geom1');
model.sol('sol1').feature('v1').set('initsol','sol2');
model.sol('sol1').feature('v1').set('notsol','sol2');
model.sol('sol2').name('COMSOL 3.5a Solution');

9 Delete the line that creates the data set using the COMSOL 3.5a Solution (Line 67

in the original M-file):


model.result.dataset('dset2').set('geom', 'geom1');

10 Add the command to run the solver sequence after the definition of the solver

sequence (line 81 in the original M-file):


model.sol('sol1').runAll;

CONVERTING M-FILES

124

11 The first mesh case mesh1 has been removed from the model object definition. The

study node needs to be updated accordingly. Change from mesh1 to mesh2 on line
71(in the original M-file) as follows:
model.study('std1').feature('stat1').set('mesh',{'geom1'
'mesh2'});

12 The COMSOL 3.5a Solution data set has been removed from the model object

definition. The plot group needs to updated accordingly. Change dset2 to dset1
on line 82 (in the original M-file):
model.result('pg1').set('data','dset1');

13 The converted M-file should now look like the following:


function out = model
%
% Converted.m
%
% Model exported on May 28 2010, 11:05 by COMSOL 4.0.0.967.
import com.comsol.model.*
import com.comsol.model.util.*
model = ModelUtil.create('Model');
model.modelPath('Path');
model.param.set('Q0','1e5');
model.modelNode.create('mod1');
model.geom.create('geom1', 2);
model.geom('geom1').feature.create('CO1', 'Rectangle');
model.geom('geom1').feature('CO1').set('pos', '-0.8,0.0');
model.geom('geom1').feature('CO1').set('size', {'1.6' '1'});
model.geom('geom1').setGeom('Converted_geom1.mphbin');
model.physics.create('ht', 'HeatTransfer', 'geom1');
model.physics('ht').feature.create('hs1', 'HeatSource', 2);
model.physics('ht').feature('hs1').selection.set([1]);
model.physics('ht').feature.create('temp1', 'TemperatureBoundary', 1);
model.physics('ht').feature('temp1').selection.set([1 2]);
model.mesh.create('mesh2', 'geom1');
model.mesh('mesh2').feature.create('ftri1', 'FreeTri');
model.physics('ht').feature('solid1').set('k_mat', 'userdef');
model.physics('ht').feature('solid1').set('k', {'400'; '0'; '0'; '0'; '400';
'0'; '0'; '0'; '400'});
model.physics('ht').feature('solid1').set('rho_mat', 'userdef');
model.physics('ht').feature('solid1').set('rho', '8700');
model.physics('ht').feature('solid1').set('Cp_mat', 'userdef');
model.physics('ht').feature('solid1').set('Cp', '385');
model.physics('ht').feature('init1').set('T', '273.15');

125 |

CHAPTER 8: COMSOL 3.5A COMPATIBILITY

model.physics('ht').feature('hs1').set('Q', 'Q0');
model.physics('ht').feature('temp1').set('T0', '273.15');
model.mesh('mesh2').feature('size').set('hmax', '0.058667');
model.mesh('mesh2').feature('size').set('hmin', '2.0E-4');
model.mesh('mesh2').feature('size').set('hcurve', '0.25');
model.mesh('mesh2').feature('size').set('hgrad', '1.25');
model.mesh('mesh2').feature('size').set('hauto', '3');
model.mesh('mesh2').feature('size').set('hmax', '0.058667');
model.mesh('mesh2').run;
model.study.create('std1');
model.study('std1').feature.create('stat1', 'Stationary');
model.sol.create('sol1');
model.sol('sol1').feature.create('st1', 'StudyStep');
model.sol('sol1').feature.create('v1', 'Variables');
model.sol('sol1').feature.create('s1', 'Stationary');
model.sol('sol1').feature('s1').feature.create('fc1', 'FullyCoupled');
model.sol('sol1').feature('s1').feature.create('d1', 'Direct');
model.result.dataset('dset1').set('geom', 'geom1');
model.result.create('pg1', 2);
model.result('pg1').feature.create('surf1', 'Surface');
model.study('std1').feature('stat1').set('mesh', {'geom1' 'mesh1'});
model.sol('sol1').feature('st1').name('Compile Equations: Stationary 1');
model.sol('sol1').feature('st1').set('studystep', 'stat1');
model.sol('sol1').feature('s1').set('stol', '1e-006');
model.sol('sol1').feature('s1').feature('fc1').set('minstep', '0.0001');
model.sol('sol1').feature('s1').feature('d1').set('errorchk', 'off');
model.sol('sol1').runAll;
model.result('pg1').set('data', 'dset1');
model.result('pg1').feature('surf1').set('descr', 'T');
model.result('pg1').feature('surf1').set('smooth', 'none');
out = model;

14 Save the modified M-file.

The new M-file is ready to run. This regenerates a new mesh case in COMSOL 4.2.
Note that the mesh can differ slightly from the one obtained in version 3.5a. This does
not affect the results as long as the solution is not mesh dependent.

M-File Conversion, Including a For Loop


The first example consider that the a single FEM structure is set up in the M-file. It is
common to have more complicated M-files that combine COMSOL and MATLAB
commands. For instance including a MATLAB for loop in order to parameterize the

CONVERTING M-FILES

126

COMSOL model. In this case it is recommended to convert the FEM structure to the
model object at each iteration.
The following example illustrates a multiple parameterization procedure. Both
geometry parameters and the inlet velocity boundary condition are parameterized.
% The line below is added for the 4.2 conversion procedure
fem=femgui;
j = 1;
for L = [1 2]
for Q0 = [1e5 1e6]
fem.geom=rect2(L,1,'base','corner','pos',[-0.8,0]);
fem.const={'Q0',Q0,'L',L};
fem.mesh=meshinit(fem,'hauto',3);
fem.appl.mode.class = 'HeatTransfer';
fem.appl.sshape = 2;
fem.appl.assignsuffix = '_ht';
fem.appl.bnd.type = {'q0','T'};
fem.appl.bnd.ind = [2,2,1,1];
fem.appl.equ.Q = 'Q0';
fem.appl.equ.ind = [1];
fem=multiphysics(fem);
fem.xmesh=meshextend(fem);
fem.sol=femstatic(fem,'solcomp',{'T'},'outcomp',{'T'});
postplot(fem, 'tridata',{'T'},...
'trimap','Rainbow','axis',[-0.9,0.9,-0.6,1.6]);
% The two lines below are added for the 4.2 conversion procedure
model = mphv4(fem);
model.save(['Y:\v4_models\ConvertedFEM_',num2str(j),'.mph']);
j=j+1;
end
end

To translate the script in version 4.2, follow the procedure below:


1 Run the model M-file, this generates as many MPH file as you have iterations.
2 Load one of the model objects (for instance the first one) at the MATLAB prompt

with the following command:


model = ModelUtil.load('Model','ConvertedFEM_1.mph')

3 Save the model object as an M-file.


model.save('Converted_param','m')

127 |

CHAPTER 8: COMSOL 3.5A COMPATIBILITY

4 Edit Converted_param.m and modify the file according to the procedure details in

the previous example.


5 Note that the COMSOL 4.2 model object supports geometry parameterization

directly. Modify the geometry node settings such that they include the parameter L
as the definition of the length of the rectangle:
model.geom('geom1').feature('CO1').set('size', {'L' '1'});

6 Add for loops in the new M-file:


import com.comsol.model.*
import com.comsol.model.util.*
model = ModelUtil.create('Model');
model.modelNode.create('mod1');
model.modelPath('PATH');
model.param.set('Q0', 1e6);
model.param.set('L',2);
model.geom.create('geom1', 2);
model.geom('geom1').feature.create('CO1', 'Rectangle');
model.geom('geom1').feature('CO1').set('pos', '-0.8,0.0');
model.geom('geom1').feature('CO1').set('size', {'L' '1'});
model.geom('geom1').setGeom('Converted_param_geom1.mphbin');
model.physics.create('ht', 'HeatTransfer', 'geom1');
model.physics('ht').feature.create('hs1', 'HeatSource', 2);
model.physics('ht').feature('hs1').selection.set([1]);
model.physics('ht').feature.create('temp1', 'TemperatureBoundary', 1);
model.physics('ht').feature('temp1').selection.set([1 2]);
model.mesh.create('mesh2', 'geom1');
model.mesh('mesh2').feature.create('ftri1', 'FreeTri');
model.physics('ht').feature('solid1').set('k_mat', 'userdef');
model.physics('ht').feature('solid1').set('k', {'400'; '0'; '0'; '0'; '400';
'0'; '0'; '0'; '400'});
model.physics('ht').feature('solid1').set('rho_mat', 'userdef');
model.physics('ht').feature('solid1').set('rho', '8700');
model.physics('ht').feature('solid1').set('Cp_mat', 'userdef');
model.physics('ht').feature('solid1').set('Cp', '385');
model.physics('ht').feature('init1').set('T', '273.15');
model.physics('ht').feature('hs1').set('Q', 'Q0');
model.physics('ht').feature('temp1').set('T0', '273.15');
model.mesh('mesh2').feature('size').set('hmax', '0.058667');
model.mesh('mesh2').feature('size').set('hmin', '2.0E-4');
model.mesh('mesh2').feature('size').set('hcurve', '0.25');
model.mesh('mesh2').feature('size').set('hgrad', '1.25');
model.mesh('mesh2').feature('size').set('hauto', '3');
model.mesh('mesh2').feature('size').set('hmax', '0.058667');
model.mesh('mesh2').run;

CONVERTING M-FILES

128

model.study.create('std1');
model.study('std1').feature.create('stat1', 'Stationary');
model.sol.create('sol1');
model.sol('sol1').feature.create('st1', 'StudyStep');
model.sol('sol1').feature.create('v1', 'Variables');
model.sol('sol1').feature.create('s1', 'Stationary');
model.sol('sol1').feature('s1').feature.create('fc1', 'FullyCoupled');
model.sol('sol1').feature('s1').feature.create('d1', 'Direct');
model.result.dataset('dset1').set('geom', 'geom1');
model.result.create('pg1', 2);
model.result('pg1').feature.create('surf1', 'Surface');
model.study('std1').feature('stat1').set('mesh', {'geom1' 'mesh2'});
model.sol('sol1').feature('st1').name('Compile Equations: Stationary 1');
model.sol('sol1').feature('st1').set('studystep', 'stat1');
model.sol('sol1').feature('s1').set('stol', '1e-006');
model.sol('sol1').feature('s1').feature('fc1').set('minstep', '0.0001');
model.sol('sol1').feature('s1').feature('d1').set('errorchk', 'off');
model.result('pg1').set('data', 'dset1');
model.result('pg1').set('title', 'Surface: Temperature [K]');
model.result('pg1').set('titleactive', true);
model.result('pg1').feature('surf1').set('descr', 'T');
model.result('pg1').feature('surf1').set('smooth', 'everywhere');
% Start of the FOR loops
j=1;
for L = [1 2]
for Q0 = [1e5 1e6]
model.param.set('Q0', 1e5);
model.param.set('L',1);
model.sol('sol1').runAll;
model.save(['PATH\Converted_param_',num2str(j),'.mph']);
j=j+1;
end
end

Converting Postprocessing Sequences


In case of the model M-file contains several call of the postplot function, only the
settings of the last call are stored in the FEMGUI object. In order to convert each
postplot call to a plot group implementation in the model object you need to call the
mphv4 function after each plot using postplot.
The following example illustrate how to convert a M-file that use different postplot
call:
fem.geom=rect2(1.6,1,'base','corner','pos',[-0.8,0]);

129 |

CHAPTER 8: COMSOL 3.5A COMPATIBILITY

fem.const={'Q0','1e5'};
fem.mesh=meshinit(fem,'hauto',3);
fem.appl.mode.class = 'HeatTransfer';
fem.appl.sshape = 2;
fem.appl.assignsuffix = '_ht';
fem.appl.bnd.type = {'q0','T'};
fem.appl.bnd.ind = [2,2,1,1];
fem.appl.equ.Q = 'Q0';
fem.appl.equ.ind = [1];
fem=multiphysics(fem);
fem.xmesh=meshextend(fem);
fem.sol=femstatic(fem,'solcomp',{'T'},'outcomp',{'T'});
postplot(fem,'tridata',{'T'}, ...
'trimap','Rainbow','axis',[-0.9,0.9,-0.6,1.6]);
postplot(fem,'tridata','T','triz','T','trimap','Rainbow', ...
'contdata','flux_ht','contlevels',20,'contmap','Thermal');
postplot(fem,'arrowdata',{'fluxx_ht','fluxy_ht'}, ...
'arrowxspacing',15,'arrowyspacing',15, ...
'arrowtype','arrow', 'arrowcolor',[1.0,0.0,0.0]);

1 The first step consists of adding the command to overload the FEM structure during

M-file reading in order to get the FEMGUI object. Also add the command to
convert the FEMGUI object to a COMSOL 4.2 model object after each
postprocessing function and save each of the model objects on M-file format. The
M-file should be similar to the following:
fem=femgui;
fem.geom=rect2(1.6,1,'base','corner','pos',[-0.8,0]);
fem.const={'Q0','1e5'};
fem.mesh=meshinit(fem,'hauto',3);
fem.appl.mode.class = 'HeatTransfer';
fem.appl.sshape = 2;
fem.appl.assignsuffix = '_ht';
fem.appl.bnd.type = {'q0','T'};
fem.appl.bnd.ind = [2,2,1,1];
fem.appl.equ.Q = 'Q0';
fem.appl.equ.ind = [1];
fem=multiphysics(fem);
fem.xmesh=meshextend(fem);
fem.sol=femstatic(fem,'solcomp',{'T'},'outcomp',{'T'});

CONVERTING M-FILES

130

postplot(fem,'tridata',{'T'}, ...
'trimap','Rainbow','axis',[-0.9,0.9,-0.6,1.6]);
model=mphv4(fem);
model.save('PATH\plot_1','m')
postplot(fem,'tridata','T','triz','T','trimap','Rainbow', ...
'contdata','flux_ht','contlevels',20,'contmap','Thermal');
model=mphv4(fem);
model.save('PATH\plot_2','m')
postplot(fem,'arrowdata',{'fluxx_ht','fluxy_ht'}, ...
'arrowxspacing',15,'arrowyspacing',15, ...
'arrowtype','arrow', 'arrowcolor',[1.0,0.0,0.0]);
model=mphv4(fem);
model.save('PATH\plot_3','m')

2 You can now open plot_1.m and modify it according to the first example model.

The resulting 4.2 converted M-file should be the following:


function out = model
%
% Plot_1.m
%
% Model exported on May 28 2010, 11:05 by COMSOL 4.0.0.967.
import com.comsol.model.*
import com.comsol.model.util.*
model = ModelUtil.create('Model');
model.modelPath('Path');
model.param.set('Q0','1e5');
model.modelNode.create('mod1');
model.geom.create('geom1', 2);
model.geom('geom1').feature.create('CO1', 'Rectangle');
model.geom('geom1').feature('CO1').set('pos', '-0.8,0.0');
model.geom('geom1').feature('CO1').set('size', {'1.6' '1'});
model.geom('geom1').setGeom('Plot_1_geom1.mphbin');
model.physics.create('ht', 'HeatTransfer', 'geom1');
model.physics('ht').feature.create('hs1', 'HeatSource', 2);
model.physics('ht').feature('hs1').selection.set([1]);
model.physics('ht').feature.create('temp1', 'TemperatureBoundary', 1);
model.physics('ht').feature('temp1').selection.set([1 2]);
model.mesh.create('mesh2', 'geom1');
model.mesh('mesh2').feature.create('ftri1', 'FreeTri');

131 |

CHAPTER 8: COMSOL 3.5A COMPATIBILITY

model.physics('ht').feature('solid1').set('k_mat', 'userdef');
model.physics('ht').feature('solid1').set('k', {'400'; '0'; '0'; '0'; '400';
'0'; '0'; '0'; '400'});
model.physics('ht').feature('solid1').set('rho_mat', 'userdef');
model.physics('ht').feature('solid1').set('rho', '8700');
model.physics('ht').feature('solid1').set('Cp_mat', 'userdef');
model.physics('ht').feature('solid1').set('Cp', '385');
model.physics('ht').feature('init1').set('T', '273.15');
model.physics('ht').feature('hs1').set('Q', 'Q0');
model.physics('ht').feature('temp1').set('T0', '273.15');
model.mesh('mesh2').feature('size').set('hmax', '0.058667');
model.mesh('mesh2').feature('size').set('hmin', '2.0E-4');
model.mesh('mesh2').feature('size').set('hcurve', '0.25');
model.mesh('mesh2').feature('size').set('hgrad', '1.25');
model.mesh('mesh2').feature('size').set('hauto', '3');
model.mesh('mesh2').feature('size').set('hmax', '0.058667');
model.mesh('mesh2').run;
model.study.create('std1');
model.study('std1').feature.create('stat1', 'Stationary');
model.sol.create('sol1');
model.sol('sol1').feature.create('st1', 'StudyStep');
model.sol('sol1').feature.create('v1', 'Variables');
model.sol('sol1').feature.create('s1', 'Stationary');
model.sol('sol1').feature('s1').feature.create('fc1', 'FullyCoupled');
model.sol('sol1').feature('s1').feature.create('d1', 'Direct');
model.result.dataset('dset1').set('geom', 'geom1');
model.result.create('pg1', 2);
model.result('pg1').feature.create('surf1', 'Surface');
model.study('std1').feature('stat1').set('mesh', {'geom1' 'mesh1'});
model.sol('sol1').feature('st1').name('Compile Equations: Stationary 1');
model.sol('sol1').feature('st1').set('studystep', 'stat1');
model.sol('sol1').feature('s1').set('stol', '1e-006');
model.sol('sol1').feature('s1').feature('fc1').set('minstep', '0.0001');
model.sol('sol1').feature('s1').feature('d1').set('errorchk', 'off');
model.sol('sol1').runAll;
model.result('pg1').set('data', 'dset1');
model.result('pg1').feature('surf1').set('descr', 'T');
model.result('pg1').feature('surf1').set('smooth', 'none');
out = model;

3 To get the command corresponding to the implementation of the second plot

group, open Plot_2.m and search for and copy the following lines:
model.result.create('pg1', 2);
model.result('pg1').feature.create('surf1', 'Surface');
model.result('pg1').feature('surf1').feature.create('hght1', 'Height');

CONVERTING M-FILES

132

model.result('pg1').feature.create('con1', 'Contour');

and at the end of the files:


model.result('pg1').set('data', 'dset2');
model.result('pg1').feature('surf1').set('descr', 'T');
model.result('pg1').feature('surf1').set('smooth', 'none');
model.result('pg1').feature('con1').set('expr', 'flux_ht');
model.result('pg1').feature('con1').set('unit', '');
model.result('pg1').feature('con1').set('descr', 'flux_ht');
model.result('pg1').feature('con1').set('colortable', 'Thermal');
model.result('pg1').feature('con1').set('smooth', 'none');

4 Paste the above lines in the file Plot_1.m before the line out = model;
5 In the added line replace the plot group name pg1 to pg2.
6 Do the same for the plot group defined in Plot_3.m with the following lines:
model.result.create('pg1', 2);
model.result('pg1').feature.create('arws1', 'ArrowSurfac');

And these additional lines:


model.result('pg1').set('data', 'dset2');
model.result('pg1').feature('arws1').set('expr', {'fluxx_ht' 'fluxy_ht'});
model.result('pg1').feature('arws1').set('color', 'custom');
model.result('pg1').feature('arws1').set('customcolor', {'0.99 '0' '0'});

7 Paste the above lines in Plot_1.m and replace pg1 by pg3.


8 The final M-file should now look like the following:
function out = model
%
% Plot_1.m
%
% Model exported on May 28 2010, 11:05 by COMSOL 4.0.0.967.
import com.comsol.model.*
import com.comsol.model.util.*
model = ModelUtil.create('Model');
model.modelPath('Path');
model.param.set('Q0','1e5');
model.modelNode.create('mod1');
model.geom.create('geom1', 2);
model.geom('geom1').feature.create('CO1', 'Rectangle');
model.geom('geom1').feature('CO1').set('pos', '-0.8,0.0');
model.geom('geom1').feature('CO1').set('size', {'1.6' '1'});
model.geom('geom1').setGeom('Plot_1_geom1.mphbin');
model.physics.create('ht', 'HeatTransfer', 'geom1');
model.physics('ht').feature.create('hs1', 'HeatSource', 2);

133 |

CHAPTER 8: COMSOL 3.5A COMPATIBILITY

model.physics('ht').feature('hs1').selection.set([1]);
model.physics('ht').feature.create('temp1', 'TemperatureBoundary', 1);
model.physics('ht').feature('temp1').selection.set([1 2]);
model.mesh.create('mesh2', 'geom1');
model.mesh('mesh2').feature.create('ftri1', 'FreeTri');
model.physics('ht').feature('solid1').set('k_mat', 'userdef');
model.physics('ht').feature('solid1').set('k', {'400'; '0'; '0'; '0'; '400';
'0'; '0'; '0'; '400'});
model.physics('ht').feature('solid1').set('rho_mat', 'userdef');
model.physics('ht').feature('solid1').set('rho', '8700');
model.physics('ht').feature('solid1').set('Cp_mat', 'userdef');
model.physics('ht').feature('solid1').set('Cp', '385');
model.physics('ht').feature('init1').set('T', '273.15');
model.physics('ht').feature('hs1').set('Q', 'Q0');
model.physics('ht').feature('temp1').set('T0', '273.15');
model.mesh('mesh2').feature('size').set('hmax', '0.058667');
model.mesh('mesh2').feature('size').set('hmin', '2.0E-4');
model.mesh('mesh2').feature('size').set('hcurve', '0.25');
model.mesh('mesh2').feature('size').set('hgrad', '1.25');
model.mesh('mesh2').feature('size').set('hauto', '3');
model.mesh('mesh2').feature('size').set('hmax', '0.058667');
model.mesh('mesh2').run;
model.study.create('std1');
model.study('std1').feature.create('stat1', 'Stationary');
model.sol.create('sol1');
model.sol('sol1').feature.create('st1', 'StudyStep');
model.sol('sol1').feature.create('v1', 'Variables');
model.sol('sol1').feature.create('s1', 'Stationary');
model.sol('sol1').feature('s1').feature.create('fc1', 'FullyCoupled');
model.sol('sol1').feature('s1').feature.create('d1', 'Direct');
model.result.dataset('dset1').set('geom', 'geom1');
model.result.create('pg1', 2);
model.result('pg1').feature.create('surf1', 'Surface');
model.study('std1').feature('stat1').set('mesh', {'geom1' 'mesh1'});
model.sol('sol1').feature('st1').name('Compile Equations: Stationary 1');
model.sol('sol1').feature('st1').set('studystep', 'stat1');
model.sol('sol1').feature('s1').set('stol', '1e-006');
model.sol('sol1').feature('s1').feature('fc1').set('minstep', '0.0001');
model.sol('sol1').feature('s1').feature('d1').set('errorchk', 'off');
model.sol('sol1').runAll;
model.result('pg1').set('data', 'dset1');
model.result('pg1').feature('surf1').set('descr', 'T');
model.result('pg1').feature('surf1').set('smooth', 'none');
model.result.create('pg2', 2);
model.result('pg2').feature.create('surf1', 'Surface');

CONVERTING M-FILES

134

model.result('pg2').feature('surf1').feature.create('hght1', 'Height');
model.result('pg2').feature.create('con1', 'Contour');
model.result('pg2').set('data', 'dset2');
model.result('pg2').feature('surf1').set('descr', 'T');
model.result('pg2').feature('surf1').set('smooth', 'none');
model.result('pg2').feature('con1').set('expr', 'flux_ht');
model.result('pg2').feature('con1').set('unit', '');
model.result('pg2').feature('con1').set('descr', 'flux_ht');
model.result('pg2').feature('con1').set('colortable', 'Thermal');
model.result('pg2').feature('con1').set('smooth', 'none');
model.result.create('pg3', 2);
model.result('pg3').feature.create('arws1', 'ArrowSurfac');
model.result('pg3').set('data', 'dset2');
model.result('pg3').feature('arws1').set('expr', {'fluxx_ht' 'fluxy_ht'});
model.result('pg3').feature('arws1').set('color', 'custom');
model.result('pg3').feature('arws1').set('customcolor', {'0.99 '0' '0'});
out = model;

Unsupported Functions in COMSOL Multiphysics 4.2


The MATLAB command colon (or : operator) is not interpreted by mphv4. The
converted script does not contain the list as originally defined.
fem=femgui;
fem.geom = circ2;
fem.mesh = meshinit(fem);
fem.shape = 2; fem.equ.c = 1; fem.equ.f = 'para'; fem.bnd.h = 1;
fem.xmesh = meshextend(fem);
fem.sol = femlin(fem,'pname','para','plist',[0:0.01:1]);
model=mphv4(fem);

The resulting model object does not include the proper parameter value list for
continuation parameter. To set the parameter list value enter
model.study('std1').feature('stat1').set('plist',
'range(0,0.01,1)');

and

135 |

CHAPTER 8: COMSOL 3.5A COMPATIBILITY

model.sol('sol1').feature('s1').feature('p1').set('plist',
'range(0,0.01,1)');

In a most general case (with long complicated lists) it is recommended to convert a


M-file that has a simplified expression as parameter list in the original FEM
structure, for example, ...,'plist',[0 1],..
Then once the model is converted, save it as an M-file. Edit the file and replace the
command set('plist', '0 1') by set('plist', 'your_list').
The mphv4 command only converts the results plot defined by postplot. If you
have a cross-section plot you need to generate a cut line or cut plane data set in the
model object and use this data set for the plot group.
Other postprocessing operations must be converted manually in the M-file; see the
following conversion table for the COMSOL wrapper functions:
TABLE 8-1: CONVERSION TABLE FOR PLOTTING AND EVALUATION FUNCTIONS
COMSOL 3.5A

COMSOL 4.2

posteval

mpheval

geomplot

mphgeom

postglobal

mphglobal

postint

mphint

postinterp

mphinterp

assemble

mphmatrix

meshplot

mphmesh

femstate

mphstate

CONVERTING M-FILES

136

137 |

CHAPTER 8: COMSOL 3.5A COMPATIBILITY

Command Reference
The main reference for the syntax of the commands available with LiveLink for
MATLAB is the COMSOL Java API Reference Guide. This section documents
additional interface functions that come with the product.

138

Summary of Commands
mphcd
mphdoc
mpheval
mphgeom
mphgetadj
mphgetcoords
mphgetp
mphgetproperties
mphgetu
mphglobal
mphint
mphinterp
mphload
mphmatrix
mphmesh
mphmeshstats
mphmodel
mphnavigator
mphplot
mphsave
mphselectbox
mphselectcoords
mphstart
mphstate
mphversion
mphviewselection
mphv4
mphxmeshinfo

139 |

CHAPTER 9: COMMAND REFERENCE

C o m m a nds G r ou p ed b y Fu n c t i on
Interface Functions
FUNCTION

PURPOSE

mphdoc

Return HTML help of a specified function.

mphload

Load a COMSOL model MPH-file.

mphsave

Save a COMSOL model.

mphcd

Change directory to the directory of the model.

mphstart

Connect MATLAB to a COMSOL server.

mphversion

Return the version number of COMSOL Multiphysics.

Geometry Functions
FUNCTION

PURPOSE

mphgeom

Plot a geometry in a MATLAB figure.

mphviewselection

Display a geometric entity selection in a MATLAB figure.

Mesh Functions
FUNCTION

PURPOSE

mphmesh

Plot a mesh in a MATLAB figure.

mphmeshstats

Return mesh statistics and mesh information.

Utility Functions
FUNCTION

PURPOSE

mphgetadj

Return geometry entity indices that are adjacent to other.

mphgetcoords

Return point coordinates of geometry entities

mphgetp

Obtain information about a solution.

mphgetu

Return solution vector.

mphxmeshinfo

Extract information about the Xmesh.

mphmatrix

Get model matrices.

mphstate

Get state-space matrices for dynamic system.

COMMANDS GROUPED BY FUNCTION

140

FUNCTION

PURPOSE

mphselectbox

Select geometric entity using a rubberband/box.

mphselectcoords

Select geometric entity using point coordinates.

Postprocessing Functions
FUNCTION

PURPOSE

mpheval

Evaluate expressions on node points.

mphglobal

Evaluate global quantities.

mphint

Perform integration of expressions.

mphinterp

Evaluate expressions in arbitrary points or data sets.

mphplot

Render a plot group in a figure window.

Model information and navigation


FUNCTION

PURPOSE

mphnavigator

GUI for viewing the COMSOL model object.

mphmodel

Return tags for the nodes and subnodes in the COMSOL model
object.

mphmodel

Extract properties from a model node.

COMSOL Multiphysics 3.5a Compatibility Functions

141 |

FUNCTION

PURPOSE

mphv4

Convert a FEM structure or a FEMGUI object to a model


object.

CHAPTER 9: COMMAND REFERENCE

mphcd
Change directory to the directory of the model

Purpose

mphcd

Syntax

mphcd(model)

Description

mphcd(model) changes the current directory in MATLAB to the directory where

the model was last saved.


See aalso

mphload, mphsave

142

mphdoc
Return HTML help of a specified function.

Purpose

mphdoc

Syntax

mphdoc arg1
mpdoc arg1 arg2

Description

mphdoc arg1 returns the HTML documentation associated to the function arg1.
mphdoc arg1 arg2 returns the HTML documentation associated to the function
arg1.('arg2').
mphdoc arg1 arg2 -web returns the HTML documentation associated to the
function arg1.('arg2') in the default web browser.

Example

Create a model object


model=ModelUtil.creat('Model')

Get the documentation for the mesh node


mphdoc model.mesh

Get the documentation for the rectangle feature


model.geom.create('geom1',2);
mphdoc model.geom('geom1') Rectangle

Display the documentation with the default web browser


mphdoc model.sol -web

143 |

CHAPTER 9: COMMAND REFERENCE

mpheval
Evaluate expressions on node points.

Purpose

mpheval

Syntax

pd = mpheval(model,{e1,e2,...,en},...)

Description

pd = mpheval(model,{e1,e2,...,en},...) returns the post data pd for the

expressions e1,e2,...,en.
The value pd is post data, a structure with fields p, t, ve, and fields for data values.
The field p contains node point coordinate information. The number of rows in p
is the number of space dimensions. The field t contains the indices to columns in p
of a simplex mesh, each column in t representing a simplex. The field ve contains
indices to mesh elements for each node point. For each expression e1,e2,...,en
a field with the name d1,d2,... dn is added with the numerical values. The
columns in the data value fields correspond to node point coordinates in columns
in p. The field expr contains the expression name evaluated. The field unit contains
the list of the unit for each expression. The data contains the real part of
complex-valued expressions.
The function mpheval accepts the following property/value pairs:
TABLE 9-1: PROPERTY/VALUE PAIRS FOR THE MPHEVAL COMMAND.
PROPERTY

PROPERTY
VALUE

DEFAULT

DESCRIPTION

Complexfun

off | on

on

Use complex-valued functions with


real input

Complexout

off | on

off

Return complex values

Dataset

String

Edim

0 | 1 | 2 |
3

Geometry
space
dimension

Evaluate on elements with this


space dimension.

Matherr

off | on

off

Error for undefined operations or


expressions

Outersolnum

Positive
integer

Solution number for parametric


sweep

Pattern

lagrange |
gauss

lagrange

Specifies if evaluation takes place in


Lagrange points or in Gauss points.

Phase

Scalar

Phase angle in degrees

Recover

off | ppr |
pprint

off

Accurate derivative recovery.

Refine

Integer

Refinement of elements for


evaluation points

Data set tag name

144

mpheval

TABLE 9-1: PROPERTY/VALUE PAIRS FOR THE MPHEVAL COMMAND.


PROPERTY

PROPERTY
VALUE

DEFAULT

DESCRIPTION

Selection

Integer
vector

All
domains

Domain selection list

Smooth

internal |
none |
everywhere

internal

Smoothing setting

Solnum

Integer
vector |
all | end

all

Solutions for evaluation

Double
array

Times for evaluation

The property Dataset controls which data set is used for the evaluation. Data Sets
contain or refer to the source of data for postprocessing purposes. Evaluation is
supported only on Solution Data Sets.
The property Edim decides which elements to evaluate on. Evaluation takes place
only on elements with space dimension Edim. If not specified, Edim=sdim is used,
where sdim is the space dimension of the geometry. For example, in a 3D model, if
evaluation is done on edges (1D elements), Edim is 1. Similarly, for boundary
evaluation (2D elements), Edim is 2, and for domain evaluation (3D elements),
Edim is 3 (default in 3D).
Use Recover to recover fields using polynomial-preserving recovery. This
techniques recover fields with derivatives such as stresses or fluxes with a higher
theoretical convergence than smoothing. Recovery is expensive so it is turned off by
default. The value pprint means that recovery is performed inside domains. The
value ppr means that recovery is also applied on all domain boundaries.
The property Refine constructs evaluation points by making a regular refinements
of each element. Each mesh edge is divided into Refine equal parts.
The property Smooth controls if the post data is forced to be continuous on element
edges. When Smooth is set to internal, only elements not on interior boundaries are
made continuous.
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.

145 |

CHAPTER 9: COMMAND REFERENCE

mpheval
When the property Phase is used, the solution vector is multiplied with
exp(i*phase) before evaluating the expression.
The expressions e1,e2,...,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

Load micromixer.mph from the Model Library:


model = mphload('micromixer.mph');

Evaluate the pressure p at all node points:


dat = mpheval(model,'p');

Evaluate the concentration c at the outlet boundary:


dat = mpheval(model,'c','edim',2,'selection',136);

Evaluate the pressure on all geometric vertices:


dat = mpheval(model,'p','edim',0);
See also

mphglobal, mphint, mphinterp

146

mphgeom
Plot a geometry in a MATLAB figure.

Purpose

mphgeom

Syntax

mphgeom(model,geomname)
mphgeom(model,geomname,...)

Description

mphgeom(model,geomname,...) creates a MATLAB plot of the geometry


geomname.
mphgeom(model,geomname,...) creates a MATLAB plot of the geometry
geomname with the figure properties.

Valid property include:


TABLE 9-2: PROPERTY/VALUE PAIRS FOR THE MPHGEOM COMMAND

Example

PROPERTY

VALUE

Parent

Double

DEFAULT

Parent axes

Selection

Double

Selection

Entity

point |
edge |
boundary |
domain

Geometric entity to
select

Build

on | off |
current

on

Build the geometry


before plotting

Edgecolor

Char

Edge color

Edgelabels

on | off

off

Show edge labels

Edgelabelscolor

Char

Color for edge labels

Edgemode

on | off

on

Show edges

Facealpha

Double

Use transparency

Facelabels

on | off

off

Show face labels

Facelabelscolor

Char

Color for face labels

Facemode

on | off

on

Show faces

Vertexlabels

on | off

off

Show vertex labels

Vertexlabelscolor

Char

Color for vertex


labels

Vertexmode

on | off

off

Show vertices

Load shell_diffusion.mph from the Model Library:


model = mphload('shell_diffusion.mph');

Plot the geometry geom1:

147 |

CHAPTER 9: COMMAND REFERENCE

DESCRIPTION

mphgeom
mphgeom(model,'geom1')

Plot the geometry in an existing figure:


figure
mphgeom(model,'geom1', ...
'parent',gca, ...
'edgecolor','k', ...
'edgelabels','on', ...
'alpha',0.5,...
'edgelabelscolor','b', ...
'vertexmode','on',...
'edgemode','on');

148

mphgetadj
Return geometry entity indices that are adjacent to other.

Purpose

mphgetadj

Syntax

n = mphgetadj(model,geomname,returntype,adjtype,adjnumber)

Description

n = mphgetadj(model,geomname,returntype,adjtype,adjnumber) returns

the indices of the adjacent geometry entities.


returntype is the type of the geometry entities whose index are returned.
adjtype is the type of the input geometry entity.

The entity type can be one of 'point', 'edge', 'boundary' or 'domain'


following the entity space dimension defined below:

'domain': maximum geometry space dimension

'boundary': maximum geometry space dimension -1

'edges': 1(only for 3D geometry)

Example

'point': 0

Load example model busbar.mph from the Model Library:


model = mphload('busbar.mph');

Returns the indices of the domains adjacent to point 2:


n = mphgetadj(model, 'geom1', 'domain', 'point', 2);

Returns the indices of the points adjacent to domains 2 and 3:


n = mphgetadj(model, 'geom1', 'point', 'domain', [2 3]);
See also

149 |

mphgetcoords, mphselectbox, mphselectcoords

CHAPTER 9: COMMAND REFERENCE

mphgetcoords
Return point coordinates of geometry entities.

Purpose

mphgetcoords

Syntax

c = mphgetcoords(model,geomane,entitytype,entitynumbers)

Description

c = mphgetcoords(model,geomane,entitytype,entitynumbers) returns the

coordinates of the points that belong to the entity object with the type entitytype
and the index entitynumber.
The entitytype property can be one of 'point', 'edge', 'boundary' or
'domain' following the entity space dimension defined below:

'domain': maximum geometry space dimension

'boundary': maximum geometry space dimension -1

'edges': 1(only for 3D geometry)


'point': 0
Example

Load example model busbar.mph from the Model Library:


model = mphload('stresses_in_pulley.mph');

Return the coordinates of points that belong to domain 1:


c = mphgetcoords(model, 'geom1', 'domain', 1);

Return the coordinates of points that belong to boundary 5:


c = mphgeomcoords(model, 'geom1', 'boundary', 5);

Return the coordinates of point 10:


c = mphgeomcoords(model, 'geom1', 'point', 10);
See also

mphgetadj, mphselectbox, mphselectcoords

150

mphgetp
Obtain information about a solution.

Purpose

mphgetp

Syntax

[sz,ndofs,data,name,type] = mphgetp(model)
[sz,ndofs,data,name,type] = mphgetp(model,'solname',sol)

Description

[sz,ndofs,data,name,type] = mphgetp(model) returns information about the

default solution data set.


[sz,ndofs,data,name,type] = mphgetp(model,'solname',sol) returns

information about the solution data set sol.


sz contains the size of the solution vector and the number of solutions. ndofs

contains the number of degrees of freedom. data contains the values of the
parameters, for a parametric solution, the output times for a transient solution or
eigenvalues for an eigenvalue solution. name contains the name of the parameters,
time or eigenvalue variable. type contains a string with the type of the solver, which
can be either Stationary, Time, or Eigenvalue.
TABLE 9-3: PROPERTY/VALUE PAIRS FOR THE MPHGETP COMMAND
PROPERTY

VALUE

DEFAULT

DESCRIPTION

Solname

String

Active solution data


set

Solver node tag

Studysteptag

String

st1

Study step tag

The study step tag must be the tag of a node of type StudyStep (Compile
Equations) or Variables.
The Solname property set the solution data set to use associated with the defined
solver node.
Example

Load example model stresses_in_pulley.mph from the Model Library:


model = mphload('stresses_in_pulley.mph');
[sz,ndofs,list,name,type]=mphgetp(model)

Get the size and degrees of freedom for the variables for sol1:
[sz,ndofs]=mphgetp(model,'solname','sol1','studysteptag','v1')

Get the solution information for the second solution data set:
[sz,ndofs,list,name,type]=mphgetp(model,'solname','sol2')
See also

151 |

mphgetu

CHAPTER 9: COMMAND REFERENCE

mphgetproperties
Extract properties from a model node

Purpose

mphgetproperties

Syntax

mphproperties(node)

Description

mphproperties(node) returns properties that are defined for the node node.

Example

Load busbar.mph from the Model Library:


model = mphload('busbar');

Get the properties of the node model.result('pg1'):


prop = mphgetproperties(model.result('pg1'))
See also

mphnavigator

152

mphgetu
Return solution vector.

Purpose

mphgetu

Syntax

U = mphgetu(model,...)
[U,Udot] = mphgetu(model,...)

Description

U = mphgetu(model) returns the solution vector U for the default solution data set.
[U,Udot] = mphgetu(model,...) returns in addition Udot, which is the time

derivative of the solution vector. This syntax is available for a time-dependent


solution only.
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.
TABLE 9-4: PROPERTY/VALUE PAIRS FOR THE MPHGETU COMMAND
PROPERTY

VALUE

DEFAULT

DESCRIPTION

Solname

String

Auto

Solver node tag

Solnum

Positive integer
vector

Auto

Solution for evaluation

The Solname property set the solution data set to use associated with the defined
solver node.
Example

Load cylinder_flow.mph from the Model Library:


model = mphload('cylinder_flow.mph');

Get the solution vector for the last time step (default solution number):
u = mphgetu(model);

Get the solution vector and its derivative for solution number 4:
[u,ut] = mphgetu(model,'solnum',4);
See also

153 |

mphgetp

CHAPTER 9: COMMAND REFERENCE

mphglobal
Evaluate global quantities.

Purpose

mphglobal

Syntax

[d1,d2,...,dn] = mphglobal(model,{e1,e2,...,en},...)

Description

data = mphglobal(model,{e1,e2,...,en},...) returns the results from

evaluating the global quantities specified in the string expression e1, e2,..., en.
[d1,d2,...,dn,unit] = mphglobal(model,{e1,e2,...,en},...) returns the

results from evaluating the global quantities specified in the string expression e1,
e2, ..., en. unit is a nx1 cell array that contains the unit of the different

expressions evaluated.
Valid property/value pairs include:
TABLE 9-5: PROPERTY/VALUE PAIRS FOR THE MPHGLOBAL COMMAND.
PROPERTY

PROPERTY VALUE

DEFAULT

DESCRIPTION

Complexfun

off | on

on

Use complex-valued
functions with real input

Complexout

off | on

off

Return complex values

Dataset

String

Active solution
data set

Data set tag name

Matherr

off | on

off

Error for undefined


operations or expressions

Outersolnum

Positive
integer

Solution number for


parametric sweep

Phase

Scalar

Phase angle in degrees

Solnum

Integer vector
| all | end

all

Solution for evaluation

Double array

Time for evaluation

Unit

String | cell
array

Unit to use for the


evaluation

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.
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

154

mphglobal
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.
Solnum is used to select the solution number when a parametric, eigenvalue or
time-dependent solver has been used.
Outersolnum is used to select the outer solution number when a parametric sweep

has been used in the study step node.


Example

Load fluid_valve.mph from the Model Library:


model = mphload('fluid_valve.mph');

Evaluate the global expression u_up for each time step:


u_up = mphglobal(model,'u_up')

Evaluate the global expression u_up at t = 0.8 sec:


u_up = mphglobal(model,'u_up','t',0.8)

Evaluate the expressions u_up and u_down at the last solution number:
[u_up,u_down] =
mphglobal(model,{'u_up','u_down'},'solnum','end')

Evaluate the expressions u_up in mm^2/s and u_down in cm^2/s:


[u_up,u_down] =
mphglobal(model,{'u_up','u_down'},'unit',{'mm^2/s','cm^2/s'});
See also

155 |

mpheval, mphint, mphinterp

CHAPTER 9: COMMAND REFERENCE

mphint
Perform integration of expressions.

Purpose

mphint

Syntax

val = mphint(model,{e1,e2,...,en},...)

Description

val = mphint(model,{e1,e2,...,en},...) evaluates the integrals of the string

expressions e1,e2,...,en and returns the result in the matrix val with N rows and
M columns. M is the length of the vector Solnum.
[val,unit] = mphint(model,{e1,e2,...,en},...) in addition return the

units of the integral in a nx1 cell array.


Valid property/value pairs include:
TABLE 9-6: PROPERTY/VALUE PAIRS FOR THE MPHINT COMMAND.
PROPERTY

PROPERTY VALUE

DEFAULT

DESCRIPTION

Dataset

String

active
solution
data set

Data set tag name

Edim

1 | 2 | 3

geometry
space
dimension

Element dimension

Intorder

Positive integer

Integration order

Intsurface

on | off

off

Compute surface integral

Intvolume

on | off

off

Compute volume integral

Matherr

off | on

off

Error for undefined


operations or expressions

Method

auto |
integration |
summation

auto

Integration method

Outersolnum

Positive integer

Solution number for


parametric sweep

Selection

Integer vector |
all

all

Domain list

Solnum

Integer vector |
end | all

all

Solution for evaluation

Double array

Time for evaluation

unit

String | cell
array

Unit to use for evaluation

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.

156

mphint
The property Edim decides which elements to evaluate on. Evaluation takes place
only on elements with space dimension Edim. If not specified, Edim=sdim is used,
where sdim is the space dimension of the geometry. 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 expressions e1,e2,...,en are integrated for one or several solutions. Each
solution generates an additional column in the returned matrix. The property
Solnum and t control which solutions are used for the integrations. The Solnum
property is available when the data set has multiple solutions, for example in the case
of parametric, eigenfrequency, or time-dependent solutions. The t property is
available only for time-dependent problems. If Solnum is provided, the solutions
indicated by the indices provided with the Solnum property are used. If t is provided
solutions are interpolated. If neither Solnum nor t is provided, all solutions are
evaluated.
For time-dependent problems, the variable t can be used in the expressions ei. The
value of t is the interpolation time when the property t is provided, and the time
for the solution, when Solnum is used. Similarly, lambda and the parameter are
available as eigenvalues for eigenvalue problems and as parameter values for
parametric problems, respectively.
The unit property defines the unit of the integral, if a inconsistent unit is entered,
the default unit is used. In case of multiple expression, if the unit property is
defined with a string, the same unit is used for both expressions. To use different
units, set the property with a cell array. In case of inconsistent unit definition, the
default unit is used instead.
Solnum is used to select the solution number when a parametric, eigenvalue or
time-dependent solver has been used.
Outersolnum is used to select the outer solution number when a parametric sweep

has been used in the study step node.


Example

Load micromixer.mph from the Model Library:


model = mphload('micromixer.mph');

Integrate the x-velocity u at the outlet boundary and get its unit:
[flow unit]= mphint(model,'u','edim',2,'selection',136)

Return the value of the outlet flow in [mm^3/s]:

157 |

CHAPTER 9: COMMAND REFERENCE

mphint
flow =
mphint(model,'u','edim',2,'selection',136,'unit','mm^3/s')

Load heat_transfer_axi.mph from the Model Library:


model = mphload('heat_transient_axi.mph');

Integrate the normal heat flux along the external boundaries using surface
integration:
Q = mphint(model,'ht.ndflux','intsurface','on','edim',1,...
'selection',[2,3,4]);

Integrate both normal heat flux and the temperature and set the unit to use ([MW]
and [m^2*degC] respectively):
[Int unit]=
mphint(model,{'ht.ndflux','T'},'intsurface','on','edim',1,...
'selection',[2,3,4],'unit',{'MW','m^2*degC'});

158

mphinterp
Evaluate expressions in arbitrary points or data sets.

Purpose

mphinterp

Syntax

[v1,v2,...,vn] = mphinterp(model,{e1,e2,...,en},'coord',coord,...)
[v1,v2,...,vn] =
mphinterp(model,{e1,e2,...,en},'dataset',dset,...)

Description

[v1,v2,...,vn] = mphinterp(model,{e1,e2,...,en},coord,coord,...)

evaluates expressions e1,e2,...en at the coordinates specified in the double matrix


coord. Evaluation is supported only on Solution Data Sets.
[v1,v2,...,vn] =
mphinterp(model,{e1,e2,...,en},'Dataset','datasetname',...)

evaluates expressions e1,e2,...en on the specified data set. In this case the data
set needs to be of a type that defines an interpolation in itself, such as cut planes,
revolve, and so forth.
[v1,v2,...,vn,unit] = mphinterp(model,{e1,e2,...,en},...) returns in

addition the unit of the expressions.


The columns of the matrix coord are the coordinates for the evaluation points. If
the number of rows in coord equals the space dimension, then coord are global
coordinates, and the property Edim determines the dimension in which the
expressions are evaluated. For instance, Edim=2 means that the expressions are
evaluated on boundaries in a 3D model. If Edim is less than the space dimension,
then the points in coord are projected onto the closest point on a domain of
dimension Edim. If, in addition, the property Selection is given, then the closest
point on domain number Selection in dimension Edim is used.
If the number of rows in coord is less than the space dimension, then these
coordinates are parameter values on a geometry face or edge. In that case, the
domain number for that face or edge must be specified with the property
Selection.
The expressions that are evaluated can be expressions involving variables, in
particular application mode variables.
The matrices v1,v2,...,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.

159 |

CHAPTER 9: COMMAND REFERENCE

mphinterp
The following property/value pairs are available:
TABLE 9-7: PROPERTY/VALUE PAIRS FOR THE MPHEVAL COMMAND.
PROPERTY

PROPERTY
VALUE

DEFAULT

DESCRIPTION

Complexfun

off | on

on

Use complex-valued functions


with real input

Complexout

off | on

off

Return complex values

Coord

Double
array

Dataset

String

Auto

Data set tag name

Edim

0 | 1 | 2 |
3

geometry
space
dimension

Element dimension

Matherr

off | on

off

Error for undefined operations


or expressions

Outersolnum

Positive
integer

Solution number for parametric


sweep

Phase

Scalar

Phase angle in degrees

Recover

off | ppr |
pprint

off

Accurate derivative recovery

Selection

Integer
vector |
all

all

Domain number

Solnum

Integer
vector |
all | end

all

Solutions for evaluation

Double
array

Time for evaluation

Unit

String |
Cell array

Unit to use for the evaluation

Coordinates for evaluation

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=sdim is used,
where sdim is the space dimension of the geometry. 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).

160

mphinterp
Use Recover to recover fields using polynomial-preserving recovery. This
techniques recover fields with derivatives such as stresses or fluxes with a higher
theoretical convergence than smoothing. Recovery is expensive so it is turned off by
default. The value pprint means that recovery is performed inside domains. The
value ppr means that recovery is also applied on all domain boundaries.
The property Refine constructs evaluation points by making a regular refinements
of each element. Each mesh edge is divided into Refine equal parts.
The property Smooth controls if the post data is forced to be continuous on element
edges. When Smooth is set to internal, only elements not on interior boundaries are
made continuous.
When the property Phase is used, the solution vector is multiplied with
exp(i*phase) before evaluating the expression.
The expressions e1,e2,...,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.
In case of multiple expression, if the unit property is defined with a string, the same
unit is used for both expressions. To use different units, set the property with a cell
array. In case of inconsistent unit definition, the default unit is used instead.
Solnum is used to select the solution number when a parametric, eigenvalue or
time-dependent solver has been used.
Outersolnum is used to select the outer solution number when a parametric sweep

has been used in the study step node.


Example

161 |

Load heat_convection_2d.mph from the Model Library:

CHAPTER 9: COMMAND REFERENCE

mphinterp
model = mphload('heat_convection_2d.mph');

Compute the temperature T at the center of the domain:


T = mphinterp(model,'T','coord',[0.3;0.5])

Load cylinder_flow.mph from the Model Library:


model = mphload('cylinder_flow.mph');

Evaluate the x-velocity u and the time at different location points:


[u,t]= mphinterp(model,{'u','t'},'coord',[1 1.5 2; 0.2 0.2 0.2]);

Evaluate the variation of the pressure at different times and get the unit:
[p,t, unit]= mphinterp(model,{'p','t'},'coord',[2; 0.2],...
't',[0:0.01:0.5 0.3:0.1:1]);

Evaluate the pressure and the time with the unit [mPa] and [min] respectively:
[p,t] = mphinterp(model,{'p','t'},'coord',[2; 0.2],...
't',1,'unit',{'mPa','min'});

Load transport_and_adsorption.mph from the Model Library:


model = mphload('transport_and_asorption.mph');

Evaluate the concentration along boundary 5 at t = 2 s:


list = [0:1e-3:0.1 0.2:0.1:0.9 0.9:1e-3:1];
[c,y] = mphinterp(model,{'c','y'},'coord',list,'edim',1,...
'selection',5,'t',2);

Load stresses_in_pulley.mph from the Model Library:


model = mphload('stresses_in_pulley.mph');

Evaluate the von Mises effective stress at the cut point data set cpt1:
[mises,n]= mphinterp(model,{'solid.mises','n'},...
'datset','cpt1');
See also

mpheval, mphglobal, mphint

162

mphload
Load a COMSOL model MPH-file.

Purpose

mphload

Syntax

model =
model =
model =
[model,

Description

model = mphload(File) loads a COMSOL model object and assigns the default

mphload(File)
mphload(File, ModelObjectName)
mphload(File, ModelObjectName, '-history')
filename] = mphload(File, ModelObjectName)

name Model in the COMSOL server.


model = mphload(File, ModelObjectName) loads a COMSOL model object

and assigns the name ModelObjectName in the COMSOL server.


model = mphload(File, ModelObjectName, '-history') turns on history

recording.
[model, filename] = mphload(File, ModelObjectName) also returns the full

file name filename of the file that was loaded.


If the model name is the same as a model that is currently in the COMSOL server
the loaded model overwrites the existing one.
Note that MATLAB searches for the model on the MATLAB path if an absolute
path is not supplied.
mphload turns off the model history recording by default, unless the property
'-history' is used.

The extension mph can be omitted.


Example

Load the model in the file transport_and_adsorption.mph from the Model


Library:
model = mphload('transport_and_asorption.mph');

Load the model from stresses_in_pulley.mph without specifying the mph


extension:
model = mphload('stresses_in_pulley');

Load the model from MyModel.mph with the path specified:


model = mphload('PATH\MyModel.mph');

Load the model in the file effective_diffusivity.mph from the Model Library
and return the file name:
[model, filename] = mphload('effective_diffusivity.mph');

163 |

CHAPTER 9: COMMAND REFERENCE

mphmatrix
Get model matrices.

Purpose

mphmatrix

Syntax

str = mphmatrix(model,solname,'Out',...)

Description

str = mphmatrix(model,solname,'Out',{'A'}) returns a MATLAB structure


str containing the matrix A assembled using the solver node solname and
accessible as str.A. A being taken from the Out property list.
str = mphmatrix(model,solname,fname,'Out',{'A','B',...}) returns a
MATLAB structure str containing the matrices A, B, ... assembled using the solver
node solname and accessible as str.A and str.B. A and B being taken from the
Out property list.

The following options are available


TABLE 9-8: PROPERTY/VALUE PAIRS FOR THE MPHMATRIX COMMAND
PROPERTY

EXPRESSION

DEFAULT

DESCRIPTION

out

Cell array of
strings

Initmethod

| init | sol

Use linearization point

Initsol

solname | zero

solname

Solution to use for


linearization

Solnum

Number | auto

auto

Solution number

List of matrices to assemble

The following values are valid for the out property:


PROPERTY/VALUE PAIRS FOR THE PROPERTY OUT.
PROPERTY

EXPRESSION

DESCRIPTION

out

Stiffness matrix

Load vector

Constraint vector

Constraint Jacobian

Damping matrix

Mass matrix

NF

Constraint force Jacobian

NP

Optimization constraint Jacobian (*)

MP

Optimization constraint vector (*)

MLB

Lower bound constraint vector (*)

MUB

Upper bound constraint vector (*)

Kc

Eliminated stiffness matrix

164

mphmatrix

PROPERTY/VALUE PAIRS FOR THE PROPERTY OUT.


PROPERTY

EXPRESSION

DESCRIPTION

Lc

Eliminated load vector

Dc

Eliminated damping matrix

Ec

Eliminated mass matrix

Null

Constraint null-space basis

Nullf

Constraint force null-space matrix

ud

Particular solution ud

uscale

Scale vector

(*) Requires the Optimization Module.


Note that the assembly of the eliminated matrices uses the current solution vector
as scaling method. To get the unscaled eliminated system matrices, it is required to
set the scaling method to 'none' in the variables step of the solver configuration
node.
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.
Example

Load heat_convection_2d.mph from the Model Library:


model = mphload('heat_convection_2d.mph');

Deactivate the stationary solver node


model.sol('sol1').feature('s1').active(false);

Extract the stiffness matrix and the load vector:


str = mphmatrix(model,'sol1','out',{'K','L'});

Plot the sparsity of the matrix:


spy(str.K)

Extract the eliminated system:


model.sol('sol1').feature('v1').set('scalemethod','none');
str = mphmatrix(model,'sol1','out',{'Kc','Lc'});

Compare the sparsity of both system matrices (non-eliminated (b) and eliminated
one (r)):
hold on

165 |

CHAPTER 9: COMMAND REFERENCE

mphmatrix
spy(str.Kc,'r')

Load heat_radiation_1d.mph from the model library:


model = mphload('heat_radiation_1d.mph');

Extract the eliminated residual:


str = mphmatrix(model,'sol1','out',{'Lc'});

Load heat_convection_2d.mph from the model library:


model = mphload('heat_convection_2d.mph');

Extract the stiffness matrix and the load vector evaluated for the initial solution:
str = mphmatrix(model,'sol1','out',{'Kc' 'Lc'},...
'initmethod','init');

166

mphmesh
Plot a mesh in a MATLAB figure window.

Purpose

mphmesh

Syntax

mphmesh(model,meshname)
mphmesh(model,meshname,...)

Description

mphmesh(model,meshname) plots the mesh meshname in a MATLAB figure

window.
mphmesh(model,meshname,...) plots the mesh meshname in a MATLAB figure
window with the specified properties.

Valid properties include


TABLE 9-9: PROPERTY/VALUE PAIRS FOR THE MPHMESH COMMAND

Example

PROPERTY

VALUE

DEFAULT

DESCRIPTION

Parent

Double

Edgecolor

Char

Edge color

Edgelabels

on | off

off

Show edge labels

Edgelabelscolor

Char

Color for edge labels

Edgemode

on | off

on

Show edges

Facealpha

Double

Use transparency

Facelabels

on | off

off

Show face labels

Facelabelscolor

Char

Color for face labels

Facemode

on | off

on

Show faces

Meshcolor

Char

flat

Color for face element

Vertexlabels

on | off

off

Show vertex labels

Vertexlabelscolor

Char

Color for vertex labels

Vertexmode

on | off

off

Show vertices

Parent axis

Load the example model shell_diffusion.mph from the Model Library:


model=mphload('shell_diffusion.mph');

Plot the geometry geom1:


mphmesh(model,'mesh1')

Plot the mesh with a colored element and transparency set to 0.5:
mphmesh(model, 'mesh1', ...
'edgecolor', 'b', ...
'facealpha',0.5,...
'meshcolor','r');

167 |

CHAPTER 9: COMMAND REFERENCE

mphmeshstats
Return mesh statistics and mesh information

Purpose

mphmeshstats

Syntax

stats = mphmeshstats(model, meshname)


[stats,data] = mphmeshstats(model, meshname)

Description

stats = mphmeshstats(model, meshname) returns mesh statistics as a structure.

The fields in the structure are listed below.


[stats,data] = mphmeshstats(model, meshname) returns mesh statistics and

mesh information such as vertex coordinates and definitions of elements.


meshname can be omitted if there is only one mesh in the model.
stats has the following fields:
TABLE 9-10: FIELDS IN THE STATS STRUCTURE
FIELD

DESCRIPTION

isactive

Is the mesh node active

hasproblems

Does the mesh have problems?

iscomplete

Is the mesh built to completion?

sdim

Space dimension

types

Cell array with type names

numelem

Vector with the number of elements for each type

minquality

Minimum quality

meanquality

Mean quality

qualitydistr

Quality distribution (vector)

minvolume

Volume/area of the smallest element

maxvolume

Volume/area of the largest element

volume

Volume/area of the mesh

data has the following fields:


TABLE 9-11: FIELDS IN THE DATA STRUCTURE

Example

FIELD

DESCRIPTOIN

vertex

Coordinates of mesh vertices

elem

Cell array of definition of each element type

elementity

Entity information for each element type

Load the busbar model and show the mesh distribution in a figure:
model = mphload('busbar');
stats = mphmeshstats(model);

168

mphmeshstats
bar(linspace(0,1,20), stats.qualitydistr)

Show the element vertices in a plot


[stats,data] = mphmeshstats(model, 'mesh1');
plot3(data.vertex(1,:), data.vertex(2,:), ...
data.vertex(3,:), '.')
axis equal
view(3)

Find the number of edge elements


stats.types

Note that the edge type is the first type in the list
numedgeelem = stats.numelem(1)
See also

169 |

mphmesh

CHAPTER 9: COMMAND REFERENCE

mphmodel
Return tags for the nodes and subnodes in the COMSOL model object

Purpose

mphmodel

Syntax

mphmodel(model)

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 mphmodel function 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 transport and adsorption model from the model library:
model = mphload('transport_and_adsorption')

See what nodes are available under the model object:


mphmodel(model)

See what nodes are available under the geometry node:


mphmodel(model.geom)

Get the model information as a structure:


res = mphmodel(model, '-struct')
See also

mphnavigator

170

mphnavigator
Graphical User Interface for viewing the COMSOL model object

Purpose

mphnavigator

Syntax

mphnavigator

Description

The mphnavigator command open 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 objest is stored in a variable in the base
workspace (at the MATLAB command prompt) with the name model. No other
variable name is supported at this time.

See also

171 |

mphmodel, mphgetproperties

CHAPTER 9: COMMAND REFERENCE

mphplot

Purpose

mphplot
Render a plot group in a figure window.

Syntax

mphplot(model,pg)
mphplot(model,pg,'server',on)
mphplot(model,pg,'rangenum',num)

Description

mphplot(model,pg) renders the plot group tagged pg from the model object
model in a figure window in MATLAB.
mphplot(model,pg,'server','on') renders the plot group tagged pg from
model in a figure window using the COMSOL server.
mphplot(model,pg,'rangenum',num) renders the plot group tagged pg from
model in a figure window in MATLAB with the color range bar (or legend bar) that

corresponds to the feature number num in the list of the plot group.
Note that only one color range bar and one legend bar is supported in a MATLAB
figure. When the option plot on server is active, all color range bars are displayed.
The following options are available:
TABLE 9-12: PROPERTY/VALUE PAIRS FOR THE MPHPLOT COMMAND
PROPERTY

VALUE

DEFAULT

DESCRIPTION

Rangenum

Positive
Integer

none

Color range bar (or legend) to


display

Server

on | off

off

Plot on server

Parent

Double

Set the parent figure

Note: The plot on server option requires that you start COMSOL with MATLAB
in graphics mode.

Example

Load feeder_clamp.mph from the Model Library:


model = mphload('feeder_clamp.mph');

Plot the first plot group


mphplot(model,'pg1')

Plot the first plot group with the color range bar:
mphplot(model,'pg1','rangenum',1)

172

mphplot
Load rock_fracture_flow.mph from the Model Library:
model = mphload('rock_fracture_flow.mph');

Plot the second plot group with the color range bar:
mphplot(model,'pg2','rangenum',1)

Load fluid_valve.mph and plot on server (requires that you start COMSOL with
MATLAB in graphics mode):
model = mphload('fluid_valve.mph');

Plot the first plot group on server:


mphplot(model,'pg1','server','on')

Plot the second plot group on server:


mphplot(model,'pg2','server','on')

173 |

CHAPTER 9: COMMAND REFERENCE

mphsave
Save a COMSOL model

Purpose

mphsave

Syntax

mphsave(model)
mphsave(model, filename)

Description

mphsave(model) saves the saves the COMSOL model object model.


mphsave(model, filename) saves the COMSOL model object model and to the

file named filename.


If the filename is provided, the model has to be saved previously on disk.
If the filename does not provide a path the file is saved relatively to the current path
in MATLAB.
The model can be saved as an mph-file, java-file or as an m-file. The file extension
determines which format that is saved.
See also

mphload

174

mphselectbox
Select geometric entity using a rubberband/box.

Purpose

mphselectbox

Syntax

n = mphselectbox(model,geomname,boxcoord,entity,...)

Description

n = mphselectbox(model,geomname,boxcoord,entity,...) returns the

indices of the geometry entities that are inside a selection domain (rectangle or box).
This method looks only on the vertex coordinates and does not observe all points
on curves and surfaces.
boxcoord set the coordinates of the selection domain, specified as a Nx2 array,

where N is the geometry space dimension.


entity can be one of 'point', 'edge', 'boundary' or 'domain' following the

entity space dimension defined below:

'domain': maximum geometry space dimension

'boundary': maximum geometry space dimension -1

'edges': 1(only for 3D geometry)

The following options are available:


TABLE 9-13: PROPERTY/VALUE PAIRS FOR THE MPHSELECTBOX COMMAND
PROPERTY

VALUE

DEFAULT

DESCRIPTION

Adjnumber

Scalar

none

Adjacent entity number

When a model uses form an assembly more than one vertex may 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

Load busbar.mp from the Model Library:


model = mphload('busbar.mph')

Find domains that are inside the selection box defined by


[0,0.05;0,-0.05;-0.05,0.05]:
n = mphselectbox(model,'geom1',...
[0 0.05;0 -0.05;-0.05 0.05],'domain');

Find boundaries inside the selection box that are adjacent to domain number 1:
n = mphselectbox(model,'geom1',...
[0,0.05;0,-0.05;-0.05,0.05],'boundary','adjnumber',1);

175 |

CHAPTER 9: COMMAND REFERENCE

mphselectbox
Load effective_diffusivity.mph from the Model Library:
model = mphload('effective_diffusivity.mph');

Find the boundaries that are inside the selection rectangle defined by
[3e-4,4e-4;4.5e-4,5.5e-4]:
n = mphselectbox(model,'geom1',...
[3e-4,4e-4;4.5e-4,5.5e-4],'boundary');

Find the boundaries that are inside the same selection rectangle:
n = mphselectbox(model,'geom1',...
[3e-4,4e-4;4.5e-4,5.5e-4],'point');
See also

mphgetadj, mphgetcoords, mphselectcoords

176

mphselectcoords
Select geometric entity using point coordinates

Purpose

mphselectcoords

Syntax

n = mphselectcoords(model,geomname,coord,entity,...)

Description

n = mphselectcoords(model,geomname,coord,entity,...) finds geometry

entity numbers based on their vertex coordinates.


One or more coordinate may 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.
Coord is a NxM array where N correspond of the number of point to use and M the

space dimension of the geometry.


Entity can be one of 'point', 'edge', 'boundary' or 'domain' following the

entity space dimension defined below:

'domain': maximum geometry space dimension

'boundary': maximum geometry space dimension -1

'edges': 1(only for 3D geometry)

The following options are available:


TABLE 9-14: PROPERTY/VALUE PAIRS FOR THE MPHSELECTCOORDS COMMAND
PROPERTY

VALUE

DEFAULT

DESCRIPTION

Adjnumber

Scalar

none

Adjacent entity number

Radius

Scalar

auto

Search radius

Include

All | any

all

Include all or any vertices

When a model uses form an assembly more than one vertex may 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.
If the include property is 'all' then all vertices must belong to the entity in to be
considered a match. If the Include property is 'any' then an entity is considered
a match as long as any of the vertices are adjacent to the entity.
Examplee

177 |

Load busbar.mph from the Model Library:

CHAPTER 9: COMMAND REFERENCE

mphselectcoords
model = mphload('busbar.mph');

Select the vertex near [0.095,0,0.1]:


n = mphselectcoords(model,'geom1',... [0.095,0,0.1],'point');

Select the edge from [0.095,0,0.1] to [0.095,0,0.01]:


n = mphselectcoords(model, 'geom1',...
[0.095,0,0.1;0.095,0,0.01]','edge');
Select edges that are adjacent to the points [0.095,0,0.1] and [0.095,0,0.01]:
n = mphselectcoords(model, 'geom1',...
[0.095,0,0.1;0.095,0,0.01]','edge',... 'include', 'any');

Select boundaries that are adjacent to the points [0.09,0,0.1] and [0.09,0,0.015]
with a search radius of 0.01:
n = mphselectcoords(model,'geom1',...
[0.09,0,0.1;0.09,0,0]','boundary',... 'radius',0.01);
See also

mphgetadj, mphgetcoords, mphselectbox

178

mphstart
Connect MATLAB to a COMSOL server.

Purpose

mphstart

Syntax

mphstart
mphstart(port)
mphstart(ipaddress, port)
mphstart(ipaddress, port, comsolpath)

Description

mphstart creates a connection with a COMSOL server using the default port

number (which is 2036).


mphstart(port) creates a connection with a COMSOL server using the specified
port number port.
mphstart(ipaddress, port) creates a connection with a COMSOL server using

the specified ipaddress and port number


mphstart(ipaddress, port, comsolpath) creates a connection with a
COMSOL server using the specified ipaddress and port number using the
comsolpath that is specified. This is useful if mphstart can not find the location of
the COMSOL Multiphysics installation.
mphstart can be used to create a connection from within MATLAB when this is

started without using the COMSOL with MATLAB option. mphstart then sets up
the necessary environment and connect to COMSOL.
Prior to calling mphstart it is necessary to set the path of mphstart.m in the
MATLAB path or to change the current directory in MATLAB (e.g. using the cd
command) to the location of the mphstart.m file.
A COMSOL server must be started prior to running mphstart.

179 |

CHAPTER 9: COMMAND REFERENCE

mphstate
Get state-space matrices for dynamic system.

Purpose

mphstate

Syntax

str = mphstate(model,solname,'Out',{'SP'})
str = mphstate(model,solname,'Out',{'SP1','SP2',...})

Description

str = mphstate(model,solname,'out',{'SP'}) returns a MATLAB structure


str containing the state space matrix SP assembled using the solver node solname
and accessible as str.SP. SP being taken from the Out property list.
str = mphstate(model,solname,'Out',{'SP1','SP2',...}) returns a
MATLAB structure str containing the state space matrices SP1, SP2, ... assembled
using the solver node solname and accessible as str.SP1and str.SP2. SP1 and SP2
being taken from the Out property list.
mphstate accepts the following property/value pairs:
TABLE 9-15: PROPERTY VALUE FOR THE MPHSTATE COMMAND
PROPERTY

VALUE

Out

Mc | MA | MB| C
| D | Null | ud
| x0

DEFAULT

DESCRIPTION

Keepfeature

off | on

Input

String

Output

String

Sparse

off | on

Initmethod

init | sol

Initsol

solname | zero

solname

Solution to use for


linearization

Solnmum

auto

auto

Solution number

Output variables

off

Keep the state-space feature in


the model
Input variables
Output variables

off

Sparse matrices
Use linearization point

The property Sparse controls whether the matrices A, B, C, D, M, MA, MB, and Null
are stored in the sparse format. See femsim for a description of the other properties.
The equations correspond to the system below:
Mcx = McAx + McBu

y = Cx + Du

where x are the state variables, u are the input variables, and y are the output
variables.

180

mphstate
A static linearized model of the system can be described by:

y = D C McA 1 McB u

The full solution vector U can be then obtained from:


U = Nullx + ud + u0
where Null is the null space matrix, ud the constraint contribution and u0 is the
linearization point, which is the solution stored in the sequence once the state space
export feature is run.
The matrices Mc and MA are produced by the same algorithms that do the
finite-element assembly and constraint elimination in COMSOL Multiphysics. Mc
and MA are the same as the matrices Dc (eliminated mass matrix) and Kc (Kc is the
eliminated stiffness matrix). The matrices are produced from an exact residual vector
Jacobian calculation (that is, differentiation of the residual vector with respect to the
degrees of freedoms x) plus an algebraic elimination of the constraints. The matrix
C is produced in a similar way; that is, the exact output vector Jacobian matrix plus
constraint elimination.
The matrices MB and D are produced by a numerical differentiation of the residual
and output vectors, respectively, with respect to the input parameters (the algorithm
systematically perturbs the input parameters by multiplying them by a factor
(1+10-8)).
Example

Load the heat_convection_2d.mph model:


model = mphload('heat_convection_2d.mph');

Set the temperature condition with a constant parameter:


model.param.set('T0','373');
model.physics('ht').feature('temp1').set('T0', 1, 'T0');

Add a point probe at (0.3; 0.8):


pdom1 = model.probe.create('pdom1', 'DomainPoint');
pdom1.model('mod1');
pdom1.setIndex('coords2','0.8',0,0);
pdom1.setIndex('coords2','0.3',0,0);

Extract the state-space matrix:

181 |

CHAPTER 9: COMMAND REFERENCE

mphstate
str = mphstate(model,'sol1','out',...
{'MA','MB','C','D'},'input','T0',... 'output','mod1.ppb1');

182

mphversion
Return the version number of COMSOL Multiphysics

Purpose

mphversion

Syntax

v = mphversion
[v,vm] = mphversion(model)

Description

v = mphversion returns the COMSOL Multiphysics version number that


MATLAB is connected to as a string.
[v,vm] = mphversion(model) returns the COMSOL Multiphysics version
number that MATLAB is connected to as a string in the variable v and the version
number of the model in the variable vm.

See also

183 |

mphload, mphsave

CHAPTER 9: COMMAND REFERENCE

mphviewselection
Display a geometric entity selection in a MATLAB figure.

Purpose

mphviewselection

Syntax

mphviewselection(model,geomname,number,'entity',entity,...)
mphviewselection(model,selection,...)

Description

mphviewselection(model,geomname,number,'entity',entity,...) displays

the geometric entity number of type entity in MATLAB figure including the
representation of the geometry geom.
mphviewselection(model,selection,...) displays the geometric entity
selection selection in a MATLAB figure including the representation of the
geometry.

Valid properties include:


TABLE 9-16: PROPERTY VALUE/PAIRS FOR THE MPHVIEWSELECTION FUNCTION
PROPERTY

VALUE

Parent

Double

Edgecolor

Char | RGB array

Color for edges

Edgelabels

on | off

off

Show edge labels

Edgelabelscolor

Char | RGB array

Color for edge labels

Edgemode

on | off

on

Show edges

Facealpha

Double

Set transparency value

Facelabels

on | off

off

Show face labels

Facelabelscolor

Char | RGB array

Color for face labels

Facemode

on | off

on

Show faces

Facecolor

RGB array

[0.6,0.6,0.6]

Color for face

Vertexlabels

on | off

off

Show vertex labels

Vertexlabelscolor

Char | RGB array

Color for vertex


labels

Vertexmode

on | off

off

Show vertices

Vertex marker

Marker

DEFAULT

DESCRIPTION

Parent axis

Markercolor

Char | RGB array

Color for vertex


marker

Markersize

Int

12

Font size of marker

Geommode

on | off

on

Show entire geometry

Facecolorselected

RGB array

[1,0,0]

Color for selected


face

184

mphviewselection

TABLE 9-16: PROPERTY VALUE/PAIRS FOR THE MPHVIEWSELECTION FUNCTION

Example

PROPERTY

VALUE

DEFAULT

DESCRIPTION

Edgecolorselected

RGB array

[1,0,0]

Color for selected


edges

Markercolorselected

Char | RGB array

Color for selected


vertex marker

Showselector

on | off

on

Show Selector

Selectorcolor

RGB array

[0,0,1]

Color for selected


marker

Selectoralpha

Double

0.25

Set selector
transparency value

Entity

Domain |
boundary | edge |
point

Set the selected entity


type

Selection

Char | Int

Set selection name or


entity number

Load busbar.mph from the Model Library:


model = mphload('busbar')

Plot boundary number 3 using a yellow color


mphviewselection(model, 'geom1',3, 'entity','boundary', ...
'facecolorselected', [1 1 0], 'facealpha', 0.5)

Plot edge 1 to 9
hold on
mphviewselection(model, 'geom1',1:8,'geommode','off',...
'entity','edge', 'edgecolorselected', [0 1 0.5])

Load busbar.mph from the Model Library


model = mphload('busbar')

Plot the titanium blot domains in green color


mphviewselection(model, 'sel1', 'facecolorselected', [0 1 0])

185 |

CHAPTER 9: COMMAND REFERENCE

mphv4
Convert a FEM structure or FEMGUI object to a model object.

Purpose

mphv4

Syntax

model = mphv4(obj)

Description

model = mphv4(obj) converts obj (FEM structure or FEMGUI object) to the

model object model.


If obj is defined as FEMGUI object, model contains the sequences that correspond
to the generation of the FEM structure.
If obj is defined as a FEM structure, model only contains imported data.

Note: The mphv4 function requires that you run COMSOL with MATLAB in
compatibility mode.

Example

Set the variable fem as a FEMGUI object:


fem = femgui;

Set-up and solve the model:


fem.geom = circ2;
fem.mesh = meshinit(fem);
fem.shape=2; fem.equ.c = 1; fem.equ.f = 1; fem.bnd.h = 1;
fem.xmesh = meshextend(fem);
fem.sol = femlin(fem);
postplot(fem,'tridata','u')

Convert the above sequence to a model object model:


model = mphv4(fem);

186

mphxmeshinfo
Extract information about the Xmesh

Purpose

mphxmeshinfo

Syntax

info = mphxmeshinfo(model, 'solname, solname)


info = mphxmeshinfo(model, 'solname, solname, 'Studysteptag,
sttag)

Description

info = mphxmeshinfo(model, 'solname, solname)extracts xmesh

information from the solution with the name solname.


infor = mphxmeshinfo(model, 'solname, solname, 'Studysteptag,
sttag) extracts xmesh information from the Study Step with the tag sttag.

Information is only available on StudyStep and Variables features


The function returns a structure with the fields shown in the table below
TABLE 9-17: FIELD IN THE RETURNED STRUCTURE FROM MPHXMESHINFO

Example

FIELD

DESCRIPTION

ndofs

Number of DOFs

fieldnames

Fieldnames in the model

fieldndofs

Number of DOFs per field name

meshtypes

Mesh types used in the Xmesh

dofs

Struct with information about the degrees of freedom

nodes

Struct with information about the nodes

elements

Struct with information about each element type

Load busbar.mph from the Model Library:


model = mphload('busbar.mph')

Extract xmesh information for the Solver feature:


info = mphxmeshinfo(model,'solname', 'sol1')

Extract xmesh information from the Study Step node st1


info = mphxmeshinfo(model,'solname', 'sol1', 'studysteptag',
'st1')

187 |

CHAPTER 9: COMMAND REFERENCE

I n d e x
A

access methods 172


adaptive solver 164
advancing front method 67
animations 114
ASCII file 115

Boolean operations 43, 47


boundary layer meshes 75

CAD formats 49
circle 43
Compose operation 44
COMSOL 3.5a, converting from 119
COMSOL Desktop 23
exchanging geometries with 48
COMSOL Java API 23
COMSOL Multiphysics binary files 81
COMSOL Multiphysics text files 81
constraint Jacobian matrix 90
constraint residual vector 89
constraints 89
constructor name 57
contacting COMSOL 8
converting meshes 80
copying boundary meshes 78

damping matrix 89
data filtering 106
data sets 104, 110
syntax for 109
Delaunay method 67
Difference operation 44
documentation 30
documentation, location 7
DXF files 49

emailing COMSOL 8
equations
global 60

188

modifying 59
evaluating data 111
exporting data for file 114
extruding, meshes by sweeping 73
F

FEMGUI object 120


file formats
.mphbin files 49
.mphtxt files 49
Fillet operation 45
filter data 106
for loops, in M-files 126
free quad mesh 68
function inputs/outputs 33

GDS format 49
geometries
1D 42
2D 43
3D 47
exchanging with the COMSOL Desktop 48
parameterized 51
geometry sequences 41
getType() methods 172

global variables 113


I

importing meshes 81
integrating expressions 113
Internet resources 7
interpolating data 113

Java 23

knowledge base, COMSOL 8

Lagrange multiplier vector 89


linearization point 93

mass matrix 89
materials 58
MATLAB functions, using in COMSOL 30
MATLAB help browser 30
mesh

189 |

CHAPTER :

advancing front 67
converting 80
copying 78
creating a quad mesh 68
creating boundary layers 75
Delaunay 67
getting information about 82
importing 81
refining 78
setting data for 83
mesh quality measures 77
mesh resolution 64
meshing sequences 63
M-files
from COMSOL 3.5a 119
Model Builder 23
Model Library, accessing in COMSOL 7
model object 23
modifying equations 59
MPH-files 7
N

NASTRAN files 81
NASTRAN mesh 81
native file formats 49
node point coordinates 111
null-space matrix 93

opening the Model Library 7

parameterized geometries 51
physics interfaces 57
plot groups
syntax for 103
using 104
plot types 107

quality of mesh elements 77

rectangle 43
refining meshes 78
reports 114
residual vector 89

190

results analysis 103


results evaluation 111
S

sequences of operations 23
set operations 44
simplex elements 78
solution vector 89
solver configuration, syntax for 88
sparsity, of matrix 165
state vector 93
state-space matrices
evaluating from models 94
state-space models 93
stiffness matrix 89
structured meshes 69
study, syntax for 87
summary of commands 139
sweeping, to revolve meshes 72
syntax
for materials 58
for physics interfaces 57
system matrices 89
as MATLAB data 90

technical support, COMSOL 8


transfer matrix 93
trimming solids 45
typographical conventions 9

user community, COMSOL 8


utility functions 29

visualization 103

W web sites, COMSOL 8

weights, of control polygon 47

191 |

CHAPTER :

www.comsol.com

Das könnte Ihnen auch gefallen