Function Input/Output Considerations
The functions called from COMSOL Multiphysics must support vector arguments of any length. COMSOL calls a MATLAB® function using vector arguments to reduce the number of expensive calls from COMSOL to MATLAB. All common MATLAB functions such as sin, abs, and other mathematical functions support vector arguments.
Consider the following example function where the coefficient c depends on the x coordinate:
function c = func1(x)
if x > 0.6
  c = x/1.6;
else
  c = x^2+0.3;
end
This function looks good at first but it does not work in COMSOL Multiphysics because the input x is a vector:
Element-by-element multiplication, division, and power must be used—that is, the operators .*, ./, and .^. Replace expressions such as x/1.6 and x^2+0.3 with x./1.6 and x.^2+0.3, respectively.
The comparison x > 0.6 returns a matrix with ones (true) for the entries where the expression holds true and zeros (false) where it is false. The function evaluates the conditional statement if, and only if, all the entries are true (1).
You can replace the if statement with a single assignment to the indices retrieved from the x > 0.6 operation and another assignment to the indices where x 0.6. The function could then look like this:
function c = func2(x)
c = (x./1.6).*(x>0.6) + (x.^2+0.3).*(x<=0.6);