2
$\begingroup$

I am trying to solve a difference equation using RecurrenceTable as follows.

xhat0 = {0.00000001, 256};
boxedx[x_] := Piecewise[{{-2, x < -2}, {2, 2 < x}}, x]
SetAttributes[boxedx, Listable];
test = RecurrenceTable[{xhat[n] == boxedx[xhat[n - 1]],xhat[0] == xhat0}, {xhat}, {n, 1, 4}]

If I remove the boxedx function acting on the right hand side, or replace it by a built-in function such as Sqrt, the code works. I tried the definition

boxedx[x_List] := Map[Piecewise[{{-2, # < -2}, {2, 2 < #}}, #] &, x]

which also resulted in a numerical exception. And if I write the equality as

xhat[n] == xhat[n - 1] + {1, 1}

a numerical exception happens again. I would appreciate any help!

$\endgroup$
2
  • 1
    $\begingroup$ Does it work if you use Clip[x, {-2, 2}] instead of boxedx? $\endgroup$
    – bill s
    Commented Feb 12, 2018 at 17:06
  • $\begingroup$ It does, I hadn't thought of it! I still don't understand why - and Attributes of Clip don't include listable - but your suggestions solves my problem. Thanks! $\endgroup$
    – Pait
    Commented Feb 12, 2018 at 17:54

1 Answer 1

2
$\begingroup$

You can use Clip -- it acts on the elements of a list

Clip[Range[-5, 5], {-2, 2}]
{-2, -2, -2, -2, -1, 0, 1, 2, 2, 2, 2}
$\endgroup$
3
  • $\begingroup$ Thank you very much! Do you have any idea of why defining a function doesn't work? I'm pretty sure I'll need something more complex sooner or later, so any pointer would be helpful. $\endgroup$
    – Pait
    Commented Feb 13, 2018 at 1:06
  • 1
    $\begingroup$ Sorry -- I'm not sure why -- I didn't really understand what you are trying to do in the RecurrenceTable. $\endgroup$
    – bill s
    Commented Feb 13, 2018 at 4:45
  • $\begingroup$ It was a simplified version of my problem, I removed complications in the RecurrenceTable to identify the source of the error messages. Your suggestion of using Clip solved my problem, though I still don't understand what was causing the errors. Thanks! $\endgroup$
    – Pait
    Commented Feb 14, 2018 at 16:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.