Sei sulla pagina 1di 76

LiveLink for MATLAB

Version 4.3b
LiveLink is a trademark of COMSOL AB.
MATLAB is a registered trademark of The MathWorks Inc.
LiveLink for MATLAB


This presentation provides an overview of LiveLink for MATLAB

.

LiveLink for MATLAB

allows you to integrate COMSOL Multiphysics
with MATLAB

You can
Extend your modeling with scripting.
Perform data evaluation and postprocessing in MATLAB workspace.
Access low level model information.
Build your own applications that incorporate your COMSOL Multiphysics


models.
Define model settings with MATLAB functions.


COMSOL Multiphysics

4.3b Release Highlights



LiveLink for MATLAB

works with all


other modules and LiveLink products
Functionality
Interface between MATLAB and COMSOL Multiphysics
Use MATLAB as scripting interface to set up and solve your COMSOL
Multiphysics models.
Call MATLAB functions when modeling within the COMSOL Desktop

.

Supported versions:
MATLAB 2013a.
MATLAB 2012b.
COMSOL supports the latest two releases of MATLAB at the time when we
release a new version of COMSOL. COMSOL 4.3b may also works with
MATLAB 2012a and earlier versions. However, COMSOL does not offer
technical support for these versions of MATLAB.

Applications
Preprocess data, such as images and experiments, to include in your
models.

Extract data from your models for customized postprocessing and
visualization.

Manipulate your models from the command line or script to parameterize
the geometry, physics, or the solution scheme.

Interface computations performed in other simulators.

Use MATLABs GUI building tools to create custom-made graphical user
interfaces for your models for deployment to users in your organization.

Define model settings using MATLAB functions.
Run Model in Loop
Simulate a periodic
homogenization process in
space dependent chemical
reactor model.
Homogenization take place
every 30 minutes and
assumed to be ideal.
Run several loop of the time-
dependent problem.
Set initial condition with the
averag concentration of the
last time computed in the
previous iteration.
Concentration at the center of the bulk, with
homogenization step (blue) and without (red)

Import/Export data from/to the MATLAB
workspace
The real geometry consists
in a very long pipe within
which the heat is transported
by convection.
Compute in loop the solution
for a reduced section of the
channel.
The solution at the outlet of
the ith section is mapped to
the inlet for the (i+1)th
section.

Define model settings using MATLAB functions
Temperature Distribution in a
Vacuum Flask.
Compute the temperature
distribution in a vacuum flask.
Use of external MATLAB
function to define:
Shell and insulation foam
thermal conductivity.
heat transfer coefficient for
natural convection along
vertical wall.

User Defined GUI
Use the MATLAB GUIDE
functionality to create a user
defined graphical user
interface (GUI).
Such a GUI can be used to give
quick access to powerful
COMSOL functionality to your
colleagues, clients and
customers.

Product Contents
The COMSOL API
The COMSOL Application Programming Interface (API) enables modeling
at the MATLAB command line.
Wrapper Functions
A set of wrapper functions package API functionality for ease of use.
COMSOL Desktop Interface
Interface to enable the use of external MATLAB functions when modeling
in the COMSOL Desktop environment.
Documentation and Tutorials
How to get started in practice?
Save your model from COMSOL Desktop as M-file: File > Save as
Model M-file to get the commands which make up your model.
Type mphmodellibrary at the MATLAB command line for access of
LiveLink for MATLAB

model library.
Type mphdoc at the MATLAB command line for online access of the
COMSOL API for use with Java

Reference Manual.
The COMSOL API for use with Java

Reference Manual provides a
complete list of available methods.
Documentation and Tutorials
The main documentation for
the LiveLink for MATLAB

is
represented by the books
Introduction to LiveLink for
MATLAB

.
LiveLink for MATLAB

Users
Guide.
COMSOL API for use with Java


Reference manual.



