Mathematica

From Torben's Wiki

Define Functions / Routines

define simple function

f[x_]= a * Sin[x]

This checks value of a each time f is addressed, opposite to

f[x_]:= a * Sin[x]

Advanced function/routine (note % does not work!)

findX[b_] := Module[{f1, f2, start = 2},
 f1 = Exp[x] - b;
 f2 = Sin[x];
 Plot[{f1, f2}, {x, 0, 10}];
 xSolved = FindRoot[f1 == f2, {x, start}]
]

UnDefine Variable / Function

ClearAll[f,a]

Schnippel

Numerical Integration: Splitting is extremely important for result and speed

NIntegrate[f[x], {x, -∞, 0, a, ∞}, MaxRecursion -> 20]


File Access

 exportDirData = "z:\\mathematica\\export\\";
 DeleteDirectory[exportDirData, DeleteContents -> True];
 CreateDirectory[exportDirData];
 Export [exportDirData <> "1.dat", data, "TSV"];

 importDirData = "z:\\mathematica\\import\\";
 SetDirectory[importDirData];
 files = FileNames[];
 For[i=1,i<=Length[files],i++,
  file = files[[i]];
  data = Import[file, "TSV"];
  data = Delete[data,1]; (*remove header line*)
  data = data[[All, {1, 4, 5}]]; (*only columns 1,4 and 5 *)
  out={};
  For[j=1, j<=Length[data], j++,
   x = data[[j,1]];
   y = data[[j,2]];
   out = Append[out, {x,y};
  ]
  out=Prepend[out,{"# X ", "Y (S/cm)"}];
 ]
 

Plotting

p1=Plot[Sin[x],{x,0,10},DisplayFunction->Identity];
p2=Plot[Sin[2x],{x,0,10},DisplayFunction->Identity];
Show[GraphicsArray[{p1,p2}]];
Export[exportDirImg <> filename <> ".pdf", p1, "PDF", ImageSize -> 640, ImageResolution->300, ImageRotated -> False];

Nicer Plots

<< Graphics`
SetOptions[Plot, Frame -> True, Axes -> False, FrameLabel -> {None, None, None, None}, RotateLabel -> True
, TextStyle -> {FontSize -> 12, FontWeight -> "Bold", FontFamily -> "Arial"}
, PlotStyle -> {RGBColor[1,0,0], RGBColor[0,1,0], RGBColor[0,0,1], RGBColor[1,1,0], RGBColor[1,0,1], RGBColor[0,1,1], RGBColor[0,0,0]}
, ImageSize -> 320];

similar for LogPlot, ListPlot, LogLinearListPlot, LogLogListPlot