1
$\begingroup$

I currently use MapThread[f, {{a1, a2}, {b1, b2}] for obtaining { f[a1, b1], f[a2, b2] }.

Is there a version (or alternative) for obtaining { f[a1, b1, c], f[a2, b2, c] }?

Basically I'd like to add a fixed option c (like c1 -> c11) to each invocation of f. How can it be done?

$\endgroup$
1
  • $\begingroup$ Somewhat related: (38827) $\endgroup$
    – Mr.Wizard
    Mar 12, 2015 at 21:54

3 Answers 3

5
$\begingroup$

Since c is common to all the entries, I would do this:

MapThread[f[##, c] &, {{a1, a2}, {b1, b2}}]

(* ==> {f[a1, b1, c] , f[a2, b2, c]} *)

Here the ## stands for SlotSequence and accepts the pair of arguments fed into it by Inner, taken from the two Lists.

This is based on constructing a pure function (identified by the & at the end) that is used instead of f.

This also works in the special case that c is a rule:

MapThread[f[##, c1 -> c11] &, {{a1, a2}, {b1, b2}}]

(* ==> {f[a1, b1, c1 -> c11], f[a2, b2, c1 -> c11]} *)
$\endgroup$
3
  • $\begingroup$ This is close, but this Inner sums elements, wheras I need a list of elements. f is e.g. HighlightImage. $\endgroup$
    – Drux
    Mar 12, 2015 at 17:32
  • $\begingroup$ Oh, I wasn't looking carefully at what you wanted and over-thought the answer. Just keep using MapThread, not Inner. $\endgroup$
    – Jens
    Mar 12, 2015 at 17:35
  • $\begingroup$ Tx, now it's perfect. $\endgroup$
    – Drux
    Mar 12, 2015 at 17:41
3
$\begingroup$
Thread[f[{a1, a2}, {b1, b2}, c]]
(* {f[a1, b1, c], f[a2, b2, c]} *)

Thread[f[{a1, a2}, {b1, b2}, c1 -> c11]]
(* {f[a1, b1, c1 -> c11], f[a2, b2, c1 -> c11]} *)
$\endgroup$
5
  • $\begingroup$ (+1) for the simplest approach. $\endgroup$
    – Jens
    Mar 12, 2015 at 17:37
  • $\begingroup$ If you try this with HighlightImage as f it will complain about expecting an image instead of a list of images. $\endgroup$
    – Drux
    Mar 12, 2015 at 17:37
  • $\begingroup$ @Drux - yes, the dimensions of the lists on which you work is important for Thread. It doesn't matter in your original example. But MapThread then would offer simpler control over the level at which the threading happens. It can be done with Thread, too, though. $\endgroup$
    – Jens
    Mar 12, 2015 at 17:39
  • $\begingroup$ Thank you @Jens. Drux, try Unevaluated@HighlightImage instead of HighlightImage. $\endgroup$
    – kglr
    Mar 12, 2015 at 17:50
  • $\begingroup$ @Drux maybe try Thread[f[{a1, a2}, {b1, b2}, c1 -> c11]] /. f-> HighlightImage where f is a "dummy" symbol without any definition $\endgroup$ Mar 12, 2015 at 22:55
0
$\begingroup$
f[##, c] & @@@ (Transpose[{{a1, a2}, {b1, b2}}])
    (*{f[a1, b1, c], f[a2, b2, c]}*)
$\endgroup$

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.