Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2008

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

Search the Archive

Re: ConstantArray and List

  • To: mathgroup at smc.vnet.net
  • Subject: [mg88184] Re: [mg88156] ConstantArray and List
  • From: Carl Woll <carlw at wolfram.com>
  • Date: Sun, 27 Apr 2008 05:00:19 -0400 (EDT)
  • References: <200804260746.DAA08772@smc.vnet.net>

Szabolcs Horvát wrote:

>Consider the following inputs:
>
>In[1]:= ConstantArray[f[], {5}]
>
>Out[1]= {f[], f[], f[], f[], f[]}
>
>In[2]:= ConstantArray[List[], {5}]
>
>During evaluation of In[2]:= ConstantArray::scalar: Argument {} at \
>position 1 is not a scalar. >>
>
>Out[2]= ConstantArray[{}, {5}]
>
>
>Why doesn't the second one work?  Is this because of the way packed 
>arrays are handled (just a guess)?
>
>
>What is the advantage of ConstantArray over Table or Array?  It doesn't 
>seem to be much faster, and it doesn't seem to return an array stored in 
>a more efficient way (I experimented a little with MemoryInUse[]).
>  
>
Try comparing ConstantArray and Table for the creation of very large 
packed arrays:

In[41]:= ConstantArray[0, 10^7]; // Timing
Table[0, {10^7}]; // Timing

Out[41]= {0.031,Null}

Out[42]= {0.531,Null}

In[43]:= ConstantArray[1., {10^4, 10^3}]; // Timing
Table[1., {10^4}, {10^3}]; // Timing

Out[43]= {0.062,Null}

Out[44]= {0.531,Null}

So, ConstantArray is useful when you want to create a large constant 
packed array, which you then modify in some way. This approach is very 
common in Compile code.

Another example is:

In[51]:= r1 = Table[ConstantArray[i, 10^6], {i, 10}]; // Timing
r2 = Table[i, {i, 10}, {10^6}]; // Timing
r1 === r2

Out[51]= {1.84075*10^-13,Null}

Out[52]= {1.844,Null}

Out[53]= True

although here, I should mention that neither r1 nor r2 are packed.

Carl Woll
Wolfram Research


  • Prev by Date: Re: Enable multicore calculation ?
  • Next by Date: Re: ConstantArray and List
  • Previous by thread: ConstantArray and List
  • Next by thread: Re: ConstantArray and List