1
$\begingroup$

I have to calculate:

enter image description here

How can I create such a sum? Do I have to set the factors of each term manually (one by one), like G1 = 1, H1 = 1, G2 2, H2 = ....?

Update

enter image description here

Addtional Questions:

  1. How can I store te results into another List? (In this example, the list F)

  2. Sometimes, a variable turns blue and does not get calculated in expression. How do I fix this?

$\endgroup$

2 Answers 2

5
$\begingroup$

Create lists like this:

g = {1, 2, 3, 4}
h = {10, 20, 30, 40}

Then you can sum like this:

Sum[g[[i]] h[[i]], {i, Length[g]}]

or more nicely (Mathematica does element-wise operations automatically where applicable):

Total[g*h]

Additional question 1) You can use this feature to easily calculate a new list with the results, without using indices:

f = (g h)/Total[g h]

{1/30, 2/15, 3/10, 8/15}

If you want to use indices anyway, you can do it with Table:

f1 = Table[
  (g[[k]] h[[k]])/Sum[g[[i]] h[[i]], {i, Length[g]}],
  {k, Length[g]}]

Additional question 2) A blue variable means it is unbound to a value. The variable will be used as a symbol instead. Teal color means it is bound to a value via an enclosing function. In your example, Sum binds i to a value it fills in. A black variable has a globally assigned value.

$\endgroup$
4
  • $\begingroup$ How manipulate g[i], h[i] in basic calculations?(Not just in the sum function) $\endgroup$
    – ZK Zhao
    Apr 21, 2014 at 11:12
  • $\begingroup$ See my update please, thank you. $\endgroup$
    – ZK Zhao
    Apr 21, 2014 at 11:17
  • $\begingroup$ You can always change individual elements like this: g[[1]] = 17 $\endgroup$ Apr 21, 2014 at 11:21
  • $\begingroup$ I updated the answer $\endgroup$ Apr 21, 2014 at 11:36
4
$\begingroup$

Given a set of lists:

h = Table[RandomReal[{0, 30}], {7}]
g = Table[RandomReal[{17000, 20000}], {7}]

(* {22.7964, 26.9984, 0.971047, 4.21998, 21.7333, 20.8884, 14.155} *)
(* {18409.6, 17870.2, 19297.1, 19537.1, 19840.5, 19043.6, 17829.} *)

For alternatives to the fine answer by Justin, you can:

also use the Dot (a.k.a. Inner) product:

fList = g h/h.g

(* {0.201312, 0.231435, 0.00898861, 0.0395486, 0.206842, 0.190815, 0.121059} *)

or using Table explicitly gives the same List

fList = Table[h[[i]] g[[i]], {i, Length@h}]/h.g

If you want an actual Function to pick out individual parts of the list:

fFunction[i_] := h[[i]] g[[i]]/h.g
fFunction[1]

(* 0.201312 *)
$\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.