Skip to main content
1 of 3
imida k
  • 4.4k
  • 10
  • 20

Applying f for a part of list (MapAt is slow)

Suppose that there are 2000 stones in a row.
You should grind 1000 of them to make beads.
The time loads(making beads) for each stone are similar.
But which 1000 stones?

case1) the first 1000 stones.

case2) Let B = RandomSample[Range[2000], 1000].
Then, all b-th stones, where b denotes element of B.

If this is a problem of real world, then case1) is faster then case2), because
for case2),

  1. You have to read the B every time after grinding a stone.
  2. If the next stone to be processed is far away, it will take a long time to go there.
  3. B is even not sorted by size.

But, if it was a problem of mathematica,

2000 stones in a row = a list of 2000 elements
grinding a stone = applying function to an element

The time loads for case1) and time loads for case2) should be similar in my opinion.

I experienced that "just because some elements of a list are positionally close, there is no particular advantage to processing(=applying function) them at once(or consecutively)"

Also I believe that "there is a fast mathematica code for case2) always, that takes silmilar time compared to case1)"

Am I thinking correctly?

If so, can you make a fast code for the following problem ?

For L, square(=apply #^2&) each b-th element of L.(leave other element unchanged)

L = Range[40000, 59999];
B = RandomSample[Range[20000], 10000];

My first trial was

MapAt[#^2&, L, {#}&/@B] //Timing
2.85938

which is never successful.

After some more trials, I realized that MapAt is very slow, in all case.
The performance was so bad that I felt MapAt should not be used in any case.

Can you help me?

imida k
  • 4.4k
  • 10
  • 20