Tips & Tricks
Follow


Zhaoxu Liu / slandarer

Solve Syms Equations With Piecewise

Zhaoxu Liu / slandarer on 5 Feb 2024

There will be a warning when we try to solve equations with piecewise:
syms x y
a = x+y;
b = 1.*(x > 0) + 2.*(x <= 0);
eqns = [a + b*x == 1, a - b == 2];
S = solve(eqns, [x y]);
% 错误使用 mupadengine/feval_internal
% System contains an equation of an unknown type.
%
% 出错 sym/solve (第 293 行)
% sol = eng.feval_internal('solve', eqns, vars, solveOptions);
%
% 出错 demo3 (第 5 行)
% S=solve(eqns,[x y]);
But I found that the solve function can include functions such as heaviside to indicate positive and negative:
syms x y
a = x+y;
b = floor(heaviside(x)) - 2*abs(2*heaviside(x) - 1) + 2*floor(-heaviside(x)) + 4;
eqns = [a + b*x == 1, a - b == 2];
S = solve(eqns, [x y])
% S =
% 包含以下字段的 struct:
%
% x: -3/2
% y: 11/2
The piecewise function is divided into two sections, which is so complex, so this work must be encapsulated as a function to complete:
function pwFunc=piecewiseSym(x,waypoint,func,pfunc)
% @author : slandarer
gSign=[1,heaviside(x-waypoint)*2-1];
lSign=[heaviside(waypoint-x)*2-1,1];
inSign=floor((gSign+lSign)/2);
onSign=1-abs(gSign(2:end));
inFunc=inSign.*func;
onFunc=onSign.*pfunc;
pwFunc=simplify(sum(inFunc)+sum(onFunc));
end
Function Introduction
  • x : Argument
  • waypoint : Segmentation point of piecewise function
  • func : Functions on each segment
  • pfunc : The value at the segmentation point
example
syms x
% x waypoint func pfunc
f=piecewiseSym(x,[-1,1],[-x-1,-x^2+1,(x-1)^3],[-x-1,(x-1)^3]);
For example, find the analytical solution of the intersection point between the piecewise function and f=0.4 and plot it:
syms x
% x waypoint func pfunc
f=piecewiseSym(x,[-1,1],[-x-1,-x^2+1,(x-1)^3],[-x-1,(x-1)^3]);
% solve
S=solve(f==.4,x)
% S =
%
% -7/5
% (2^(1/3)*5^(2/3))/5 + 1
% -15^(1/2)/5
% 15^(1/2)/5
% draw
xx=linspace(-2,2,500);
f=matlabFunction(f);
yy=f(xx);
plot(xx,yy,'LineWidth',2);
hold on
scatter(double(S),.4.*ones(length(S),1),50,'filled')
precedent
syms x y
a=x+y;
b=piecewiseSym(x,0,[2,1],2);
eqns = [a + b*x == 1, a - b == 2];
S=solve(eqns,[x y])
% S =
% 包含以下字段的 struct:
%
% x: -3/2
% y: 11/2