# Output response for state-space with piecewise nonlinear elements

In addition to the previous topic:

System model merge with multiple input and one output

For example, I am trying to reproduce a system from simulink, a diagram of which is shown in the figure below: With system output: As usual, I use the "SystemModelMerge" command, but this time I encountered the difficulty of including a piecewise-nonlinear element in the system - a relay with a hysteresis, the logic of which is shown in the figure: I reproduce the same logical operation and other elements in Mathematica,

pars = {m = -1, h = 0.1}
sum = NonlinearStateSpaceModel[{{}, u1 - u2}, {}, {u1, u2}];
integrator = TransferFunctionModel[1/(s), s];
differentiator = TransferFunctionModel[s, s];
relay = NonlinearStateSpaceModel[{{},
If[e > -m*h && e < h && de > 0, 1,
If[e > -h && e < m*h && de < 0, 0,
If[Abs[e] >= h, 1*Sign[e],
If[e >= m*h && de < 0, 1,
If[e <= -m*h && de > 0, 1, 0]]]]]}, {}, {e, de}];
nsys = SystemsModelMerge[
SystemsConnectionsModel[{sum, differentiator, relay,
integrator}, {{1, 1} -> {2, 1}, {1, 1} -> {3, 1}, {2, 1} -> {3,
2}, {3, 1} -> {4, 1}, {4, 1} -> {1, 2}}, {{1, 1}}, {{1, 1}}]]


but I get the following error.

NonlinearStateSpaceModel::ssmconv: Conversion of StateSpaceModel[{{{1,0},{0,1}},{{0},{1}},{{-1,0}},{{0}},{{0,1},{0,0}}}] failed.


Although, the inputs seem to be indicated correctly (I could be wrong).

Next, I need to get the same output as in simulink. P.S. Is there any other way to create such systems, because this operation is not for inattentive people like me.

## 1 Answer

NonlinearStateSpaceModel does not support descriptor systems yet, and that is the conversion error you are seeing.

If we write out the equations of the block diagram, we can then use NDSolve to simulate it. (I noticed some discrepancies between the expressions you have in Matlab and Mathematica. I think I have fixed these below, as I can get the results to agree.)

{e[t] == 1 - f[t], de[t] == e'[t], f'[t] == With[{m = -1, h = 0.1},
Which[e > -m*h && e < h && de > 0, 0, e > -h && e < m*h && de < 0,
0, Abs[e] >= h, 1*Sign[e], e >= m*h && de < 0, 1,
e <= -m*h && de > 0, -1, True, -1] /. {e -> e[t], de -> de[t]}]};
NDSolve[Join[%, {e == 0.25}], {e[t], f[t], de[t]}, {t, 0, 5},
Method -> {"IndexReduction" -> Automatic}];
Plot[e[t] /. %, {t, 0, 2}] • Thank you, Suba Thomas. – dtn Jan 9 '20 at 8:27