[Date Index]
[Thread Index]
[Author Index]
Re: Zero-based indexing option?
*To*: mathgroup at smc.vnet.net
*Subject*: [mg61660] Re: Zero-based indexing option?
*From*: Bill Rowe <readnewsciv at earthlink.net>
*Date*: Mon, 24 Oct 2005 21:07:21 -0400 (EDT)
*Sender*: owner-wri-mathgroup at wolfram.com
On 10/24/05 at 1:44 AM, anonmous69 at netscape.net (Matt) wrote:
>I am a C/C++ developer by trade and zero-based indexing is the norm.
>When dealing with a set of objects, if I want to iterate over all
>of them for some reason or another, I'm used to doing something
>like this:
>unsigned int ii(0);
>while (ii < elementCount)
>{
> // do something
> ++ii;
>}
>where elementCount represents the number of elements in a set of
>objects. In Mathematica, I'm getting into the habit of doing
>something like this:
>iterations = Length[(* of something *)] ;
>iterations++;
>ii = 1;
>While[ii < iterations, (* do something *); ii++]
>As you can see, I need to initialize my iterator to 1 and in order
>to keep strictly 'less than' semantics, I need to increase the size
>of my object set by one. This is not a big deal, and if I have no
>other choice, I'll probably settle for setting the iterator to one
>and using 'less than or equal' semantics for the loop constraint so
>I'm not altering the size of the object set.
>However, it would be great if there were a Mathematica option or
>code driven setting that would allow me to use zero-based indexing.
> Is there such a thing?
As far as I know, there is no setting withing Mathematica to use zero based indexing. Perhaps it would be possible to code something so you could use Mathematica as if it were zero based. But this would not serve you well.
Put simply, Mathematica is not C or C++. While it is possible to write Mathematica code that closely mimics C or C++ code, the result almost always is far less than optimum code.
Consider:
In[6]:=
data = Table[Random[], {100000}];
n = 1;
sum = 0;
Timing[While[n <= 100000, sum += data[[n]]; ++n]]
sum
Out[9]= {1.953046*Second, Null}
Out[10]= 50096.368760114085
versus
In[11]:=Timing[Plus @@ data]
Out[11]= {0.129745*Second, 50096.368760114085}
or even faster
In[12]:=Timing[Total@data]
Out[12]= {0.002571*Second, 50096.368760114085}
If you use Mathematica's functional programming paradigm, the issue of zero based indexing nearly disappears. And the resulting code runs faster.
--
To reply via email subtract one hundred and four
Prev by Date:
**Re: Zero-based indexing option?**
Next by Date:
**Re: JLink discover and link to an already running kernel from a Java App**
Previous by thread:
**Re: Zero-based indexing option?**
Next by thread:
**Re: Zero-based indexing option?**
| |