Re: For Loop problem

• To: mathgroup at smc.vnet.net
• Subject: [mg65623] Re: For Loop problem
• Date: Tue, 11 Apr 2006 04:04:40 -0400 (EDT)
• Sender: owner-wri-mathgroup at wolfram.com

```On 4/10/06 at 2:31 AM, rob at piovere.com (Rob) wrote:

>I've got to manipulate some signed 12bit integer numbers from a file
>and apparently Mathematica only handles 8 and 16 bit signed numbers
>(probably for a very good reason). So I bring them in as 16 bits
>(and they're stored that way with a leading zero nibble) and then I
>have to do the following to make sense of them.  I really don't know
>why this code works but it does.

>For[i = 1, i < Length[y], i++, If[y[[i]] > 2048, y[[i]] =
>y[[i]] - 2048, y[[i]] = y[[i]] + 2048]];

>So to my question: once again I had to resort to a For loop to pull
>this off and I know this is a no-no.  But I'm so clueless about
>Mathematica that I've never come up with a more sophisticated method
>after a year or so of thinking about it. Can someone help (as they
>usually can)?

If a For loop does what you need, then don't worry about it being a "no-no". The only real issue with For loops is they are usually slower than other ways of achieving the same result.

A simple way to replace the For loop in this case would be:

y = If[#>2048, #-2048, #+2048]&/@y;

Here, I've defined a pure function (If[#>2048, #-2048, #+2048]&) that will either add or subtract 2048 from its argument depending on whether the argument is greater or less than 2048 then used Map to apply that function to each element of y.
--
To reply via email subtract one hundred and four

```

• Prev by Date: Re: Joint Entropy
• Next by Date: Re: To apply a function to a List
• Previous by thread: Re: For Loop problem
• Next by thread: Integral problem