4
$\begingroup$

Suppose I have the following lists:

eqexp={a,b,c,d}
eqval={e,f,g,h}
signval={{},{1},{-1},{1,-1}}

I want to create a new list of inequalities, where the signval list signals whether to use greater than or less than. I need it to handle empty sublists, and multi-component sublists. My desired output is:

{{},{b>f},{c<g},{d>h,d<h}}

All lists have the same number of top-level elements. eqexp and eqval are one-dimensional. signval is two-dimensional, but the length of the sub-lists is variable. The only numerical values allowed in signval are 1 and -1.

How do I do this?

$\endgroup$

3 Answers 3

6
$\begingroup$
MapThread[#3 /. {1 -> #1 > #2, -1 -> #1 < #2} &, {eqexp, eqval, signval}]
(*    {{}, {b > f}, {c < g}, {d > h, d < h}}    *)
$\endgroup$
1
  • $\begingroup$ Nice! I'm embarrassed that I didn't come up with that. Thank you! $\endgroup$ Jun 27, 2019 at 19:20
4
$\begingroup$
MapThread[Through @ # @ ##2 &, {signval /. {1 -> Greater, -1 -> Less}, eqexp, eqval}]

{{}, {b > f}, {c < g}, {d > h, d < h}}

Or do the replacement inside the first argument of MapThread:

 MapThread[Through @ ReplaceAll[ {1 -> Greater, -1 -> Less}][#] @ ##2 &, 
  {signval, eqexp, eqval}]

same result

Alternatively, define a function f0 with attribute Listable and use regular function application:

f0 = Function[, # @ ##2, Listable];
f0[signval /. {1 -> Greater, -1 -> Less}, eqexp, eqval]

{{}, {b > f}, {c < g}, {d > h, d < h}}

Or use ReplaceAll in the definition of the listable function:

f1 = Function[, ReplaceAll[{1 -> Greater, -1 -> Less}][#] @ ##2, Listable];
f1[signval, eqexp, eqval]

same result

$\endgroup$
1
$\begingroup$

And the power of posting... I have found a way to do it:

MapThread[
  Function[{a, b, c}, If[c > 0, a > b, a < b], Listable], 
  {eqexp, eqval, signval}]

If there is a better way to do it, I would love to see it, though!

$\endgroup$

Your Answer

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

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