0
$\begingroup$

I want to replace parts of a result from a calculation that involves fetching data from files, only some of those files do not contain data. So when I do a calculation, I would for example get a result like this:

{(π (74967393 + Take[Drop[{#1, LineNumber, N_liquid, N_solid, pressure, vol, cutoff}, 14], {3, -3, 7}]))/(6 (4.54588*10^8 + 2474.73 e + Take[{}, {6, -6, 7}]))}

I know that the replace all command /. can be used here, and it indeed works if I replace the "e" and the Take[{}, {6, -6, 7}] with 0, but this does not work for the

Take[Drop[{#1, LineNumber, N_liquid, N_solid, pressure, vol,  cutoff}, 14], {3, -3, 7}] 

part. I tried to convert this into a string, use StringReplace on the Take expression, and convert it back into an Expression afterwards, but this messes up the exponent of my results due to the exponent (the 10^8) not being correctly converted back into an expression.

Is there any other way to remove the

Take[Drop[{#1, LineNumber, N_liquid, N_solid, pressure, vol, cutoff}, 14], {3, -3, 7}]

part?

$\endgroup$
2
  • $\begingroup$ I'd suggest a If[] structure to avoid this problem in the first place. $\endgroup$
    – Feyre
    Oct 27, 2016 at 14:56
  • $\begingroup$ That would work, but my code takes a long time to computate these values from the files, so I would prefer to not have any If/Select/Cases etc. statements that further slow it down.. Isnt there a way to stop mathematica from executing code parts like this Take part in my OP? It seems like that is the problem, this line in my code will try to execute before the replacement rule is used, it throws an exception and then the replace all is skipped. $\endgroup$ Oct 27, 2016 at 16:13

1 Answer 1

0
$\begingroup$

You can handle this by defining an auxiliary function:

zero[__]:=0

(The double underscore in the argument means that the function can have one or more arbitrary entries, which will all default to the right hand side.)

And then do the following with your output of interest:

(output//Hold)/.e->0/.Take->zero//ReleaseHold//Quiet

In particular, for example for the output you suggest, you will get:

({(π (74967393 + Take[Drop[{#1, LineNumber, N_liquid, N_solid, pressure, vol, cutoff}, 14], {3, -3, 7}]))/(6 (4.54588*10^8 + 2474.73 e + Take[{}, {6, -6, 7}]))}//Hold)/.e->0/.Take->zero//ReleaseHold//Quiet

{0.0863482}

Which I assume is what you are looking for.

$\endgroup$
1
  • $\begingroup$ Thank you, that worked like a charm! $\endgroup$ Oct 28, 2016 at 8:04

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.