7
$\begingroup$

I have a list of associations, and I would like to make it so that an expression automatically reads the associated data from the associations list, that has the same name, into the expression. An example would be better than words:

The expression:

-0.0441268 (-0.905134 - f + (3.24967 + p)^0.638117)

The associations:

<|a -> -0.497445, b -> -0.12459, c -> 0.59053, d -> 0.26936, 
 e -> 0.745094, f -> -0.225087, g -> 0.744386, h -> 0.915999, 
 i -> 0.540287, j -> 0.406811, k -> -0.664433, l -> 0.355135, 
 m -> -0.880653, n -> -0.559651, o -> -0.23426, p -> 0.260966, 
 q -> 0.435459, r -> -0.105631, s -> 0.544961, t -> 0.347138, 
 u -> 0.958919, v -> 0.200587, w -> -0.656598, x -> 0.553327, 
 y -> -0.282113, z -> 0.178719|>

I would like the f and p, from the associations list, to be automatically mapped into the expression, so that, in the expression, f would have the value -0.225, and p would have the value 0.26.

Is there any way to do this? Thanks!

$\endgroup$
11
$\begingroup$

You can simply use your association as a list of rules to be passed to ReplaceAll, also known as /..

expr = -0.0441268 (-0.905134 - f + (3.24967 + p)^0.638117)

assoc = <|a -> -0.497445, b -> -0.12459, c -> 0.59053, d -> 0.26936, 
  e -> 0.745094, f -> -0.225087, g -> 0.744386, h -> 0.915999, 
  i -> 0.540287, j -> 0.406811, k -> -0.664433, l -> 0.355135, 
  m -> -0.880653, n -> -0.559651, o -> -0.23426, p -> 0.260966, 
  q -> 0.435459, r -> -0.105631, s -> 0.544961, t -> 0.347138, 
  u -> 0.958919, v -> 0.200587, w -> -0.656598, x -> 0.553327, 
  y -> -0.282113, z -> 0.178719|>

Now

expr /. assoc

or

ReplaceAll[expr, assoc]

will give you the answer, in this case -0.0683299.

$\endgroup$
  • $\begingroup$ Thanks a bunch, it worked! $\endgroup$ – Jmeeks29ig Sep 9 '18 at 17:35
6
$\begingroup$

Also

With[{f = assoc[f], p = assoc[p]}, Evaluate @ expr] 

-0.0683299

$\endgroup$

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.