Re: [functional approach should give] an even faster way
- To: mathgroup at smc.vnet.net
- Subject: [mg85682] Re: [mg85648] [functional approach should give] an even faster way
- From: Carl Woll <carlw at wolfram.com>
- Date: Tue, 19 Feb 2008 01:57:03 -0500 (EST)
- References: <200802171220.HAA01093@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.}
> ]
> ]
> ];
>
>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?
>
>Thanks in advance.
>
>Regards..Roger W.
>
>
Here is one possibilitiy:
normalize[matrix_] := matrix N@UnitStep@Total[Clip[matrix, {0, 1}, {-10,
-10}], {3}]
Timings:
matrix = RandomReal[{-.1,1.1}, {512,512,3}];
r1 = Map[If[#[[1]] < 0 || #[[1]] > 1 || #[[2]] < 0 || #[[2]] > 1 ||
#[[3]] < 0 || #[[3]] > 1, {0., 0., 0.}, #] &,
matrix, {2}]; // Timing
r2 = normalize[matrix]; // Timing
r1 == r2
{0.703,Null}
{0.078,Null}
True
Almost an order of magnitude faster.
Carl Woll
Wolfram Research
- References:
- [functional approach should give] an even faster way to normalize a
- From: congruentialuminaire@yahoo.com
- [functional approach should give] an even faster way to normalize a