2
$\begingroup$

What I need is the equivalent of Maple's zip(+, A, B, 0). Sure I can get it with:

Thread[PadRight[A, max = Max[Length[A], Length[B]]] + PadRight[B, max]]

But is there a less verbose way to do this?

P.S. Eventually the shortest solution seems to be:

 Plus @@ PadRight[{A, B}]
$\endgroup$
  • 1
    $\begingroup$ Possible duplicate: mathematica.stackexchange.com/q/22437/121 $\endgroup$ – Mr.Wizard Jan 29 '14 at 16:51
  • $\begingroup$ In your code Thread is useless (because Plus is Listable) and PadRight[A, max = Max[Length[A], Length[B]]] + PadRight[B, max] can be rewritten as Plus @@ PadRight[{A,B}] $\endgroup$ – andre314 Jan 29 '14 at 19:30
  • 2
    $\begingroup$ 'Plus' was used as an example $\endgroup$ – user6109 Jan 29 '14 at 21:18
7
$\begingroup$
a = {1, 2, 3};
b = {q, r, s, t, u};
Plus @@@ Flatten[{a, b}, {2}]
{1 + q, 2 + r, 3 + s, t, u}

See: Flatten command: matrix as second argument

For convenience:

SetAttributes[myThread, HoldFirst]
myThread[h_[args__]] := h @@@ Flatten[{args}, {2}]

Now:

myThread[a + b]
{1 + q, 2 + r, 3 + s, t, u}

This utility may also be useful.


The reason I showed use of Flatten rather than PadRight is that it is more general. With PadRight your function will see zeros:

Times @@ PadRight[{a, b}]
{q, 2 r, 3 s, 0, 0}

Compare to:

myThread[a*b]
{q, 2 r, 3 s, t, u}

Of course for Times you could pad with ones, but the point is that the padding element would have to be changed to match the function, and for some functions no padding element would be correct.

$\endgroup$
  • $\begingroup$ Transposing ragged arrays with Flatten[array,{2}] is one of my favorite tricks. $\endgroup$ – kale Jan 30 '14 at 0:38
-1
$\begingroup$

Another possibility, which I cannot judge as equivalent to Maple's zip, is to use Distribute:

a = {1, 2, 3};
b = {q, r, s, t, u};

Distribute[f[a, b], List]

{f(1,q),f(1,r),f(1,s),f(1,t),f(1,u),f(2,q),f(2,r),f(2,s),f(2,t),f(2,u),f(3,q),f(3,r),f(3,s),f(3,t),f(3,u)}

If f is List, the result is:

Distribute[{a, b}, List]

{{1, q}, {1, r}, {1, s}, {1, t}, {1, u}, {2, q}, {2, r}, {2, s}, {2, t}, {2, u}, {3, q}, {3, r}, {3, s}, {3, t}, {3, u}}

$\endgroup$
  • 2
    $\begingroup$ I don't believe this answers the question. The result should be {1 + q, 2 + r, 3 + s, t, u} $\endgroup$ – Simon Woods Jan 29 '14 at 21:21
  • $\begingroup$ @SimonWoods Yes you are right: now I understood better the question. Thanks $\endgroup$ – user8074 Jan 29 '14 at 21:54
  • $\begingroup$ Delete then perhaps? $\endgroup$ – Mr.Wizard Jan 30 '14 at 0:32

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.