Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Imagine I'm trying to add some value $r$ to each element in a very large array $L$. Take for example:

L = Table[RandomReal[{0,1}],{q,1,10^7}];
r = 0.0032;

I can effectively add $r$ to each element in $L$ by writing:

L = Table[L[[q]]+r,{q,1,Length[L]}];

This operation takes about $\approx 322$ milliseconds. However, is there a better / faster way to proceed?

share|improve this question
add comment

2 Answers 2

up vote 2 down vote accepted

Take advantage of listability -- meaning that you do not have to loop through the list, just add r to the list.

Timing[L1 = Table[L[[q]] + r, {q, 1, Length[L]}];]
(* {1.288042, Null} *)

faster listable alternative:

Timing[L2 = L + r;]
(* {0.339668, Null} *)

L1 == L2
(* True  *)

Timings on old Mac running V8.

share|improve this answer
add comment

This can speeded up even more by eliminating Table as well as using listability. Here are timings from my system.

r = 0.0032;
SeedRandom[42]; 
Timing[t1 = Table[RandomReal[{0, 1}], {q, 1, 10^7}];
  t2 = Table[t1[[q]] + r, {q, 1, Length[t1]}];]

{1.331451, Null}

SeedRandom[42];
Timing[tbl = RandomReal[1., 10^7] + r;]

{0.243818, Null}

tbl == t2

True

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.