When you make a change to a model, including changes to the geometry, COMSOL Multiphysics keeps track of most settings you have applied to the model and their associated selections. If you have a boundary condition applied to a set of boundaries, then the model remembers these settings — and even updates the entity numbers of the boundaries when they change due to changes to the geometry.

Of course, there are cases when settings can’t be kept. For instance, if you delete *all boundaries* that a certain boundary condition applies to, then the boundary condition will have an empty selection. Thus, it will not contribute to the model unless you manually add new boundaries to its selection.

In Part 2 of this blog series, we showed you a method of using coordinate-based selections using functionality in LiveLink™ *for* MATLAB® to obtain entity numbers for setting up models. This is very easy to work with on the command line, but when working with selections in COMSOL Multiphysics, it is much easier to add selections via the user interface (UI) and then apply the physics settings to these selections rather than to the geometric entities. This way, you are leveraging the internal framework that keeps track of geometric entities and you do not need to use entity numbers when setting up a model.

There are two ways to add a selection to a model. The first method is to select the *Create Selections* check box that is available for every geometric operation.

This way, you can easily create selections that contain the output entities of the operation. Selections will be created for domain, boundaries, edges, and points. The name of the selections will consist of the tag of the geometry and object plus “_dom”, “_bnd”, “_edg”, and “_pnt”. For instance, for a rectangle with the tag *r2* the tag of the boundary selection becomes *geom1_r2_bnd*.

The second method of adding selections to a model is to create *named selections* in the model tree. These can be added as nodes in the *Definitions* branch of the model tree, as well as in the *geometry sequence* itself. It doesn’t matter very much where you add named selections, but selections in the geometry sequence can not only be used for physics or mesh settings but also as input to downstream geometry operations. By choosing descriptive names, you can obtain a good overview of the geometry sequence itself.

Let’s take a look at a named selection in the geometry sequence. Navigate to the *Geometry 1* node in the model tree and right-click, then click on “Selections”. Upon doing so, you’ll see a list of different selection types:

The Box Selection corresponds to the command `mphselectbox`

, but since this selection is more tightly connected to the COMSOL Multiphysics geometry, it has more options. You can choose to include the entity either if *anything* is inside the Box or if *something* is inside it. You can also *group by continuous tangent*, which allows you to select adjacent faces or edges that have continuous tangent (by some tolerance). I will not use these advanced features in this example.

For the example model of the heat sink, I will add two selections: one selection for the hot part of the heat sink and another selection for the cold side. In comparison, I made three calls to `mphselectbox`

in Part 2 of the blog series. In order to get the *hot* selection, I simply select the check box for *Create Selections* for the rectangle that defines the first component. Since this rectangle is used in an Array operation, the selection is automatically extended to cover all parts of the array. For the cold side, a Box Selection is added to the end of the geometry sequence to include the upper part of the heat sink. Now, even if I add more fins — more rectangles — to the heat sink, the box selection will automatically include them, since it is the last node in the geometry sequence.

*Box Selection configured to output the boundaries that fall within the specified limits, in this case the cold side of the heat sink.*

After having set up the selections, the boundary conditions in the model have to be configured so they utilize the selections. From now on, the geometry can be updated without having to worry about the selections or the entity numbers that COMSOL Multiphysics uses internally. Now the model can be saved and used both from within the COMSOL Multiphysics® UI and from the MATLAB® software. Setting up the selections can, of course, also be carried out using the COMSOL API. To see how this is done, you can simply save the model as a model file for MATLAB® software, as described in Part 1 of the Working with M-Files series.

When you load a model that contains selections using LiveLink™ *for* MATLAB®, you can view the selections using the wrapper function `mphviewselection`

. To see the selection for the cold side, you can execute ` mphviewselection(model,'geom1_boxsel1')`

.

*Boundaries (in red) output by the box selection for the cold side of the heat sink when viewed using the command mphviewselection.*

In the example in Part 2, I modified the geometry by adding more fins to the heat sink. Instead of using `mphselectbox`

multiple times for each version of the geometry as I did there, here I add the selections to the model just once and leave the hard work of updating geometry and selections to the software.

First, you load the model into MATLAB® software using the mphload command:

It is very simple to write the code for changing the geometry and solving the model. By using the built-in COMSOL Multiphysics® software selections, there is no need to adjust anything when using MATLAB® software for updating the model. Thus, the loop becomes shorter than before:

Running this script produces the results plot shown below.

*Temperature distribution in the heat sink for different fin configurations.*

You can verify the settings that are included in a model by writing “model.selections”. MATLAB® software will write the names (tags) of the selections in the model:

You can find out what a selection contains by using the “mphgetselection” function, which for the *geom1_r2_bnd* selection gives this result:

There are several ways of making sure that selections for model settings are preserved when you introduce large changes to a model geometry. Using commands that come with LiveLink™ *for* MATLAB®, you can keeping track of the entity numbers within specified coordinates. The downside of this approach is that you then have to continue using these commands for updating the geometry. The method will break down if you load the model into the COMSOL Desktop® environment. If you instead rely on named selections in the model tree, you can obtain the same result and also have the ability to work with the model both at the MATLAB® software command prompt and in the COMSOL Desktop®.

