6
$\begingroup$

A simple question. Here Clip works as documented:

Clip[0.5, {0, 0}, {0,1}]

(* 1 *)

Values larger than 0 are replaced with the integer 1. However, for a list we do not get integers:

lst=RandomReal[{-1, 1}, {10}];
Clip[lst, {0,0}, {0,1}]

(* {0.,0.,0.,0.,0.,1.,1.,0.,0.,1.} *)

whereas

Clip[#, {0,0},{0,1}]& /@ lst

(* {0,0,0,0,0,1,1,0,0,1} *)

I am wondering if this is intended behaviour. As far as I can see, it is not documented. I have not observed this behaviour before. It happens in 10.4 as well, but I do not have older versions to compare.

$\endgroup$
6
  • 5
    $\begingroup$ That is intended behavior. When operating on a packed array, Clip returns a packed array of the same type. $\endgroup$
    – ilian
    Commented Jun 17, 2017 at 21:55
  • $\begingroup$ @ilian. Interesting, thanks. So it is not a bug. I think your comment should be included in the documentation. $\endgroup$ Commented Jun 18, 2017 at 6:38
  • $\begingroup$ @ilian But Clip[RandomInteger[2, 10], {0., 0.}, {0., 1.}] returns a packed array of reals. $\endgroup$ Commented Jun 19, 2017 at 16:44
  • 4
    $\begingroup$ @AlexeyPopkov Yes, my previous comment was not precise enough. It also matters whether the ranges can be packed and into what type. For example, Clip[RandomInteger[2, 10], {0., 0.}, {0., 1}] and Clip[RandomReal[2, 10], {0., 0.}, {0., Infinity}] do not return a packed result. $\endgroup$
    – ilian
    Commented Jun 19, 2017 at 17:05
  • $\begingroup$ @ilian If you'll post a proper answer I'll delete mine. $\endgroup$ Commented Jun 19, 2017 at 17:12

1 Answer 1

2
$\begingroup$

Posting ilian's comment as an answer,

That is intended behavior. When operating on a packed array, Clip returns a packed array of the same type.

Checking:

lst = RandomReal[{-1, 1}, {10}];

lst2 = RandomInteger[2, 20];

Clip[lst, {0, 0}, {0, 1}]

Clip[lst2, {0, 0}, {0, 1}]

Clip[Developer`FromPackedArray@lst, {0, 0}, {0, 1}]    
{1., 0., 0., 1., 1., 1., 0., 1., 1., 0.}

{1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1}

{1, 0, 0, 1, 1, 1, 0, 1, 1, 0}

But Clip[RandomInteger[2, 10], {0., 0.}, {0., 1.}] returns a packed array of reals:

Clip[lst2, {0., 0.}, {0., 1.}]
% // Developer`PackedArrayQ    
{1., 0., 0., 0., 1., 0., 1., 1., 0., 1., 1., 0., 0., 1., 0., 1., 1., 0., 0., 1.}

True

ilian's responce:

Yes, my previous comment was not precise enough. It also matters whether the ranges can be packed and into what type. For example, Clip[RandomInteger[2, 10], {0., 0.}, {0., 1}] and Clip[RandomReal[2, 10], {0., 0.}, {0., Infinity}] do not return a packed result.

$\endgroup$

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.