1
$\begingroup$
MySum[p_List, iMin_] := Module[{printOuput, i, iMax},
   iMax = iMin + Length[p];
   printOuput = "";
   For[i = iMin, i < iMax, i++,
    printOuput = 
     printOuput <> " + " <> ToString[i, TraditionalForm] <> 
      " \[CenterDot] " <> 
      ToString[Part[p, i - iMin + 1], TraditionalForm]];
   Print[printOuput <> " = "];
   Sum[Part[p, i - iMin + 1]*i, {i, iMin, iMax - 1}]];
p = 1/7 {3, 2, 0, 2};
MySum[p, 0]

This is my code.

  1. I would like to have it in one separate line.
  2. I would also like to remove the first "+",

So the output will look exactly like this:

$$0 \cdot \frac{3}{7} + 1 \cdot \frac{2}{7} + 2 \cdot 0 + 3 \cdot \frac{2}{7}= \frac{8}{7}$$

$\endgroup$
2
  • $\begingroup$ Get rid of the Print[...] line and change the next one to StringDrop[printOuput, 2] <> " = " <> ToString[Sum[...], TraditionalForm] $\endgroup$
    – rm -rf
    Commented Aug 2, 2013 at 18:36
  • $\begingroup$ Thank you. It works perfectly now. $\endgroup$ Commented Aug 2, 2013 at 18:44

1 Answer 1

4
$\begingroup$

Here's an alternative for you to consider:

mySum[p_List, iMin_] :=
  Sum[CenterDot[i + iMin - 1, p[[i]]], {i, Length@p}] //
    Row[{#, Times @@@ #}, "\[LongEqual]"] &

mySum[1/7 {3, 2, 0, 2}, 0]

enter image description here


Thanks for the Accept. Since you found this helpful I'd like to make sure you understand it.

The function CenterDot formats objects as implied, and by default it has no meaning so it will not evaluate to anything. This is used in Sum which you are already familiar with. (If you watched the evolution of this answer you saw that originally I used MapIndexed, which is equally applicable, but I thought Sum would be more comfortable.)

The second important bit is the function Row[{#, Times @@@ #}, "\[LongEqual]"] &.
Row itself is a formatting function that puts objects in a row, optionally with a separating character.
Times @@@ # replaces the heads at level one (here CircleDot) with Times effecting the evaluation of the sum.

$\endgroup$
1
  • 1
    $\begingroup$ +1,you shall write some book or some Mathematica articles. $\endgroup$ Commented Aug 2, 2013 at 19:09

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.