6
$\begingroup$

I have the expression:

Times[0.19157500241430547,Power[Plus[0.7235014213631388,k,Times[-1,Power[m,c]]],Times[g,z]]]

Also represented as:

0.191575 (0.723501 + k - m^c)^(g z)

I want to randomly select either a symbol or real and delete it from the expression, so the expression might become:

0.191575 (k - m^c)^(g z)

Or maybe:

0.191575 (0.723501 + k - m^c)^(z)

Is there a simple way to do this?

$\endgroup$
1
  • $\begingroup$ If there were even a way to use Dimensions[] to get all of the dimensions of the expression, I could use those dimensions to plug in for Delete[]. $\endgroup$
    – Jmeeks29ig
    Sep 10, 2018 at 19:13

3 Answers 3

3
$\begingroup$
Clear@expr
expr=0.191575 (0.723501 + k - m^c)^(g z)
Delete[expr,RandomChoice@Position[expr, x_ /; Length@x == 0, Heads -> False]]

(*Original: 0.191575 (0.723501 +k-m^c)^(g z)
New: (0.723501 +k-m^c)^(g z)*)
$\endgroup$
2
  • 2
    $\begingroup$ I would use Position[expr, _Symbol | _Real, {-1}, Heads -> False] instead. $\endgroup$
    – Carl Woll
    Sep 10, 2018 at 19:42
  • $\begingroup$ It works, thanks!! $\endgroup$
    – Jmeeks29ig
    Sep 10, 2018 at 19:44
8
$\begingroup$

Maybe, as a simple but general utility function, you can use this:

RandomDelete[expr_, pattern_, opts___] := Delete[
  expr, 
  RandomChoice[Position[expr, pattern, opts]]
]

Then you can use it to randomly delete symbols:

RandomDelete[0.191575 (0.723501 + k - m^c)^(g z), _Symbol]

Or reals:

RandomDelete[0.191575 (0.723501 + k - m^c)^(g z), _Real]

And use the Heads option that is used by Position:

Table[RandomDelete[f[x, y], _, Heads -> False], 30]

I've added this to my Prototypes paclet, available here:

PacletInstall["https://github.com/arnoudbuzing/prototypes/releases/download/v0.4.1/Prototypes-0.4.1.paclet"]

(And to uninstall, run PacletUninstall["Prototypes"])

Its documentation page has a few examples on how you can use it:

enter image description here

$\endgroup$
1
  • $\begingroup$ Awesome, thanks! $\endgroup$
    – Jmeeks29ig
    Sep 11, 2018 at 17:36
3
$\begingroup$
deleteRandomCase = DeleteCases[#, RandomChoice[Cases[#, _Symbol | _Real, -1]], -1, 1] &;

Examples:

Table[deleteRandomCase[expr], {5}] // Column // TeXForm

$\begin{array}{l} 0.191575 \left(0.723501\, -m^c\right)^{g z} \\ 0.191575 \left(-m^c+k+0.723501\right)^g \\ \left(-m^c+k+0.723501\right)^{g z} \\ 0.191575 \left(k-m^c\right)^{g z} \\ 0.191575 \left(k-m^c\right)^{g z} \\ \end{array}$

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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