Workflows
Load an existing mph-file using the mphload command.
The model file contains the model settings, mesh and solution.
Change model settings and add details to it before you re-solve, or save
using the mphsave command.
Work with a model m-file saved from the COMSOL Desktop.
When run in MATLAB, the m-file sets up the new model and solves it.
Very useful for learning the syntax of the COMSOL API.
Write a model m-file from scratch.
Requires knowledge of the COMSOL API.
Gives the greatest flexibility.
Useful when you wish to build complex, parameterized geometries from
scratch.

Under the Hood COMSOL with MATLAB
MATLAB is connected to a COMSOL server using a client/server mode
No COMSOL Desktop is involved
Commands that are executed in MATLAB set up and modify the Model
Object, which exists on the COMSOL server


COMSOL Server
COMSOL Client
Interface Functions
mphcd: Change directory to the directory of the model.
mphdoc: Access HTML documentation.
mphload: Load a COMSOL model MPH-file.
mphsave: Save a COMSOL model.
mphstart: Connect MATLAB to a COMSOL server.
mphversion: Get the version number of COMSOL.

Geometry Functions
mphgeom: Plot a geometry in a MATLAB figure.
mphimage2geom: Convert image to geometry.
mphviewselection: Display a geometric entity selection
Mesh Functions
mphmesh: Plot mesh in a MATLAB figure.
mphmeshstats: List mesh information and mesh statistics.

Utility Functions (1)
mphgetadj: Return geometric entities that are adjacent to other.
mphgetcoords: Return point coordinates of geometry entities.
mphgetu: Return solution vector.
mphinputmatrix: Add linear matrix system to a model.
mphmatrix: Get model system matrices.
mphselectbox: Select geometric entity using a rubberband/box.
Utility Functions (2)
mphselectcoords: Select geometric entity using point coordinates.
mphsolinfo: Obtain information about a solution.
mphsolutioninfo: Obtain information about solution objects and
datasets containing given parameters.
mphstate: Get state-space matrices for dynamic system.
mphxmeshinfo: Extract information about the extended mesh.
New in 4.3b
Postprocessing Functions (1)
mpheval: Evaluate expressions on node points.
mphevalglobalmatrix: Evaluate global matrix variables.
mphevalpoint: Evaluate expressions at geometry vertices.
mphglobal: Evaluate global quantities.
mphint2: Perform integration of expressions.
mphinterp: Evaluate expressions in arbitrary points.
Postprocessing Functions (2)
mphmax: Perform maximum of expressions.
mphmean: Perform mean of expressions.
mphmin: Perform minimum of expressions.
mphparticle: Evaluate expressions on particle trajectories.
mphplot: Render a plot group in a figure window.
mphtable: Get table data.
New in 4.3b
New in 4.3b
Model Information Functions (1)
mphgetproperties: Get properties from a model node.
mphgetexpressions: Get the model variables and parameters.
mphgetselection: Get information about a selection node.
mphmodel: Return tags for the nodes and subnodes in the model
object.
Model Information Functions (2)
mphmodellibrary: GUI for viewing the Model Library.
mphnavigator: GUI for viewing the model object.
mphsearch: GUI for searching expressions in the model object.
mphshowerrors: Show messages in error and warning nodes in the
model object.
Compatibility Function: Versions 3.5a > 4.3b
A version 3.5a model can simply be saved as an MPH-file and
loaded into either the COMSOL 4.3b Desktop or MATLAB. From
there you can save an MPH-file that uses the new format. It is also
possible to save the model as an M-file that can be run in MATLAB
(this would typically require a bit of editing to make it work nicely
and efficiently).

Using MATLAB Functions in the COMSOL
Desktop
Under the Hood
An external function defined in the COMSOL Desktop is evaluated
in MATLAB. The result is sent back to COMSOL.
A MATLAB session is started automatically when needed.




COMSOL Desktop MATLAB
The MATLAB function node
Plot button
Clear function button to expunge the function from MATLAB cache
Function name and arguments definition
Define here the plot parameter limits to display the function in a
figure. Enter each argument plot limit from top to bottom
You can define here the function derivatives with respect to any
arguments. By default the derivatives are assumed to be null.
COMSOL use the chain rule to compute the derivative with respect
to any expression
Demos
Demo 1: Working with a Model M-file
Demo 2: Writing a Model M-File from Scratch
Demo 3: Loading a Model from an MPH-File
Demo 4: MATLAB Function Callback in the COMSOL Desktop





