Note: This discussion is about an older version of the COMSOL Multiphysics® software. The information provided may be out of date.
Discussion Locked This discussion was locked by a forum moderator.
Creating and using external Matlab functions
Posted 30 lug 2010, 14:00 GMT-4 LiveLink for MATLAB Version 4.4 45 Replies
Please login with a confirmed email address before reporting spam
external Matlab functions?
I am running Comsol 4.0a, and would like to be able to pass
parameters to a Matlab function, do some calculations, pass
the results back to Comsol and assign them to a variable. It
would also be really useful to be able to pass back and assign
an array of results to Comsol variables. An example of this
would be in the Chemical Reaction Engineering Module
where one might want to compute externally an array of
reaction coefficients for assignment to Comsol. Is this
possible?
I have no problem launching Live Link and exporting models
to Matlab. However, the procedures for defining and invoking
a Matlab function from within Comsol are unclear in the
documentation. The basic description is:
1. Right click Global Definitions, and then go to Functions=>Matlab
A MATLAB1 node is created.
2. Select the MATLAB1 node, and under Settings, enter in the required
information. This includes the Function name and Arguments. There
is a button for plotting the function, but it invokes an error message
saying you can't plot a Matlab function.
3. Comsol can't fiind any external Matlab function that I create.
I tried numerous things, including putting the function in the
default Matlab 2010a path, in the Comsol 4.0a directory,
etc. None of them worked.
Things that are expected but missing from the Matlab
function interface and the documentation are:
1. The path to a stored Matlab m-file with the function.
How does Comsol know where to look for it, or does
it follow the Matlab path tree as defined in Matlab? Is
it possible to define a path within Comsol independent
of Matlab (this would be preferable, since it wouldn't
require messing with an otherwise stable Matlab tree.)
2. Some information about restrictions on usage of such
a function, for example only allow return values of floating
point, and no arrays permitted. (see my comment above
about reaction rates.)
3. At least one worked example illustrating proper
usage would be very useful.
Anyone with experience successfully doing this?
Thanks!
Dave
Please login with a confirmed email address before reporting spam
sorry I cannot give you any clues yet, this is on my list of things to check in the new V4, but there are so many things to check with such a major revision (I cannot just go ahaid and sell my projects on a new version without a minimum of checks. I must myself be convinced that I master and believe in the results of my main calculation tool.
But I can only confirm that array/vector argument passing yould really be a must for many fields, also for postprocessing and "table" data generation.
For Comsol analytical functions you can pass several arguments as space separated names lists, though
--
Good luck
Ivar
Please login with a confirmed email address before reporting spam
I'm sorry about the confusion.
Here are some answers for your questions:
1)
Comsol relies entirely on Matlab being able to find the function. I.e. you have to add the directory where your function is placed to the Matlab PATH. Do this by opening Matlab. Alter the Matlab PATH using File->Set Path. Remember to save the new Matlab PATH. Close down Matlab.
Plotting is only possible when Matlab can find the function. This is supposed to work.
2)
For a Matlab function defined as
function y=myfunc(x,y,T)
the arguments x, y and T will be vectors of equal size. The function must return a vector y of the same size as the input arguments.
3)
We will create a knowledge base entry for this.
We realize that the documentation is a bit short on this. We will update the documentation for Comsol 4.2 and also provide some extra ways to set the Matlab PATH from within Comsol Multiphysics.
Regards
Lars Gregersen
Comsol Denmark
Please login with a confirmed email address before reporting spam
Thank you for your detailed and informative reply.
Using Matlab's path settings makes sense.
The ability to pass vectors as arguments in a Matlab function
call and return a vector of the same size is great and will
be very useful.Would it be correct to assume that these
Matlab function calls can be used in variable definitions,
in weak expressions, and in other places where string
expressions occur?
In the future documentation for Matlab it would be extremely
useful to have a short tutorial with a few worked examples
of how to access and manipulate data exported to Matlab .
Examples of what users might find helpful would include
such things as getting a list of dependent and independent
variable names, and accessing mesh data corresponding
to these names.
Also, it would be good in future documentation to have a clear
discussion about exactly what the differences are between
the native language that Comsol uses and Matlab, including
some details about the differences in their libraries. There
are a lot of similarities in the respective function libraries,
but there are differences, too. It would be good to see a
description that explicitly addresses the differences and
whatever issues of usage there might be.
A suggestion about a useful feature that would
great to see in Comsol is a Text Editor. At present, there
appears to be no utility for creating and working with
complicated string expressions efficiently. For example,
weak expressions are quite often very complex and it is
easy to make mistakes with balanced parentheses etc. when
typing them in. In some places a string expression is color
coded red when some kind of parsing error occurs, or orange
when an apparent inconsistency in units is detected. This is
very useful, but often the text box containing a string
expression is too small to display it, and even a mouse
hover exposing the full expression often reveals a hugely
complicated expression that is difficult to decipher.
It would be useful to have a separate Text Editor for creating
these expressions and parsing them for correctness, similar
to Matlab's text editor but working entirely within Comsol. This
editor would, ideally, allow comment lines, statement
continuation to more than one line, etc. It would also be aware
of other variables in a model and have visual clues like color
coded variables and bars along the right side flagging incorrect
expressions, and a lint-like capability that would permit
a user to detect and correct most syntax and usage errors
before submitting a run.
Many thanks again.
Dave
Please login with a confirmed email address before reporting spam
Dear Davis Sentman,
I have been trying to work with Comsol through Matlab. I need to modify some parameters from Comsol with a Matlab function and then give these parameters back to Comsol.
First of all, although I followed the steps explained in "Livelink for Matlab-User’s Guide" page 24 (for Comsol 4.0a), I am not able to use a Matlab function in Comsol program. There is no problem when defining the function (even though the information given in the manual is not really clear) but when I execute Comsol I always obtain the error "Undefined variable", being the variable not defined my matlab function.
After that, I tried to directly change the Comsol script in Matlab, but I cannot use Matlab functions. THe point is, I need to use a Matlab function whose arguments are the X and Y coordinates from Comsol. I do not know how to set this up,t herefore Matlab keeps complaining it does not understand the arguments of the function.
By the way, it is also not clear for me how I should handle the values from Comsol: I do not know which type of values they are (doubles, strings?), which are the comsol functions I need to use to get those values and set them back (until now I have only discovered setU and getU...)
I read you had similar problems so I would like to know if you finally found out a solution. I would be really pleased with any idea or example.
Thank you very much,
Cristina
Please login with a confirmed email address before reporting spam
Lars,
Thank you for your detailed and informative reply.
Using Matlab's path settings makes sense.
The ability to pass vectors as arguments in a Matlab function
call and return a vector of the same size is great and will
be very useful.Would it be correct to assume that these
Matlab function calls can be used in variable definitions,
in weak expressions, and in other places where string
expressions occur?
In the future documentation for Matlab it would be extremely
useful to have a short tutorial with a few worked examples
of how to access and manipulate data exported to Matlab .
Examples of what users might find helpful would include
such things as getting a list of dependent and independent
variable names, and accessing mesh data corresponding
to these names.
Also, it would be good in future documentation to have a clear
discussion about exactly what the differences are between
the native language that Comsol uses and Matlab, including
some details about the differences in their libraries. There
are a lot of similarities in the respective function libraries,
but there are differences, too. It would be good to see a
description that explicitly addresses the differences and
whatever issues of usage there might be.
A suggestion about a useful feature that would
great to see in Comsol is a Text Editor. At present, there
appears to be no utility for creating and working with
complicated string expressions efficiently. For example,
weak expressions are quite often very complex and it is
easy to make mistakes with balanced parentheses etc. when
typing them in. In some places a string expression is color
coded red when some kind of parsing error occurs, or orange
when an apparent inconsistency in units is detected. This is
very useful, but often the text box containing a string
expression is too small to display it, and even a mouse
hover exposing the full expression often reveals a hugely
complicated expression that is difficult to decipher.
It would be useful to have a separate Text Editor for creating
these expressions and parsing them for correctness, similar
to Matlab's text editor but working entirely within Comsol. This
editor would, ideally, allow comment lines, statement
continuation to more than one line, etc. It would also be aware
of other variables in a model and have visual clues like color
coded variables and bars along the right side flagging incorrect
expressions, and a lint-like capability that would permit
a user to detect and correct most syntax and usage errors
before submitting a run.
Many thanks again.
Dave
I followed Lars's steps, but there was still an error: MATLAB functions cannot be plotted directly. You can define and plot an analytic function that calls the MATLAB function that you want to plot.
I don't know why.
Please login with a confirmed email address before reporting spam
cheers,
mike
Hi Dave
I'm sorry about the confusion.
Here are some answers for your questions:
1)
Comsol relies entirely on Matlab being able to find the function. I.e. you have to add the directory where your function is placed to the Matlab PATH. Do this by opening Matlab. Alter the Matlab PATH using File->Set Path. Remember to save the new Matlab PATH. Close down Matlab.
Plotting is only possible when Matlab can find the function. This is supposed to work.
2)
For a Matlab function defined as
function y=myfunc(x,y,T)
the arguments x, y and T will be vectors of equal size. The function must return a vector y of the same size as the input arguments.
3)
We will create a knowledge base entry for this.
We realize that the documentation is a bit short on this. We will update the documentation for Comsol 4.2 and also provide some extra ways to set the Matlab PATH from within Comsol Multiphysics.
Regards
Lars Gregersen
Comsol Denmark
Please login with a confirmed email address before reporting spam
Attached is an example model made with COMSOL 4.1.0.154. The model itself and the properties it calculates are not resemble any physical system and this example should only be used for studying the MATLAB functions in COMSOL Multiphysics.
The example shows how to define a MATLAB function and how to use it for the definition of material parameters and for plotting.
You can place the extfun_heatcond.mph anywhere, but the thermalcond.m file must be placed where MATLAB can find it. MATLAB searches for files on the MATLAB PATH, which can be viewed and altered using File->Set Path.
If you have (had) more than one version of MATLAB installed on your computer you should look at this knowledge base entry:
www.comsol.com/support/knowledgebase/1093/
If things are set up correctly on your computer you will be able to load the extfun_heatcond.mph file and select Study->Compute.
We have noted that setting up the MATLAB PATH is the most difficult part of making this interface work for our customers. In Comsol 4.2 we will add a few extra ways to add directories to the MATLAB PATH that should help a lot with these issues.
Best regards
Lars Gregersen
Comsol Denmark
Attachments:
Please login with a confirmed email address before reporting spam
Sure
Attached is an example model made with COMSOL 4.1.0.154. The model itself and the properties it calculates are not resemble any physical system and this example should only be used for studying the MATLAB functions in COMSOL Multiphysics.
The example shows how to define a MATLAB function and how to use it for the definition of material parameters and for plotting.
You can place the extfun_heatcond.mph anywhere, but the thermalcond.m file must be placed where MATLAB can find it. MATLAB searches for files on the MATLAB PATH, which can be viewed and altered using File->Set Path.
If you have (had) more than one version of MATLAB installed on your computer you should look at this knowledge base entry:
www.comsol.com/support/knowledgebase/1093/
If things are set up correctly on your computer you will be able to load the extfun_heatcond.mph file and select Study->Compute.
We have noted that setting up the MATLAB PATH is the most difficult part of making this interface work for our customers. In Comsol 4.2 we will add a few extra ways to add directories to the MATLAB PATH that should help a lot with these issues.
Best regards
Lars Gregersen
Comsol Denmark
Hi, I tested the example you gave, it model can work but I still have problems. In the MATLAB function interface, i.e., Global Definitions --- MATLAB (thermalcond), I press the "plot" button, an error occurred "MATLAB functions cannot be plotted directly. You can define and plot an analytic function that calls the MATLAB function that you want to plot." Why? The other question is about the "Arguments", in this example, it is "arg1", why not "T"? Thank you!
Please login with a confirmed email address before reporting spam
1)
You can't plot directly from the window due to an internal limitation in the way this feature was implemented. It may change in a future release of Comsol. I recommend that you plot your functions using MATLAB.
2)
When you specify the arguments in the MATLAB node you basically just specify the arguments by writing names (placeholders) for the variables that are later going to be used in the calculation.
For a function that accepts two arguments you separate the arguments by comma. E.g. can use "x,y" or "arg1,arg2" or any other legal variable names separated by commas.
When you use the function you specify the real arguments that must be substituted into your function. Hence the use of "T" in the example.
This behaviour is exactly the same as you see when using the analytic function (which is perhaps easier to experiment with).
Lars Gregersen
Comsol Denmark
Please login with a confirmed email address before reporting spam
Brilliant - very helpful indeed.
One last thing is the bit where you said 'The output k must have exactly the same size as column vector T', which is only sensible. But what happens when the function requires two input arguments (column vectors of same size). In such case as long as COMSOL calls the Matlab function at every iteration feeding only one elemnt of arg1 and one element of arg2 it all works fine, but I recall it does not work this way.
From what I remember COMSOL uses Matlab ones to feed the entire vector of argument(s), so from two inputs 5 elements long each we would get 5 elements long outout. In practise from two vector having 5 elements each we would get 25 possible results which means the resulting output will NOT have the same length as inputs.
Is there really no way around it? Can COMSOL comprehend only a situation where it takes 1st element of arg1 with 1st element of arg2 and gets 1st output, then moves to combination 2nd arg1 + 2nd arg2 => 2nd output? (which drastically narrows the number of possible outcomes, omitting combinations like 1st arg1 + 2 arg2).
I mean I can extend both input vectors so that every combination would be 'covered' by following the simple rule above (each would be 25 elemnts long), but with longer vectors it quickly becomes very tedious.
Cheers
Please login with a confirmed email address before reporting spam
When you have two arguments each being vectors with a length equal to 5 your output must also have exactly 5 elements.
The Matlab function may be called once or several times depending on the structure of your problem and size of your mesh. The reason we call the function with vectors is that each call from Comsol to Matlab takes some time and we would like mimimize the number of calls.
In order to handle vector inputs you can use vectorisation of your code in order to get the best speed. For a lot of problem types it is not that easy to perform vectorisation and you can simply run a for loop around you function (which accepts scalar inputs only). Here is the code for such a function:
function q=source(x,y)
% vector inputs and outputs
% Each element of x and y are processed independently
for i=1:length(x)
q(i) = calcsource(x(i), y(i));
end
function q=calcsource(x,y)
% scalar inputs and outputs
r = sqrt(x^2+y^2);
if r<0.5
q = 1000;
else
q = 500;
end
I've attached the function and a model that uses the function.
Lars Gregersen
Comsol Denmark
Attachments:
Please login with a confirmed email address before reporting spam
Your guidance is very helpful.
One more question:
If I modify the m-file of a function in Matlab, and recalculate the model in Comsol or Live-Link, the result doesn't change. I tried to close Comsol and restart, but it didn't work. Using a new function name is ok, but not very convenient.
What should I do to get a new result after modifying m-file?
Please login with a confirmed email address before reporting spam
The missing updates is unfortunately a feature of the Matlab Engine we are using for performing the calls to Matlab. When using this interface Matlab doesn't look for changes to the files.
I suggest that you work with your function using Matlab while designing the function and perform any tests and plots there before using the function from Comsol.
On Windows you have the option of using Matlab's built-in editor (write "edit" on the command line) or you can write "clear functions" to force a reload of the functions.
--
Lars Gregersen
Comsol Denmark
Please login with a confirmed email address before reporting spam
I have not succeeded in doing that, but to stay on the safe side (as it would save me a lot of work) I wanted to ask if/how this can be done?
In Matlab I could just populate the scalar to be a vector of same length as other two inputs like this: repmat(scalar,size(vector_input)), but in COMSOL...?
cheers
Please login with a confirmed email address before reporting spam
this discussion is very helpful. I was able to import some function calculated in Matlab.
@Mike: I ve got some similar problem. In my case, I know that some variable is a scalar, though I only use one entry of the vector to set up if-else-conditions
@all: I realized that loading Matlab functions take several time. In my case, every process extracts some information of a *.mat data set. I ve already vectorized this function but for continuing my work it is still exorbitant slow. Has someone solved this problem or know a work around?
cheers
Dennis
Please login with a confirmed email address before reporting spam
What if a MATLAB function has more than one output variable? How can those individual output variables be distinguished and used in COMSOL.
For example if in your thermalcon.m you have:
[k1 k2]=thermalcond(T)
k1 = 3-0.01*(T-298);
k2 = 5-0.02*(T-298);
Of course an alternative but not an efficient way is to create several function files each contining just one output variable.
Thanks,
Jessica
Please login with a confirmed email address before reporting spam
Sure
Attached is an example model made with COMSOL 4.1.0.154. The model itself and the properties it calculates are not resemble any physical system and this example should only be used for studying the MATLAB functions in COMSOL Multiphysics.
The example shows how to define a MATLAB function and how to use it for the definition of material parameters and for plotting.
You can place the extfun_heatcond.mph anywhere, but the thermalcond.m file must be placed where MATLAB can find it. MATLAB searches for files on the MATLAB PATH, which can be viewed and altered using File->Set Path.
If you have (had) more than one version of MATLAB installed on your computer you should look at this knowledge base entry:
www.comsol.com/support/knowledgebase/1093/
If things are set up correctly on your computer you will be able to load the extfun_heatcond.mph file and select Study->Compute.
We have noted that setting up the MATLAB PATH is the most difficult part of making this interface work for our customers. In Comsol 4.2 we will add a few extra ways to add directories to the MATLAB PATH that should help a lot with these issues.
Best regards
Lars Gregersen
Comsol Denmark
Hi Lars,
I tried your mph file with the m file. After successfully running the problem, I decided to check a couple of things: I changed the thermal conductivity function that was defined in the m function file to get another value of k, but I did not find any change in the temperature and conductivity (I checked a series of k values smaller and greater than k=3). I even made everything in the function file except the first line "comment", but still COMSOL solved the problem without any error and as if it does not call the function all.
Am I missing something here?
Thanks.
Jessica
Please login with a confirmed email address before reporting spam
I do the same, I mean define a boundary condition with Matlab function in a Laminar Flow (spf), however, I get the following error message:
Syntax error in expression.
- Expression: mod1.mat1.def.rho(mod1.spf.fp1.minput_pressure[1/Pa],mod1.spf.fp1.minput_temperature[1/K])[kg/m^3]
According to my observation, it is happens just when I use Laminar Flow (spf) model never more. Can you please suggest me something to avoid this error?
Regards,
Gábor
Please login with a confirmed email address before reporting spam
I ran Lars' code, and it worked fine. Next I set the radius equal to a parameter W, and tried to define W (under Global Definitions --> Parameters as a matlab function rad. The MATLAB function rad() was in the same path as thermalcond in Lars' example, yet COMSOL did not recognize it and gave an error (unknown function rad). In fact inside of "Parameters" COMSOL is unable to recognize thermalcond (yellowed out in COMSOL 4.2) although it works just fine in the material definition.
I need COMSOL to update the geometry as a function of time by calling a MATLAB script. Could someone please help me with this or show me an example where this is done?
Best regards,
Ramu.
Please login with a confirmed email address before reporting spam
Can we include the matlab functions inside the model .m file which is generated after saving from the comsol4.2? I have my matlab functions which can generate the required geometry. How to do it?
How to see the output data in matlab?
Regards,
Varshney
Please login with a confirmed email address before reporting spam
normally you can call it from a GUI command (external matlab function,, or is it that you want to run the saved .m file and link in your matlab command, in which case it should be enough that the file is in the same directory as the calling .m file. (Or have I missed something ;) I hardly need matlb since v4 has arrived
--
Good luck
Ivar
Please login with a confirmed email address before reporting spam
the cited problem is a bug in COMSOL 4.2 and already fixed in version 4.2a.
Regards,
Gábor
Hi All,
I do the same, I mean define a boundary condition with Matlab function in a Laminar Flow (spf), however, I get the following error message:
Syntax error in expression.
- Expression: mod1.mat1.def.rho(mod1.spf.fp1.minput_pressure[1/Pa],mod1.spf.fp1.minput_temperature[1/K])[kg/m^3]
According to my observation, it is happens just when I use Laminar Flow (spf) model never more. Can you please suggest me something to avoid this error?
Regards,
Gábor
Please login with a confirmed email address before reporting spam
How to see the output data in matlab?
Once your model solved in matlab, use the mpheval command, it creates a structure with all you need in it. For example, if you want to know the temperature in the domain :
T = mpheval(model,'T')
it creates the structure T with a lot of stuff in it, check the Matlab Livelink User's Guide --> mpheval
Once you have your structure in matlab, it's way faster than mphplot for plotting results.
P.S. out of context, I know, just want to quickly help the guy...
Please login with a confirmed email address before reporting spam
I've opened Lars's model, and I'm able to see the surface plot
But when I compute to solve the model, COMSOL gave me an error.
Which is the following:
Internal error: cannot convert ElemStruct to int.
- Value: e9
Error in multiphysics compilation.
The 2 MATLAB functions are in my MATLAB directory, in which i know its the right path because I'm able to see the surface plot.
What's wrong with COMSOL?
I'm using MATLAB R2011a and COMSOL 4.2a with the lastest update
Alain
Please login with a confirmed email address before reporting spam
(all the text and photos are integrated in the .doc file, please see the .doc file , thanks)
Files:
extfun_heatcond_q
source.m
thermalcond.m
The above two .m files are put in the directory of matlab, and the .mph file just on the computer desktop.
When open the “extfun_heatcond_q.mph”, I can see the surface plot (under the “Results“ branch) of heat source, conductivity, temperature, which are illustrated in Fig. 1.
Fig. 1 the surface plot of temperature (a), conductivity (b) and heat source (c)
I turn to the matlab node (Global Definitions –MATLAB 1), which is an external matlab function and includes thermalcond and source functions.
Question 1: expression in the “Derivatives” term
There is no expression in “Derivatives” term, I wonder when do I must specify the derivatives?
Question 2: convert ElemStructure to int error when plotting
According to the guidance from the documents (new 4.2a edition), the external matlab function can be plotted only in COMSOL (do I misunderstand?). So I add the data ranges (two data sets because there are two arguments in function) in ”plot parameters”. Then I click the “Plot” to plot the function, but fail, and the error “Internal error: cann’t convert ElemStructure to int” occurs, just like Fig. 2.
Fig. 2 the ElemStructure to int error
Question 3: about the unit in the material property
I check the model whole with the hope of making it clear. Then I found the thermal conductivity is defined using the external matlab function “thermalcond(T)”. While it shows orange-coloured, and implies “unexcitable unit of input”. The T in the COMSOL model have its inherent unit ‘K’, if using “thermalcond(T[1/K])” instead, the color is black (means no error). The “Heat Souce” in the Heat Transfer model node is similar. Is there any difference between them?
Question 4: the ElemStructure to int error again when solving
Then, I click “Study” to calculate the model. However, the following problem occurs just similar with the situation when I try to plot the function only before.
Is There anyone give me some tips and guidance?
Thanks sincerely in advance. Best wishes to you and your family.
FM Huang
Dec.4th.2011
Hi,
I've opened Lars's model, and I'm able to see the surface plot
But when I compute to solve the model, COMSOL gave me an error.
Which is the following:
Internal error: cannot convert ElemStruct to int.
- Value: e9
Error in multiphysics compilation.
The 2 MATLAB functions are in my MATLAB directory, in which i know its the right path because I'm able to see the surface plot.
What's wrong with COMSOL?
I'm using MATLAB R2011a and COMSOL 4.2a with the lastest update
Alain
Attachments:
Please login with a confirmed email address before reporting spam
Hi Lars,
What if a MATLAB function has more than one output variable? How can those individual output variables be distinguished and used in COMSOL.
For example if in your thermalcon.m you have:
[k1 k2]=thermalcond(T)
k1 = 3-0.01*(T-298);
k2 = 5-0.02*(T-298);
Of course an alternative but not an efficient way is to create several function files each contining just one output variable.
Thanks,
Jessica
Hi
I am facing the exact same problem; i want to extract more than 1 output from a matlab function. Did anyone figure out how to do this?
Thank you.
Please login with a confirmed email address before reporting spam
You can only have one output from a Matlab function that is used by Comsol.
If you have cases where you really need more than one output then please send such examples to support where someone will see what we can do about it.
Lars Gregersen
Comsol Denmark
Please login with a confirmed email address before reporting spam
Example:
When the following code segment is embedded in a Matlab script used as an external function with Comsol no file is created. When the function is run from within Matlab (w/o Comsol) it works as expected. I run Matlab 2011a.
...
fid = fopen('nodes.txt','a');
fprintf(fid,'%s\r\n',['t = ' num2str(t) ', no of nodes = ' num2str(n)]);
fclose(fid);
...
Please login with a confirmed email address before reporting spam
Hi and thanks for a good and clarifying discussion. I've got the external functions to work but when I'm trying to get the Matlab script to produce output, e.g. write data to a file as in the script segment below, nothing is produced. Does anyone know if this is due to some known limitation in Comsol?
Example:
When the following code segment is embedded in a Matlab script used as an external function with Comsol no file is created. When the function is run from within Matlab (w/o Comsol) it works as expected. I run Matlab 2011a.
...
fid = fopen('nodes.txt','a');
fprintf(fid,'%s\r\n',['t = ' num2str(t) ', no of nodes = ' num2str(n)]);
fclose(fid);
...
What's the working directory when Comsol calls the script? Maybe you just have to specify an absolute path for 'nodes.txt'...
Please login with a confirmed email address before reporting spam
Hi and thanks for a good and clarifying discussion. I've got the external functions to work but when I'm trying to get the Matlab script to produce output, e.g. write data to a file as in the script segment below, nothing is produced. Does anyone know if this is due to some known limitation in Comsol?
Example:
When the following code segment is embedded in a Matlab script used as an external function with Comsol no file is created. When the function is run from within Matlab (w/o Comsol) it works as expected. I run Matlab 2011a.
...
fid = fopen('nodes.txt','a');
fprintf(fid,'%s\r\n',['t = ' num2str(t) ', no of nodes = ' num2str(n)]);
fclose(fid);
...
What's the working directory when Comsol calls the script? Maybe you just have to specify an absolute path for 'nodes.txt'...
Indeed the path was the issue. I had been running with the working directory being both the standard Matlab one and the folder where the Comsol model was stored, without any succes. When I specified, as you suggested, the complete path like "C:\nodes.txt" everything worked as expected. Thanks!
Please login with a confirmed email address before reporting spam
I've been trying to use a MATLAB function to obtain the value of a geometric parameter. I.e. Based on a calculated volume, I am trying to find the dia of the channel. The formula is as simple as d = sqrt(4*V/h*pi). I defined a matlab function called diameter(Vol,height) to do this. When I use this function inside the 'Geometry' it doesn't quite take in this value. It shows up an error. The same thing happens even when I use analytical functions to define this.
What is going on? Can I not use a function to obtain a geometric parameter value?
Any help would be appreciated.
Thanks,
Please login with a confirmed email address before reporting spam
Please login with a confirmed email address before reporting spam
to update the geometry (and consequently the mesh) you need to use a "parametric Sweep node", that is the only way to have COMSOL "loop" around the full model tree, the solver and solver continuation (sweep) remains with the same geometry and mesh. So this feature is I believe not linked with the fact you are calling a matlab function.
You can call the full sequence in matlab, but then you control OCMSOL from matlab
There might be some subtilities here that I have missed, so in doubt, the true final response can only come from "support"
--
Good luck
Ivar
Please login with a confirmed email address before reporting spam
The trouble that I am having even with the parametric sweep option is the fact that, in my geometry, some of the dimensions and geometric parameters need to be calculated based on some other values that I feed as inputs. It seems to me that COMSOL isn't quite able to do this calculation at the geometry specification level.
And, how do I contact support?
Thanks,
Rohini
Please login with a confirmed email address before reporting spam
for "support" it's easy, scan the main COMSOl web site or jump directly here: www.comsol.eu/support/contact/
Indeed I cannot make it work either, in v4.2a, bizarre
--
Good luck
Ivar
Please login with a confirmed email address before reporting spam
thanks for the very nice posts. I've managed to call a matlab function which takes all three axes as arguments (x,y,z) and returns, e.g. a strength of the magnetic field B of a rectangular permanent magnet. The function takes axes coordinates as vectors and returns B field as a vector as well. The only problem is that this communication between Matlab and Comsol takes very long time, which makes it hard to use in 3D transient or parametric problems.
If I implement the same formulas directly in Comsol everything works much faster, but then I am restricted to simple explicit expressions.
Does anyone have the same experience, and is there a way to make the things a little bit faster.
Best regards,
Mladen Zec
Please login with a confirmed email address before reporting spam
I am new to COMSOL. I currently use v4.3. My model set up like this:
I work on the diffusion model with two domains; domain 1 is HDPE and domain 2 is void embedded in HPDE using Transport diluted species with time dependent solver. My species is hydrogen gas. I have condition like this;
Initial conditions:
domain 1 (HDPE) has concentration of C1
domain 2 (void) has concentration of C2, where C1>C2
BCs: Domain 1's outer boundaries has zero concentration.
I would like to specify BCs of the void by using accumulation of diffusive flux, how should I do that? My concentration at the boundaries change with time and is expressed like follows
C(t) (at t=tend) = constant*(diffusive flux at t=t0+diffusive flux at t=t1 +...diffusive flux at t= tend)
Questions are how can I calculate summation of diffusive flux from old time? Do I need external function from MATLAB to calculate diffusive flux using For loop? If yes, how to do that?
Sincerely,
Please login with a confirmed email address before reporting spam
Hi Lars
while using Anfisedit
after loading Training data and chek data
while I was using ANFISEDIT in matlab and loading file from Generate fis. I received a message wrong size of arguments defining system inputs can you explain to me what I did wrong
Please login with a confirmed email address before reporting spam
Comsol always calls your function with vector arguments (length is usually 1000 to 5000 elements). Your function must return a vector of the same size.
Try to call your function from the command line in Matlab in order to test the behaviour.
--
Lars Gregersen
Comsol Denmark
Please login with a confirmed email address before reporting spam
first, thank you for your nice explanations.
I have a slightly different problem, where I, at the end, want to integrate some variable (using mphint2 in Matlab) on the simulation volume, but in each point weighted with a factor that is given by a coordinate-dependent Matlab function.
For that I wanted to define a Matlab function in Comsol as described above and then simply call it within the expression that I want to evaluate.
As a first step I ran the example model that Lars showed here, which worked fine for me, but then I added an own Matlab function defined similar to ones that are already used in the model.
I was able to use this function within Comsol and to plot its shape (so apparently it is properly loaded and recognized by Comsol and Matlab). The problem appeared, when I then tried to evaluate this function on data stored in dataset 'dset1' so the actual simulation result.
For example:
If I would create a function that for simplicity would do nothing, but return the x coordinate, so f(x)=x.
I define it in Matlab and import it in Comsol, as already described and it seems to work.
I then add this function as a factor in the expression for the conductivity plot (which is of course nothing physical relevant).
I then would get the following error message:
Evaluation of result expression failed.
Unknown function or operator.
- Name: myfunctionname
- Plot: surf1 (Surface)
So, do you have a clue what I do wrong or any hint that I could try?
Thanks already in advance for your help.
Best,
Hannes
Please login with a confirmed email address before reporting spam
sorry for wasting your time. I got my mistake.
One can apparently just apply a function to a dataset, if the function was defined before running the respective solver.
Cheers,
Hannes
Please login with a confirmed email address before reporting spam
That's fine.
You don't have to resolve the model if you create or change a function, parameter or variable that only affects a result. You can simply right click on Study and select "Update Solution".
Regards
Lars Gregersen
Comsol Denmark
Please login with a confirmed email address before reporting spam
thank you for your advice.
By the way, I have two further questions regarding MATLAB functions:
First:
Do you know, whether it is possible to have a function that connects to a COMSOL server that then may evaluate an expression of a another model?
And second:
Is it somehow possible to pass a string type Comsol variable to a Matlab function? If I try that I always get an error message saying:
Evaluation of result expression failed
Strings are only allowed in function arguments.
Thanks already in advance.
Best,
Hannes
Please login with a confirmed email address before reporting spam
I'm not sure that I fully understand your questions.
Could you please send your questions to support@comsol.com and perhaps attach some examples. You may refer to me when submitting your support case.
--
Lars Gregersen
Comsol Denmark
Please login with a confirmed email address before reporting spam
Note that while COMSOL employees may participate in the discussion forum, COMSOL® software users who are on-subscription should submit their questions via the Support Center for a more comprehensive response from the Technical Support team.