In the following application

f = MapThread[If [#2 == 0, 0, #1/#2] &, {d, c}] // N;

I need to overlay another mapping operation so that d and c can be taken from two other lists of which d and c are just two corresponding sublists. I tried

F=Map[MapThread[If [#2 == 0, 0, #1/#2] &, {#3, #4}]&,{D,C}]

Help would be much appreciated.

  • $\begingroup$ Does this g[d_,c_]:=MapThread[If[#2==0,0,#1/#2]&,{d,c}]; f=MapThread[g,{dd,cc}] do what you want? That keeps one set of MapThread and #1,#2,& separated from the other. $\endgroup$
    – Bill
    Commented Jun 13, 2020 at 5:35
  • $\begingroup$ How would I link d to dd where d is a sublist of dd, and similarly for cc and c? $\endgroup$
    – Z Ming Ma
    Commented Jun 13, 2020 at 6:29
  • $\begingroup$ The f MapThread is going to take two lists of lists. f will take one list from dd and one from cc. It will send those two lists to g. g will take one item from each of the two lists and calculate your result. Try g[d_,c_]:=MapThread[If[#2==0,0,#1/#2]&,{d,c}]; f=MapThread[g,{{{m,n},{o,p}},{{q,r},{s,t}}}] to see if the result is correct. If not then please provide an example input and what output should be. (D and C are functions defined by Mathematica and using those for variable names will cause problems) My method is only to put an inner Map or MapThread into a separate function. $\endgroup$
    – Bill
    Commented Jun 13, 2020 at 6:48
  • $\begingroup$ If ds come from D and cs come from C shouldn't your Map be another MapThread? $\endgroup$
    – swish
    Commented Jun 13, 2020 at 7:50
  • $\begingroup$ If I understand your question correctly, shouldn't F=MapThread[MapThread[If[#2==0,0,#/#2]&,{##}]&,{cc,dd}] or F=MapThread[MapThread[If[#2==0,0,#/#2]&]@*List,{cc,dd}] do the trick? $\endgroup$
    – Lukas Lang
    Commented Jun 13, 2020 at 8:16

1 Answer 1


If your sublists are all the same length you can use the third parameter of MapThread:

dd = {{d11, d12, d13}, {d21, d22, d23}};
cc = {{c11, c12, c13}, {c21, c22, c23}};

MapThread[f, {dd, cc}, 2]
{{f[d11, c11], f[d12, c12], f[d13, c13]}, {f[d21, c21], f[d22, c22], f[d23, c23]}}

If they are not you can use a second MapThread:

dd = {{d11, d12, d13}, {d21, d22}};
cc = {{c11, c12, c13}, {c21, c22}};

MapThread[MapThread[f, {#, #2}] &, {dd, cc}]
{{f[d11, c11], f[d12, c12], f[d13, c13]}, {f[d21, c21], f[d22, c22]}}

Or my raggedMapThread from MapThread over sublists of different length

raggedMapThread[f, {dd, cc}, 2]
{{f[d11, c11], f[d12, c12], f[d13, c13]}, {f[d21, c21], f[d22, c22]}}

Or kglr's raggedThread (reproduced here in full since it's short)

raggedThread = Inner[Thread@*#, ##2, List] &;

raggedThread[f, dd, cc]
{{f[d11, c11], f[d12, c12], f[d13, c13]}, {f[d21, c21], f[d22, c22]}}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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