Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.soft-sys.math.mathematica > #8137

Re: Compile function and AppendTo for lists (vrs. 8.0.4)

From DrMajorBob <btreat1@austin.rr.com>
Newsgroups comp.soft-sys.math.mathematica
Subject Re: Compile function and AppendTo for lists (vrs. 8.0.4)
Date 2012-01-25 12:02 +0000
Organization Steven M. Christensen and Associates, Inc and MathTensor, Inc.
Message-ID <jfor10$5p6$1@smc.vnet.net> (permalink)
References <201201241006.FAA20254@smc.vnet.net>

Show all headers | View raw


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@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@yahoo.com

Back to comp.soft-sys.math.mathematica | Previous | Next | Find similar | Unroll thread


Thread

Re: Compile function and AppendTo for lists (vrs. 8.0.4) DrMajorBob <btreat1@austin.rr.com> - 2012-01-25 12:02 +0000

csiph-web