1

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.

C. E.
  • 70,533
  • 6
  • 140
  • 264
Z Ming Ma
  • 497
  • 2
  • 9
  • 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. – Bill Jun 13 '20 at 05:35
  • How would I link d to dd where d is a sublist of dd, and similarly for cc and c? – Z Ming Ma Jun 13 '20 at 06:29
  • 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. – Bill Jun 13 '20 at 06:48
  • If ds come from D and cs come from C shouldn't your Map be another MapThread? – swish Jun 13 '20 at 07:50
  • 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? – Lukas Lang Jun 13 '20 at 08:16
  • Thanks to both Lukas and Bill a great deal. It appears that both will work. I implemented with Lukas' suggestion simply because the first option appears more intuitive to me. Thanks again. – Z Ming Ma Jun 13 '20 at 15:48

1 Answers1

2

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]}}
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371