4
$\begingroup$

I have a matrix test = { {2.5,1.4,3.3},{4,4,4},{7,3.2,9}} and a function f that requires 2 arguments, the row number and the index of the element inside the row, and I want to ParallelMap the function over the matrix to speed up the computation ( the matrix can be very long, over 30k elements) .how would you achieve this result and what is the fastest method available? the result should be :

result = {{f[1,1],f[1,2],f[1,3]},{f[2,1],f[2,2],f[2,3]}, {f[3,1],f[3,2],f[3,3]}}

closest thing I have achieved is :

 ParallelMap[
 MapIndexed[f[1, #2[[1]]] &    ,   #[[2]]       ] &,           
 Transpose[{{1, 2, 3}, test}]                  ]   

but it fails when I try to change the row number from 1 to #[1]

enter image description here

$\endgroup$
  • $\begingroup$ no in this case i get { {f(1,1),f(2,2),f(3,3)},{ f(1,1),f(2,2),f(3,3)} {f(1,1),f(2,2),f(3,3)}} which is not what i need $\endgroup$ – Alucard May 20 '18 at 8:48
  • $\begingroup$ I am not sure what you want to accomplish. I guess I would do it with Compile and the options RuntimeAttributes -> Listable and Parallelization -> True. Also, many built-in functions are vectorized, so for example Sin[test] is so fast that you won't beat it by ParallelMap. $\endgroup$ – Henrik Schumacher May 20 '18 at 8:51
  • $\begingroup$ I cannot understand what you want to get, especially, the part result = ....... $\endgroup$ – Αλέξανδρος Ζεγγ May 20 '18 at 8:53
  • 1
    $\begingroup$ ParallelMap[ Module[{x = #[[1]], y = #[[2]]}, MapIndexed[f[x, #2[[1]]] &, y]] &, Transpose[{{1, 2, 3}, test}]]? $\endgroup$ – kglr May 20 '18 at 9:10
  • 1
    $\begingroup$ For tasks such as in snapshot from the book, the functions ListCorrelate and ListConvolve should we worth a look. These methods are also faster as you can ever be with Compile (believe me, I tried several times ^^); probably because they have optimised memory access at a level that is hardly achievable through the Compile keyhole. $\endgroup$ – Henrik Schumacher May 20 '18 at 9:26
3
$\begingroup$
ParallelMap[Module[{x = #[[1]], y = #[[2]]}, MapIndexed[f[x, #2[[1]]] &, y]] &, 
  Transpose[{{1, 2, 3}, test}]];
% == result

True

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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