Creating the MATLAB® Functions
Assume that the material in the example is characterized by a random thermal conductivity. To define the thermal conductivity, create a MATLAB function with the x-axis position as an input argument and let the conductivity vary randomly within 200 W/(m·K) around a constant value of 400 W/(m·K).
Define a MATLAB function for the external heat flux to be a function of the following arguments:
x and y, the location coordinates.
x0 and y0, the origin of the heat source.
Q0, the maximum heat source.
scale, a parameter that scales the period of the heat flux.
x and y are dependent variables of the model. x0, y0, Q0, and scale are defined with constant value in this exercise.
The functions must adhere to a certain structure. In order for the calls from COMSOL to MATLAB to be as efficient as possible the arguments are transferred to MATLAB in blocks. This means that all the input arguments for the functions are vectors, and that the functions need to return vectors with the same length as the input arguments. It is highly recommended to test the functions on the MATLAB command line with some reasonable vector arguments.
1
2
function out = conductivity(x)
out = 400+5*randn(size(x));
3
Save the file in the user Documents folder under MATLAB as conductivity.m. Saving the file in this location (/Documents/MATLAB) ensures that MATLAB can find the function when COMSOL calls it for evaluation.
Note: If you want to save the function in a specific directory, saving the COMSOL model at the same location as the external MATLAB functions ensures that the function path is known by MATLAB. Other alternatives include setting the function path directly in MATLAB before running the model or setting the environmental variable COMSOL_MATLAB_PATH with the directory path of the functions.
4
function out = heatflux(x,y,x0,y0,Q0,scale)
radius = sqrt((x-x0).^2+(y-y0).^2);
out = Q0/5+Q0/2.*sin(scale*pi.*radius)./(scale*pi.*radius);
5
Save the file as heatflux.m, in the same location as the previous file.