@sym
: symreplace (newx)
¶@sym
: symreplace (x, newx)
¶@sym
: symreplace (x, newx, context)
¶@sym
: symreplace (xstr, newx)
¶@sym
: symreplace (xstr, newx, context)
¶@sym
: [f, flag] =
symreplace (f, xstr, newx)
¶Replace symbols in caller’s workspace or in syms/struct/cells.
WARNING: you probably do not need this for normal usage; see ‘@sym/subs’ instead.
One mode of operation is similar to subs()
:
syms x y f = {x; 2*x; sin(x)}; g = symreplace(f, x, y); g{:} ⇒ ans = (sym) y ⇒ ans = (sym) 2⋅y ⇒ ans = (sym) sin(y) g = symreplace(f, 'x', y); % alternative
However, unlike subs()
, here f
can be a cell array
or struct, which we recursively traverse down into.
flag is true if the output f was changed from the input f:
syms x y f = sin(y); [g, flag] = symreplace(f, x, y) ⇒ g = (sym) sin(y) ⇒ flag = 0
The alternative form using xstr is used internally by
OctSymPy for assumptions (see ‘@sym/assume’, see ‘@sym/assumeAlso’),
to replace one x
with another x
with possibly
different assumptions. For example:
syms x positive f = x^2; assumptions(f){:} ⇒ x: positive x = sym('x', 'real'); f = symreplace(f, 'x', x); assumptions(f){:} ⇒ x: real
The other mode of operation is also used by OctSymPy for supporting assumptions. It has no output but plenty of side-effects! Not scared off yet? Here’s what it does:
syms x real f = abs(x); syms x positive f ⇒ f = (sym) │x│ symreplace ('x', x) f ⇒ f = (sym) x
Here is the scary part: this works by searching expressions in
the callers workspace for variables with same name as
x/xstr. We then substitute newx. If x
is omitted, the string of newx is used instead. This is
precisely what happens when using assume
:
syms x f = abs(x); assume(x, 'positive') f ⇒ f = (sym) x
Note: operates on the caller’s workspace via evalin/assignin.
So if you call this from other functions, it will operate in
your function’s workspace (not the base
workspace).
You can pass 'base'
to context to operate in
the base context instead.
Note for developers: if you want to call this from your function
but have it work on the ’caller’ context
of your function, that unfortunately does not seem to
be possible. Copy-paste the highlighted bits of this code into
your function instead (see assume
for example).
See also: @sym/assume, @sym/assumeAlso, assumptions, sym, syms.
Package: symbolic