Search code examples
matlabsymbolic-mathmupad

How to write a `lhs()` or `rhs()` function for symbolic expressions on Matlab


I have a symbolic expression in MATLAB with a == operator that I can use in solve(). What I want is to separate out the left hand side and the right hand side of the expression into two separate symbolic expressions.

For example:

expr = sym('[1-x^2==2*y; 1+x^2==x+y]');
side1 = lhs(expr);        % returns side1 = [1-x^2; 1+x^2];

of course my expressions are far more complicated, and it is always vector or matrix form.

Workaround 1 I can use the MuPAD built-in function lhs() but I wanted to know if it possible to do this using only MATLAB functions and I want to make it work for vectors of expressions and not just one value.

This is what I have so far that works as expected. Maybe the result filling can be vectorized somehow by using : but I have not manage to get it working.

function [ r ] = lhs( expr )
%LHS Returns the left hand side an expression
%   LHS(sym('[1-x^2==2*y'; 1+x^2==x+y]')) = [1-x^2; 1+x^2]

  cmd = @(e)['lhs(',char(e),')'];
  [m,n] = size(expr);
  r = sym(zeros(m,n));
  for i=1:m
      for j=1:n
          r(i,j) = evalin(symengine, cmd(expr(i,j)));
      end
  end  
end

Solution

  • Starting R2017a, use "lhs" and "rhs" as

    syms x
    expr = [1-x^2==2*y; 1+x^2==x+y];
    lhsExpr = lhs(expr)
    lhsExpr =
     1 - x^2
     x^2 + 1
    
    
    rhsExpr = rhs(expr)
    rhsExpr =
      2*y
     x + y