Best Practice for Working with Model M-Files

Lars Gregersen May 14, 2014
Share this on Facebook Share this on Twitter Share this on Google+ Share this on LinkedIn

When developing models in COMSOL Multiphysics® software, it is common to come across tasks that have to be carried out repeatedly. This three-part blog series will show you how repetitive tasks can be efficiently achieved using model M-files and LiveLink™ for MATLAB®.

Introducing Variations into Models

You can introduce many variations into your models through the COMSOL Multiphysics user interface (UI). Functionality, such as parametric sweeps and optimization, allow you to vary a set of parameters in tailor-made edit fields for this purpose.

Yet, some types of variations are not catered to by the UI. In these cases, LiveLink™ for MATLAB® comes in handy as it can access all the model settings, using the COMSOL® API for use with Java® (COMSOL API).

With LiveLink™ for MATLAB®, it is possible to:

  • Start simulations automatically from a MATLAB® program
  • Introduce changes to model settings through the use of scripting
  • Create models from scratch
    • Creating the geometry, meshing, defining physics, calling a solver, and postprocessing the results
  • Read CAD files and files containing meshes
  • Connect to other data sources and read data from files, databases, etc.
  • Create a simplified UI for novices to run models

Many of these features are important if you wish to avoid repeating your work in the COMSOL Multiphysics UI.

Building a Model from Scratch Using LiveLink™ for MATLAB®

If you are new to LiveLink™ for MATLAB®, then the Introduction to LiveLink™ for MATLAB® manual provides sufficient information to get you started. In particular, the LiveLink™ for MATLAB® User’s Guide provides further resources about the commands within the COMSOL Multiphysics API and the equivalent MATLAB® functions they access. You can actually create your first model M-file, which controls a COMSOL Multiphysics model, without having to read this documentation. This is because such scripts can be auto-generated from the COMSOL Multiphysics UI.

Let’s look at a simple heat transfer example that only requires the COMSOL Multiphysics base package to build and solve. The geometry can be seen in the following figure, where a heat flux is introduced at the bottom boundaries and dissipates into the surrounding air at the top boundaries.

A geometry where heat flux originates at the bottom boundary and then dissipates into the air

Plot created with COMSOL Multiphysics that shows the surface temperature of a model

The geometry consists of a few rectangles that are either combined with or subtracted from each other. The M-file code for making this geometry can be seen below:

Example M-file code needed to make a geometry

Here, the code is commanding COMSOL Multiphysics to create rectangle nodes in the model tree, as well as the node that takes the difference between rectangles. You see that the size and position (pos) of the entities are defined. These definitions can be used to define the geometry as you’d like it to be. It is evident that even small geometries may lead to a lot of defining code. The next section shows how to create lines automatically.

Automatic Generation of Model M-files

All functionality within COMSOL Multiphysics can be represented by a line of code, and a full model would correspond to many lines of code. Instead of creating a model from scratch using a script, you can create it in the COMSOL software UI and then save it as an M-file. This is done by choosing File > Save as and then selecting “Model File for MATLAB (*.m)”.

Such an M-file contains all the steps that have been followed when building the model. By running the file using LiveLink™ for MATLAB®, you will notice that all the commands that were performed are recorded. If the model was solved several times, there will be several calls to the solvers, which you typically don’t want. If you were to run the model from the MATLAB® command line, it will solve the model several times. In order to obtain an M-file that is compact, you can choose File > Compact History before saving the file.

Diagram showing the steps necessary to obtain a compact M-file

Now that we have the entire model as an M-file, we are free to investigate — or change — any of the settings in the model. We can add new features to the model, as well.

Have a look at your M-file and see if you can identify the various sections of the model and how things are set up. Some things will be easy to understand in a model, such as how parameters and the geometry are defined. Other things, such as solver or plots settings, can be more obscure. However, if you have MATLAB® coding experience, you should easily be able to see where things are defined.

In the following example snippet:

Example code showing how mesh settings are defined

you can see how the mesh settings are defined. When an M-file contains the definition of the geometry, physics, mesh, solvers, etc., a call is made to a “run()” method. This takes all the commands in the M-file and executes them in COMSOL Multiphysics. Calls to “run()” may take a long time if your model is big, so if you wish to follow the solution progress, you can switch on the Progress window by using this code (before calling run):

Code used to turn on the Progress window prior to calling a run

Working Even Faster Without Model M-Files

If you use MATLAB® to change a model using the COMSOL software API and lose track of changes, it is nice to know that you can always save the model as an MPH-file, load it into the COMSOL Multiphysics UI, and inspect it there. Furthermore, you can load MPH-files into MATLAB® and manipulate them from there, as well.

