I'm a physics grad and have been using Mathematica mostly for data visualization. The evaluation part I normally do with C/Python, but I've been wanting to try out Mathematica for these tasks, too.
Case in point, I made two notebooks for trimming and evaluating data for a recent experiment.
Code example:
new = data[[All, 1]]
For[i = 1, i < Length[data[[All, 1]]] - 1, i += 1,
If[
Abs[data[[i, 1]] - data[[i + 1, 1]]] > 2000,
new[[i + 1]] = Mean[{data[[i, 1]], data[[i + 2, 1]]}];
i += 1;
]];
data[]
is a list with ~30000 datapoints (x, y, value). Here, x from xmin to xmax has to be linear, but there are some (very few) points that were measured incorrectly and thus are way above/below the other points.
The loop above iterates over this list and checks the difference of list element [i]
and [i+1]
. If this difference is larger than a threshold, element [i+1]
is replaced by the mean value of element [i]
and [i+2]
.
I would love to know if there was a more elegant way of doing this? Ideally faster, too, since I intend to use this on much larger lists. The above is one loop of many, so an explanation of the thought process that went into the solution would help a great deal :)
Thanks a lot in advance!
EDIT: Maybe I haven't stated my problem clearly enough, so I'll try again. I really don't need help regarding what the above code does - it does exactly what I want and has been tested with many datasets. I just want to know if there is a more "Mathematica-ish" way of writing it, since I've been told to avoid for-loops as Mathematica promotes a more functional style of programming.
ONE MORE EDIT: I'd like to thank everyone who devoted some time to this. I see that I should've included sample data when stating the problem, I'll try to remember next time ;)
-1
inLength[data[[All, 1]] - 1]
? $\endgroup$Mean[{x[i], x[i+2]}]
- I'm cheating a bit because I'm not actually checking the last two elements of the list. Which is okay in this case, though. $\endgroup$Length[data[[All, 1]]] - 1
, i.e. the-1
out of theLength
call. $\endgroup$-1
though, otherwise I'd have to doi <= length -2
... $\endgroup$