6
$\begingroup$

I tried searching in the docs in "Transformation Rules and Definitions", however there wasn't anything of help.

So imagine I have these two rules:

{x -> 2, y -> 3} 
{x -> 3, y -> 5}

I want to do the following: I want to multiply the second set of rules by e.g. I: so something like this should come out:

{x -> I 3, y -> I 5}

and then I want to 'add them together':

{x-> 2+3I, y-> 3+5I}

Is there a good way to do this?

Context: These are the BestFitParameters from a model of the Re and Im part of data sets. So I essentially have the Im and Re part of my parameters separetely and I want to add them together.

(No, I do not need the parameters to reinsert into the model, this can of course be done naturally with Normal and the two nonlinearfits.)

$\endgroup$

5 Answers 5

10
$\begingroup$
a = {x -> 2, y -> 3};
b = {x -> 3, y -> 5};

<|a|> + <|b|> I // Normal

{x -> 2 + 3 I, y -> 3 + 5 I}

<||> is a short form for Association

$\endgroup$
9
$\begingroup$
{a, b} = {{x -> 2, y -> 3}, {x -> 3, y -> 5}};

Normal @ Merge[Apply @ Complex] @ {a, b}
{x -> 2 + 3  I, y -> 3 + 5  I}
$\endgroup$
4
$\begingroup$

This is a naive solution:

Thread[{x, y} -> 
  Map[Times[I, Values[#]] &, {x -> 2, y -> 3}] + 
   Values[{x -> 3, y -> 5}]]

Any improvements are welcomed.

$\endgroup$
1
  • 1
    $\begingroup$ Thread[{x, y} -> Complex @@@ Transpose[{Values@r1, Values@r2}]] where r1 and r2 are the rules $\endgroup$
    – Syed
    Commented Jan 24 at 9:31
4
$\begingroup$

This is just for fun and to try to get to 10 different ways for doing the same thing in Mathematica !

rules = {{x -> 2, y -> 3}, {x -> 3, y -> 5}};
rules = rules /. Rule[a_, b_] :> Sequence @@ {a, b};
rules[[2, {2, 4}]]*I + rules[[1, {2, 4}]];
MapThread[Rule[#1, #2] &, {{x, y} , %}]

Mathematica graphics

$\endgroup$
3
$\begingroup$
MapThread[Sequence[First@#1->Last@#1 + Last@#2 I]&,{{x -> 2, y -> 3}, {x -> 3, y -> 5}}]

(* {x->2+3 I,y->3+5 I} *)

Alternatively

{Replace[{x -> 3, y -> 5}, (a_ -> b_):> (a -> b I),1],{x -> 2,
   y -> 3}}//Merge[Total]//Normal

(* {x -> 2 + 3 I, y -> 3 + 5 I *)
$\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.