MathGroup Archive 2006

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: For Loop problem


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)?
> 
> Thanks, Rob

Assuming that your data are all integers between -2047 and 6144, you 
could use Mod. Here is some data:

In[11]:=
data=Table[Random[Integer,{-2047,6144}],{10}]

Out[11]=
{5745,-1569,4196,3299,5796,1621,596,-1299,1074,3547}

Your method (modified with <= instead of < so that the last entry is 
processed):

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

Out[14]=
{3697,479,2148,1251,3748,3669,2644,749,3122,1499}

Using Mod:

In[15]:=
Mod[2048+data,4096,1]

Out[15]=
{3697,479,2148,1251,3748,3669,2644,749,3122,1499}

If you want 2048->0 instead of 2048->4096, use

Mod[2048+data,4096]

Carl Woll
Wolfram Research


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