I have a data file which has been calculated from mathematica code and saved in test.txt, I need to import the data and do new calculation on it, here is the simple part of the code:

prob = 

 {{"9.780659097977332*^-7"}, {"9.0432074782253*^-7"}, 
{"9.264934689099364*^-7"}, {"9.516465106429963*^-7"}, 
{"8.577198332761887*^-7"}, {"1.1079713181045429*^-6"}}

 alpha = 1.1;
 t = Length[prob];

 Shanon = -prob[[i]].Log[prob[[i]]] + Shanon, {i, 1, t}]
Print[{alpha, Shanon}]

and here is the output,

 {1.1,-1.1079713181045429*^-6 Log[1.1079713181045429*^-6]-8.577198332761887*^-7 Log[8.577198332761887*^-7]-9.0432074782253*^-7 Log[9.0432074782253*^-7]-9.264934689099364*^-7 Log[9.264934689099364*^-7]-9.516465106429963*^-7 Log[9.516465106429963*^-7]-9.780659097977332*^-7 Log[9.780659097977332*^-7]}

I have been tried different ways including Flatten, ScientificForm,...! I am not sure if there is a problem in the way of importing the data or in the format of data.

  • 1
    $\begingroup$ Where to begin? Flatten the input, transform those strings into numbers with ToExpression, set an initial value for Shanon=0 before the Do loop, use simple * instead of the . dot product operator for simple multiplication... $\endgroup$ – MarcoB May 12 '15 at 20:42
  • $\begingroup$ HiMarcob, Thanks for reply, I just ignored to include the initialization part to keep the code small and brief here,as I mentioned I have tried the Flatten, changing . with *, the only thing that I was missing was using ToExpression,now I got it to work... $\endgroup$ – setareh May 12 '15 at 21:05

You need to flatten the list and convert elements to numeric values:

prob = Import["/home/Desktop/test1.txt", "Table"]// ToExpression// Flatten;

Then you can find the Shannon Entropy (without a do loop and initialization):

alpha = 1.1;
t = Length[prob];
shannon = Sum[-prob[[i]]*Log[prob[[i]]], {i, 1, t}];
Print[{alpha, shannon}]

(* {1.1,0.0000793592} *)

  • $\begingroup$ Hi Mahdi, thanks for the reply and comments to make the code more efficient, seems I was missing ToExpression... $\endgroup$ – setareh May 12 '15 at 21:07
  • $\begingroup$ Hi Setareh! You're very welcome. $\endgroup$ – Mahdi May 12 '15 at 21:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.