[Date Index]
[Thread Index]
[Author Index]
Re: Compile function and AppendTo for lists (vrs. 8.0.4)
*To*: mathgroup at smc.vnet.net
*Subject*: [mg124563] Re: Compile function and AppendTo for lists (vrs. 8.0.4)
*From*: DrMajorBob <btreat1 at austin.rr.com>
*Date*: Wed, 25 Jan 2012 07:01:06 -0500 (EST)
*Delivered-to*: l-mathgroup@mail-archive0.wolfram.com
*References*: <201201241006.FAA20254@smc.vnet.net>
*Reply-to*: drmajorbob at yahoo.com
We'd have to see the REAL problem to give better advice, but AppendTo is
generally slow, as you can see from the following, where the compiled code
takes almost 26,000 times as long:
n = 10^5;
mat = {};
test = Compile[{{k, _Integer}},
For[i = 1, i <= k, i++, AppendTo[mat, {1, i}];];];
Timing[test[n]]
{181.242, Null}
test2[k_] := Table[{1, i}, {i, 1, k}]
Timing[mat2 = test2[n];]
{0.007079, Null}
mat == mat2
True
Here's another code that's MUCH faster than your original, although still
slower than Table:
n = 10^5;
mat3 = {};
test = Compile[{{k, _Integer}},
For[i = 1, i <= k, i++, mat3 = {mat3, {1, i}};];];
Timing[test[n];
mat3 = Partition[Flatten@mat3, 2];]
mat3 == mat2
{1.42912, Null}
True
Compile is not always the answer to our speed problems.
Bobby
On Tue, 24 Jan 2012 04:06:23 -0600, kris <kristophs.post at web.de> wrote:
> Hi
>
> I have some trouble with my code and would like ask for your help. In
> general it is about appending data in form of a list to an existing
> list in a compiled function. As far as I understand Mathematica is not
> supporting what I am asking for. In order to understand the problem in
> more detail I present some "toy" code below.
>
> test=Compile[{{k,_Integer}},
> Module[{mat={}},
> For[i=1,i<=k,i++,
> AppendTo[mat,{1,i}];
> ];
> mat
> ]
> ];
>
> test[2]
> (*which produces an error*)
>
> Appending data in form of numbers for example works just fine but not
> with lists. Can anybody explain why Mathematica does not support
> appending lists to lists for compiled function? As an alternative I
> tried Reap and Sow, which also produces an error.
>
> However, what seems funny is the following code:
>
> mat={};
> test=Compile[{{k,_Integer}},
> For[i=1,i<=k,i++,
> AppendTo[mat,{1,i}];
> ];
> ];
>
> test[2];mat
>
> The above code produces the result that I was looking for in a
> cumbersome way. I would like to prefer compile code which produces the
> same result without calling the list mat again.
>
> Thanks for help I do appreciate it.
> Cheers,
> Kris
>
--
DrMajorBob at yahoo.com
Prev by Date:
**Re: Infinite Series Error - Bug?**
Next by Date:
**Re: Infinite Series Error - Bug?**
Previous by thread:
**Compile function and AppendTo for lists (vrs. 8.0.4)**
Next by thread:
**Re: Compile function and AppendTo for lists (vrs. 8.0.4)**
| |