Search code examples
stringmatlablinear-algebrasymbolic-mathmupad

Algorithm to determine if a symbolic expression is a linear function


Is there an easy way to check if a vector valued symbolic function is linear? If so, is there an easy way to represent this expression in the form A*x, where A is a symbolic matrix and x is the argument (i.e. is there a way to "extract" A given x and A*x)?

syms x1 x2 a b c;
fx1 = [a*(x1+x2); b*x1+c*x1];
fx2 = [a*x1/log(x2); x2^2];
A=checklinearity(fx1, [x1 x2]') % should return [a, a; b+c, 0]
A=checklinearity(fx2, [x1 x2]') % should return false

Answer: There is an easy way to solve the problem using a built-in MATLAB function equationsToMatrix.


Solution

  • I decided to post and accept my own answer.

    Generally, there are several approaches that lead to the correct solution:

    1). The easiest solution is to use the built-in MATLAB function equationsToMatrix(). The function tests for linearity and if the expression is nonlinear, then the function throws an exception with identifier symbolic:sym:equationsToMatrix:NonlinearSystem. If the system is linear, then the function returns the matrix of interest.

    2). Solution proposed by patrik was to use the definition of the linearity: f(ax)-a*f(x). This only tests for linearity, but once it is confirmed that the system is linear it is not difficult to infer the matrix.

    3). Solution proposed by horchler was to use polynomial algebra.