If you’ve been wondering whether or not we can do without entity numbers in selections, the answer is “Yes.” As you saw here, we can indeed do without manually fiddling with entity numbers in selections. It takes a little work to include named selections in the model, but they offer better usability and robustness.

*MATLAB is a registered trademark of The MathWorks, Inc. All other trademarks are the property of their respective owners. For a list of such trademark owners, see http://www.comsol.com/tm. COMSOL AB and its subsidiaries and products are not affiliated with, endorsed by, sponsored by, or supported by these trademark owners.*

When large changes are introduced to a model’s geometry, keeping track of the numbers that domains, boundaries, edges, or vertices are assigned is a challenge. These numbers are used to specify where certain settings should be applied:

The upper part of the above figure shows a heat sink with only one fin above the heat sink base. This is not a very efficient design, so I’ll add further fins in order to calculate the heat sink’s performance for different designs.

As you can see in the lower part of the figure, the numbering of the boundaries changes when a second fin is introduced on top of the heat sink base. Naturally, the boundaries that are a part of the newly introduced fin have to get numbers that are different from the previous design, since these boundaries have not been a part of the model so far. Introducing the new boundaries also means that some of the old numbers will change.

Note that the numbering is usually very difficult to predict, even for a simple 2D model like this. For a more complicated model in 2D and 3D, it becomes even more complicated. The examples and code used here could just as easily have been made with a 3D model, but I’ve chosen to go with a 2D model, as it becomes much easier to follow what’s going on.

When applying model settings to boundaries, the numbering becomes important. The figure below shows what the boundary condition for the cool side of the heat sink looks like:

*The boundaries are easily identified in the Graphics window on the right. The corresponding numbers are seen in the Heat Flux settings window in the middle (circled in pink)*.

Let’s have a look at what the corresponding selections look like in the model M-file code:

The first set is for the upper part, where the cooling takes place, and the second set represents the hot part of the heat sink. When the second fin (or more, depending on your modeling scenario) is added to the model, we normally have little idea of which selection numbers to use.

There are two distinct ways of keeping track of the entity numbers:

- Using LiveLink™
*for*MATLAB® functionality to track geometric entities based on their coordinates - Working with selections from geometric operations to track geometric entities

Method 1 is usually the easiest when you are introducing very large changes (such as new objects, for instance, like we will do here) into a geometry and the number of geometric entities change. This method makes it very easy to work with a model on the command line when changing the model bit by bit.

Method 2 usually requires more steps to set up, but has the added benefit that once the model has been set up, you can avoid the use of entity numbers altogether. The model can be used either via LiveLink™ *for* MATLAB® or directly in the COMSOL Multiphysics® user interface (UI), with ease.

Note that if you have a model where you don’t add or remove objects and you do not change its topology, then the numbering of the selections in the model will automatically be updated when you change model settings, and, for example, move objects from one location to another.

The model is available as both an M-file and an MPH-file. Typically, the best solution is to use the MPH-file as a base for the changes to the model. Loading an MPH-file is usually faster than running the corresponding M-file. The MPH-file can, of course, contain meshes and solutions that can’t be saved as part of the M-file, which makes plotting model results a lot easier.

We load the model using this command: `model = mphload('heat_param1')`

A new fin is introduced into the model by these simple commands:

The design is verified by using this command:

`mphgeom(model,'geom1','edgelabels','on')`

which plots the geometry in a MATLAB® figure.

This produces the lower part of the heat sink figure . In this figure, the numbers can be identified visually, but we would like to automate the process such that we can vary both the number of fins and their design. Getting the entity numbers of the boundaries that we need is easy if we use the `mphselectbox`

command. This command selects entities using a box for which you have to specify the coordinates of two opposite corners. There is a corresponding function called ` mphselectcoords`

that selects entities inside a circle (or a sphere in 3D), but we will not use that function in this example.

Below, are the `mphselectbox`

commands that we have to use for this model. For the cooling fins, we supply one set of coordinates that cover the entire upper part of the heat sink. This means that when I add more fins to the heat sink, these new fins will be covered by the rectangle and I can use the same code to get the selection numbers at that time. For the hot, lower part of the heat sink, I have to use two calls to mphselectbox and take the union of the selection numbers. “Union” is a standard MATLAB® function that takes the union of a set. It is also possible to use the MATLAB® functions, “setdiff” and “intersect”, in order to play around with the selection numbers to get the result you wish.

The output looks like this:

Now it is easy to update the model settings with the correct numbers:

Once the selections have been set up, it is easy to adjust the number of fins. The following script shows how to set up a simple loop that will add four fins (one by one) to a model and solve. The goal is to find the effect of adding more fins to the heat sink.

The first line is used to load the model from an MPH-file. This way, we don’t have to run an M-file, which usually takes longer time than loading an MPH-file.

