mapSymType
Applies a function to every subexpression of a given type.
Category: Symbolic Computations in MATLAB > Symbolic Variables, Expressions, Functions, and Preferences
Syntax
R = mapSymType(S, type, f)
Replaces each subexpression of S of type type with f applied to it.
Description
mapSymType walks the expression tree, finds every part of the requested type and replaces it by the value of f on that part. It is a structural rewrite: unlike subs it can act on all occurrences of a whole class of subexpressions, such as every integer or every call of sin.
For example, mapping n -> n + 1 over the integers of x^2 + 3*x produces x^3 + 4*x, since both the exponent and the coefficient are integers.
Input arguments
S- Symbolic expression.
type- Type name string, such as
'variable','integer'or a function name like'sin'. f- Function handle that takes one subexpression and returns its replacement.
Output arguments
R- The rewritten expression.
Example
Rewriting variables and function calls
syms x
mapSymType(x + 1, 'variable', @(v) v^2)
mapSymType(sin(x) + cos(x), 'sin', @(s) cos(children(s)))
mapSymType(x^2 + 3*x, 'integer', @(n) n + 1)
Output
ans = x^2 + 1
ans = 2*cos(x)
ans = x^3 + 4*x