Consider an expression exp = a^2 + b + c which has variables a, b, and c, and its values are stored in aval = 1, bval = 2, and cval = 3.
If cval is not given I would like the expression to get evaluated to 3 + c.
The function I have written is:
rulesVal[exp_] :=
Cases[Variables@exp,
x_ /; Head[x] == Symbol :> (x -> Symbol[ToString[x] <> "val"])]
toVal[exp_] := exp /. rulesVal[exp]
When I input a^2 + b + c to toVal function, I get 3 + cval.
How do I get 3 + c?
ValueQ? – Michael E2 Dec 13 '16 at 01:44exp=a^2+b+candexp/.{a->1,b->2}which yields3+c– Manuel --Moe-- G Dec 13 '16 at 01:46aval = 1etc., or are they given to you in a data file or something? I ask because there are better ways to manage such data.val[x_] := xand thenval[a] = 1; val[b] = 2; usage something likeexp /. Thread[# -> val /@ #]&@Variables[exp]. Or similarly withAssociation. – Michael E2 Dec 13 '16 at 02:21ValueQin the following way,rulesVal[exp_] := If[ValueQ[ Symbol[ToString[#] <> "val"]], (# -> Symbol[ToString[#] <> "val"]), # -> #] & /@ (Variables@exp);toVal[exp_] := exp /. rulesVal[exp];When evaluating toVal[exp], it gives an error which says "OwnValues::sym: Argument Symbol[ToString[a]<>val] at position 1 is expected to be a symbol."
– Anjan Kumar Dec 13 '16 at 02:22I wrote those assignments and there are around 50 of such assignments. If there is no other way, then I will adapt your way. – Anjan Kumar Dec 13 '16 at 02:27
ValuesQis perhaps not so easy because it isHoldAll: it's tricky to pass it the unevaluated symbol. If the assignments are all numeric values, tryNumericQ. – Michael E2 Dec 13 '16 at 02:32