Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2008

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

Search the Archive

Re: [functional approach should give] an even faster way to normalize

  • To: mathgroup at smc.vnet.net
  • Subject: [mg85681] Re: [functional approach should give] an even faster way to normalize
  • From: Szabolcs Horvát <szhorvat at gmail.com>
  • Date: Tue, 19 Feb 2008 01:56:32 -0500 (EST)
  • Organization: University of Bergen
  • References: <fp9945$199$1@smc.vnet.net>

congruentialuminaire at yahoo.com wrote:
> Hello UG:
> 
> I have a 512x512 array of 3-tuples. I want to make any tuple with a
> value outside of 0 <--> 1, become {0.,0.,0.}.
> 
> The first version has this loop:
> 
> For[i = 1, i <= graphSize, i++,
>   For[j = 1, j <= graphSize, j++,
>    If[((sum[[i, j, 1]] < 0) || (sum[[i, j, 1]] > 1) ||
>       (sum[[i, j, 2]] < 0) || (sum[[i, j, 2]] > 1) ||
>       (sum[[i, j, 3]] < 0) || (sum[[i, j, 3]] > 1)),
>     sum[[i, j]] = {0., 0., 0.}
>     ]
>    ]
>   ];

Please don't use For[] for iteration.  It is so ugly and unreadable. :-( 
Use Do[] instead, which does exactly the same thing, and doesn't even 
need to be nested.

> 
> After scratching my head for a while I came up with this (equivalent)
> Map statement.
> 
> sum = Map[
>    If[#[[1]] < 0 || #[[1]] > 1 || #[[2]] < 0 || #[[2]] > 1 || #[[3]] <
>         0 || #[[3]] > 1, {0., 0., 0.}, #] &, sum, {2}];
> 
> It is faster but only by about 15%.
> 
> It is unreasonable to believe some other construction can accomplish
> this with a bigger payoff?

Try this:

Clip[data, {0, 1}] /. 1 -> 0; // Timing

(Note the space between /. and 1 !!)

On my computer (which has a Pentium-M processor) the For[] version takes 
3.8 s, the Map[] version ~0.9 s, and the Clip[] version ~0.5 s.  But 
please understand that *any* timing less than a few seconds is 
completely unreliable (especially with Mathematica's Timing[] on a 
Windows platform).  So all that these results tell us is that the Map[] 
version is surely  a few times faster than For[].  But please don't make 
quantitative conclusions about the performance of the Clip[] version vs 
the Map[] version.

Instead, measure the real application which uses this code fragment and 
is too slow for you needs.  Or just repeat it with Do[command, 
{bigNumber}] if you're really curious.

Szabolcs


  • Prev by Date: NDSolve[] and Differential Equations: Problem solving two similar
  • Next by Date: RE: StyleSheets How-to
  • Previous by thread: Re: [functional approach should give] an even faster way to normalize
  • Next by thread: .NET/Link: Explicitly define data type to be sent to .NET object?