The following example loads an MPH-file and performs a “for” loop on the parts of the model that has changed (its geometry) before solving it.

Code that loads a MPH file and runs a for loop on model parts that have been changed


One of the biggest reasons for working with M-files is to be able to manipulate geometries. In order to do this, you need to understand Selections:

Code that sets up physics for heat transfer and boundary conditions for Heat Flux Boundary

The above code sets up some of the heat transfer physics, including two boundary conditions for a “Heat Flux Boundary” on a series of boundaries, identified by numbers. When a geometry is changed in a way that introduces more domains, boundaries, or vertices, these numbers will change too. You will need a way to either track these numbers, or avoid using them.

These will be the topics of the next two blog entries in this series. Stay tuned.

MATLAB is a registered trademark of The MathWorks, Inc.



  1. Peter Cendula September 16, 2014   8:20 am

    Thanks for useful blog! I tried to ‘compact history’ in my rather larger MPH file and I got the error ‘Unknown model parameter’. Is there any way to workaround this?


  2. Lars Gregersen September 16, 2014   8:24 am

    COMSOL analyzes the structure while performing Compact History, but sometimes has to give up. Please send the MPH-file to so we can have a look.

  3. Mathias Perrin December 29, 2015   5:25 am

    Thank you for this blog,

    I use every day Matlab Livelink with comsol, and I think it is very efficient.

    It is a fantastic tool when you combine Matlab advantages (graphics, data posttreatment, highlevel mathematical functions such as FFT, matrix operations) with Comsol advantages (multiphysics approach, numerical computation of complex physical problems).

    That’s why I am trying to compile matlab programs using Matlab compiler. The idea is to be able to distribute exécutables that would use a Comsol licence and Matlab runtime libraries.

    I am trying to compile a simple script that opens some .mph model, using mphload().

    Untill now, I always have some bug at runtime. It is probably a matter of setting correctly the path to the .dll and java files that are needed at runtime.

    I discussed with Comsol but they don’t support matlab compiler, and of course matlab do not support compilation of comsol exécutables.

    So, if someone ever tried, and has a procedure, or at least some experience, I would be very very glad to know it !



  4. Lars Gregersen January 4, 2016   9:59 am


    Although not officially supported applications compiled with the Matlab Compiler should work together with Comsol Multiphysics.

    When creating your application then include a call to mphstart at the beginning of your application. Make sure to use one of the variants of mphstart that includes a COMSOLPATH. Make sure you use the correct COMSOLPATH at runtime. Comsol has to be installed on the computer in order for the application to run.

    If this doesn’t work then please contact support and we’ll see if we can help you. Please include the version of Matlab and your operating system that you are using in the message to us.

  5. Oscar Diaz April 7, 2016   3:45 pm

    Hej Lars,
    Nice blog entrances on Matlab livelink. Some of those useful tricks I learned on the way, by creating a model, compacting the history and saving the m-file to check some syntaxis errors and similar.
    The program that I did, creates new geometries during the execution process calling different comsol-functions from matlab. Always when the meshing crashed and red text came to the matlab command window, indicating an error and that the execution was cancelled.
    Now, after 3h execution, the execution got stocked somewhere, but I cannot find where. While in normal execution, it has been calling the same functions since the early beginning until it just dies…
    It might have to do something with memory I guess (not so sure), because the only closing/stopping possible when goes to this problem, is closing the OS command window where the comsol server was started. Then, I go back to Matlab editor, and find out an active breakpoint (green arrow on a code line that stops the execution when the program reaches that code line), even if the comsol server is already closed (not possible to continue in execution). Can it be that the size of the object that is stored in the memory of the Comsol API overflows the memory available (the output files from previous steps is ca. 100MB)
    I’ve been stocked here for a long time, do you have any suggestions?

  6. Lars Gregersen April 8, 2016   2:43 am

    Hi Oscar

    Without seeing your script it is hard to guess what goes wrong. It is quite easy to run out of memory when you are creating a large model using a script since you can easily create thousands of geometric objects, physics and settings, which all take up memory, of course.

    The most common memory related mistake when creating models and geometries using a script is that when you create a model using
    model = ModelUtil.create(‘Model1′)
    each subsequent statement you execute will add some information to the model history. This is done such that you later can export an M-file (or VBA- or Java-file) with all you steps. However, exporting such files are rarely useful (since you already have a script that can do what you want) and you can always use “Compact model history” to get what you want.
    The solution is to switch history generation off. We always cover this topic at the tutorials we give at the Comsol Conferences. It is also mentioned in the Introduction to LiveLink for Matlab manual where it says you need to write:

    If this doesn’t help your case then please send your script/model to Comsol Support where we will have a look at it.

Loading Comments...