DEMO 1: Working with a Model M-file
Save a model as an m-file from the COMSOL Desktop

Examine the m-file. Learn about the
API syntax
Structure of a model object

Run the file
Opening a Model Library Model
Open the file busbar from the
Model library:
COMSOL Multiphysics >
Multiphysics > busbar
Resetting the Model History
Reset History Removes commands that are not in the current
configuration of a model.
Do this first to save a clean m-file.

From the File menu, select Reset
History
Saving the Model as an M-File
From the File menu, select Save As Model
M-File
The Model M-File (1)
The m-file is defined as a
MATLAB function which
returns the Model Object
Create a Model Object
Set model parameters
The Model M-File (2)
Create a new 3D geometry
Add Workplane and Extrude
feature nodes
Create geometry object in
the geometry
The Model M-File (3)
Create an explicit selection
named Ti bolts for domains
2-7
Define material properties
Add a J oule heating physics
interface and set heat flux,
electric potential, and ground
boundary conditions
Create free tetrahedral mesh
on the geometry geom1
The Model M-File (4)
Create a stationary study
Create a solver node and
define the solver settings
used for the computation
Create result plots
Compute the solution
Click the COMSOL 4.3b with MATLAB icon

Note: The COMSOL Desktop is not automatically started at
this time
Starting COMSOL with MATLAB
Starting COMSOL with MATLAB
A startup message is shown in the MATLAB
Command window.

You can create a comsolstartup.m file in
order to execute statements that should
always be executed when starting COMSOL
with MATLAB, such as adding directories to
the PATH. Save the file comsolstartup.m in
the user home directory.

Run the File
The output of the function is a model
object accessible from the server with the
specified link model
Call the M-function
M-File Structure Compared to the Model Builder
Workplane containing
geometry features
Extrude feature node
Material properties
J oule heating physics interface
and boundary condition
Free tetrahedral mesh
Solver node containing solver
settings
Result node with plot groups
Stationary study
Model parameters
ALWAYS
Improving Performance for Large Models
Do not run the entire script in a loop.
Load a model, and run only the command to change the desired settings

Disable the model history.
model.hist.disable
Note: done automatically when loading a model using mphload

Disable model feature update.
model.disableUpdate(true)
Note: need to enable it again before computing the solution


ALWAYS
RARELY
DEMO 2: Writing a Model M-File from Scratch
Learn to use the COMSOL API to set up a COMSOL Model Object

You rarely have to set up a model like this, but it is useful when setting up
a model where the number of geometric objects, number of physics etc.
are varying.
Creating the Model Object and Geometry Node
Create a Model Object
Create a 3D geometry
Adding Geometry Features
Create a block
Create a second block
Each node in the model builder,
such as geometry object, physics
interface, mesh, etc requires a
unique tag (here blk1 and blk2)
Using For-Loops to Create Several Geometry
Objects
Start the loop
Create a unique tag to define
the geometry object
Create a block geometry
object using the tag defined
previously
Set the block properties
The link in the MATLAB workspace
(here blk) can be overwritten
Displaying the Geometry
Finding Domain Indices
Define the selection box
extreme coordinates
mphselectbox returns
entity indices located
inside a box selection
Display the selection in a
MATLAB figure
Setting-up the Physics
Set user defined material
properties
Temperature boundary condition
on boundary 1, T0 =30 [degC]
Add a heat transfer
physics interface
Add heat source to the domains
with indices idx.
You can use directly MATLAB variables to
define model settings. To specify the unit with
a MATLAB variable, use string format.
Creating a Mesh
Display the mesh
Generate a mesh
with default settings
Defining Solver Settings
A solver configuration associated to
a solution object is automatically
built, as in the COMSOL Desktop.
Create a stationary study
Run the study
Plotting the Results
Create a 3D plot group
Display the plot group
Set the solution data set
Add a surface plot to the
group and plot the
temperature T
DEMO 3: Loading a Model from an MPH-File
Load a COMSOL Model Object
Display the geometry and mesh
Display the results
Evaluate data in the MATLAB interface
Update a global parameter and compute the solution
Solve the model using a for loop
Display a graph of the result
The Model Object: tags
Nodes in the Model Builder tree and in the LiveLink for
MATLAB

