Another approach that is supported by the previous versions (11.3
at least) is to create a list of functions which are either (Identity
which doesn't touch the data or fn
which apply your function) and then MapThread
this list with Construct
:
Block[{temp},
(* create a list of Identity function *)
temp = ConstantArray[Identity, Length[L]];
(* replace the positions with your function *)
temp[[B]] = #^2 &;
(* apply your list of function to your data (element-wise) *)
t2result = MapThread[Construct, {temp, L}];
] // MaxMemoryUsed // AbsoluteTiming
(* Out: {0.0161858, 800568} *)
Result:
t2result == SubsetMap[#^2 &, L, {#} & /@ B]
(* Out: True *)
Another benefit is the memory footprint (could vary):
MapAt[#^2 &, L, {#} & /@ B]; // MaxMemoryUsed // AbsoluteTiming
(* Out: {1.2336, 1912832} *)
(* @Syed answer *)
SubsetMap[#^2 &, L, {#} & /@ B]; // MaxMemoryUsed // AbsoluteTiming
(* Out: {0.0305638, 6541432} *)
which is around 2
and 8
times smaller respectively.
Notes:
- Minimum version
11.3
is because ofConstruct
, if you happen to have an alternative, the minimum requirement would be lowered (although performance would be affected). - This method could easily be extended to apply multiple functions.