1
$\begingroup$

All,

I want to know how to replace multiple variables in the result expression. To be specific, all those variables are inside the array I defined.

For a simple example, if I define input

mm5 = {a, b, c, d};

mm7 = {2, 3, 9, 8};

mm7a = mm7.mm5

Out: 2 a + 3 b + 9 c + 8 d

After that, if I define a new array

mm6 = {3, 4, 5, 7}

And I want to replace every unknown component in mm5 to be the values in mm6, and to let the final result of mm7a be 2*3+3*4+9*5+8*7=119. How should I do that?

I was thinking is there any way similar to

mm7a /. {mm5[[i]] -> mm6[[i]],{i,1,4}}

Of course, what I wrote is wrong. But is there any simple way to use /. to help me achieve this effect?? And after substituting, I want symbols in mm5 be reserved, for example, when I output mm5 result, it is still {a, b, c, d}

I searched the whole web but I didn't find a simple way to do it. Maybe I didn't search it right. So I post my question here and hope get some answer.

Thank you

$\endgroup$
0

2 Answers 2

5
$\begingroup$
Clear["Global`*"]

mm5 = {a, b, c, d};

mm7 = {2, 3, 9, 8};

mm7a = mm7 . mm5

(* 2 a + 3 b + 9 c + 8 d *)

mm6 = {3, 4, 5, 7};

If mm5 is known

mm7a /. Thread[mm5 -> mm6]

(* 119 *)

or

((List @@ mm7a)/mm5) . mm6

(* 119 *)

If mm5 is not known

Cases[mm7a, _Integer, ∞] . mm6

(* 119 *)

or

(List @@ mm7a /. n_Integer*_ :> n) . mm6

(* 119 *)
$\endgroup$
1
  • $\begingroup$ Nice to find a easy command using "Thread". Thanks ! $\endgroup$
    – VinCC899
    Apr 22, 2021 at 17:52
0
$\begingroup$

Another approach you might want to consider is to define a function that does the job. So for the specific setup you request:

f[x_, y_] := x . y

Now you can apply f to your desired values:

mm5 = {a, b, c, d};
mm7 = {2, 3, 9, 8};
mm6 = {3, 4, 5, 7};

f[mm5, mm7]
f[mm5, mm6]

and you get something that is generic and can be easily modified for other applications by redefining f[ ].

$\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.