are identified by their tag. The tag is shown by using
the View menu.
Loading a Model Library Model
Load the model busbar.mph as
model
Note: mphload loads a file from the MATLAB local
directory, the MATLAB PATH or the COMSOL Model
Library if no path is given in the statement.
Displaying the Geometry
Run mphgeom to
display the geometry
in the Model Object
Displaying the Mesh
Run mphmesh to display
the mesh stored in the
Model Object
mphgeom and mphmesh can be called
without the name of the geometry or mesh if
there is only one geometry or mesh, which is
the most common case. If you wish to use
more options for these commands you have
to supply the name of the geometry or mesh.
Displaying Results
Plot the plot group pg2
with the color legend
For mphplot you always have
to give the plot group tag
Extracting Data at Specified Coordinates
Evaluate the temperature using
mphinterp at the x,y,z coordinates
[0.05;-0.025;0.001] and assign the
results to the MATLAB variable T
Extracting Data at Node Points
Values are stored in the
structure field d1
Using mpheval, evaluate the norm of the current
density at boundary 43. The property edim is set to
2 which represents a boundary surface entity of
geometric dimension 2.
mpheval allows the user to
extract data at node points. It
returns a MATLAB structure
containing the expression
name, the point coordinates,
and the data values
Evaluate Integral
Use mphint2 to evaluate integral, here
evaluate the total current through boundary 43
Calculating Average Values
Using COMSOL API
methods
Using the wrapper
function mphmean
Changing a Parameter
mphgeom automatically
updates and displays the
geometry
Use the set method to change
the length parameter, L
Changing a Global Parameter Using MATLAB
Variable
The set method support
MATLAB variable input
Solving the Model
The run method computes the
solution. Here run the sol1
solver sequence.
Enable the progress window
The progress window is not
supported on Mac OS X
Display the Results
mphplot display the plot
group pg2 in MATLAB figure
Using a For-Loop to Solve Variations of a Model

Create a vector
with length values
For each parameter, update the model
settings with MATLAB variable and compute
Plot the temperature value vs
the geometry length parameter
Extract in the workspace the temperature
value at [5[cm];-2.5[cm],1[mm]] and plot the
result
Demo 4: MATLAB Function Callback in the
COMSOL Desktop Model Description
Heat transfer problem in
solid.

Thermal conductivity and
external heat source
defined with external
MATLAB functions.


Heat Flux
Fixed
temperature
Fixed
temperature

Define the M-function
To access these functions within the COMSOL Desktop make sure that the path of the
file directory is known in MATLAB.
To proceed either:
Set in the path in MATLAB prior to calling the function.
Save the function M-file at the same directory of the COMSOL MPH-file.
Set the system environment variable COMSOL_MATLAB_PATH with the M-function file path.

Model Wizard
Start to select a 3D, Heat Transfer in
Solid, Stationary model
Click next, to change page
Click finish to leave
the Model Wizard
Add MATLAB Functions
In the Settings page, set the Function name and the
function arguments
Select MATLAB
Right-click Global definitions
Display the Function
A MATLAB process automatically starts and
evaluates the function value, which is then returned
to the COMSOL model
Click Plot button
Set the plot parameters limits
Create the Geometry
Select Block
Right-click Geometry 1
Set Material Properties
Right-click Materials
Set material properties
value
Select Material
Physics Settings (1)
Select boundaries 3, 5 and 6
Note: You can use the Paste selection button to
enter the boundary number list
Right-click Heat Transfer in Solids
Select Temperature
Physics Settings (2)
Select boundary 4
Note: You can use the Paste selection button to enter
the boundary number list
Right-click Heat Transfer in Solids
Select Temperature
Compute the Solution
Right-click Study 1
Select Compute

Potrebbero piacerti anche