In the for loop, some more fins are added to the model with a proper size and location. The selection numbers are retrieved using mphselectbox and the model is solved. We generate a plot of each result to be studied when the analysis is completed.

The method “uniquetag” is used to get a tag for the new fin (Rectangle). When we use uniquetag, we don’t have to guess what tags are already taken and which might be available. This use of uniquetag with an ‘r’ as argument will return a tag that consists of ‘r’ and a number that is available.

When we change the geometry in a model (especially when we introduce new topology), it is important to keep track of the entity numbers for specifying model settings. An efficient way of doing this in a model M-file, or at the MATLAB® command line, is by using the wrapper functions, `mphselectbox`

and ` mphselectcoords`

, that return entity numbers based on entity coordinates.

The next blog post in this Working with M-files series will discuss how we can set up a model using selections from geometric operations. This leads to a model that is easy to handle both with LiveLink™ *for* MATLAB® and from within the COMSOL Multiphysics® user interface. Using this method means we are working directly with the selection objects and, in many cases, can avoid the use of entity numbers altogether.

*MATLAB is a registered trademark of The MathWorks, Inc.*

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.

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.

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:

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.

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.

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:

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):

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.

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:

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

We often use spreadsheets to store numerical data originating from various sources. Since spreadsheet tools, such as Excel®, are used by most everyone in an organization, the data can be collected, stored, and transferred between people and departments without special regard for programs that must be used to process and utilize it. The data may originally have been obtained from online sources, in-house or external databases imported from other file formats, or simply entered directly into the spreadsheet when the measurement was obtained.

Spreadsheets are perfect for handling data, since you can easily sort and filter it. You are also able to validate the data by visualizing it graphically before using it in your models. While spreadsheets are geared more towards handling a variety of data sources, COMSOL Multiphysics® allows you to enter material data either directly in your models or in user-created material libraries that can be used by many models.

When we introduced LiveLink™ *for* Excel®, we opened up the possibilities for collaboration across teams and departments. Now, your own or your colleague’s model data can be edited immediately in Excel®, and these edits can then be transferred back to COMSOL Multiphysics simply by pressing a button.

LiveLink™ *for* Excel® also includes a few features for exporting spreadsheet data into COMSOL software material data files, which can be used directly for subsequent modeling. The material data can even depend on field values, such as pressure and temperature.

As mentioned previously, data can come from many sources. Here I’ll show an example using some data from Wikipedia. It’s from a table that contains values for the density of water for different temperatures, listed in descending order.

We copy and paste the data directly into Excel® and it’s ready for exporting into a COMSOL Material Database file.

*Used with permission from Microsoft.*

Now, we have to specify both where the field variable (temperature) and the property (density) are defined in the spreadsheet as well as what their units are. In COMSOL Multiphysics, you can define your data in almost any combination of units, but it’s important to specify which units you are using when you import the data. You do this by first clicking on the Settings button.

*Settings button.*

A large dialog box will open that is used to define the data ranges for the inputs. The field variable and material properties are defined on two different tabs in the dialog box, as you can see below.

*Field Dependent Data tab in the Settings window.*

*Material Properties tab in the Settings window.*

Finally, we are ready to export the data and click “OK”. We export the data by clicking on the “New” or “Append” buttons where we can also provide a file name for the Material Library. The next time we start up COMSOL Multiphysics and open the Material Browser, we’ll see the new library in the list of Material Libraries, ready for use.

When you import data using the method shown above, the data is interpolated automatically by COMSOL Multiphysics when solving the model. This is vital when the data varies a lot and an analytical expression cannot be fitted to the data.

Next up, I’ll show you a simple example using the thermal conductivity of copper’s dependency on temperature, using data from this source. Since there is only a small amount of data, the easiest way to import the values for copper is simply to write them in the spreadsheet. I then plot the data as a scatter plot, which allows me to fit a second order polynomial to the data. Since there are only three data points, I achieve a perfect fit, which looks reasonable in the given data range. Extrapolating outside the range can, however, be very dangerous.

*Used with permission from Microsoft.*

The following fitted polynomial can be used directly from within COMSOL Multiphysics:

$$ k_c = -5 \cdot 10^{-5} T_c^2 -0.0025 T_c +401.09 $$

where is the thermal conductivity of copper and is the temperature in Celsius. The easiest way to use this expression in COMSOL Multiphysics is to define some expressions for these two variables.

COMSOL Multiphysics will then automatically interpret these expressions and symbolically calculate any derivatives that may be needed during the solution process. The idea of being able to enter expressions anywhere a setting can be defined in the COMSOL user interface is important since it allows you to customize the built-in models and parameter data without having to resort to writing external libraries.

- Archived Webinar: LiveLink™
*for*Excel® Streamlines Simulation in COMSOL Multiphysics® - Video Tutorial: Importing Excel® Data into a COMSOL® Model
- Blog posts:

*Excel is a registered trademark of Microsoft Corporation in the United States and/or other countries.*