Matlab 2016b:如何识别表达式中的未赋值符号函数
Got it, let's break down how to pull out user-defined unassigned symbolic functions (like a(t), b(t)) from a symbolic expression in MATLAB R2016b. We'll make sure to exclude regular symbolic variables (like c) and built-in math functions (like sin, cos) as requested.
Option 1: Get Base Symbolic Functions (No Derivatives)
MATLAB's symvar function has a handy flag in R2016b that lets you directly retrieve user-defined symbolic functions. The 'functions' argument skips regular variables and built-ins automatically—perfect if you only want the base functions like a(t) and b(t).
Using your example code:
syms a(t) b(t) c; expr = a(t)*diff(b, t) + c*diff(a,t)^2 + sin(c*pi)*cos(b); % Retrieve base user-defined symbolic functions base_funs = symvar(expr, 'functions');
Running this will return [a(t), b(t)], which matches one of your desired outcomes.
Option 2: Include Derivatives of Symbolic Functions
If you want to capture derivatives (like diff(a,t), diff(b,t)) alongside the base functions, you'll need a recursive helper function to traverse the expression and filter valid symfun objects (while excluding built-ins).
Here's a reusable function to do this:
function funs = get_all_user_symfuns(expr) funs = []; % Recursively check all child elements of the expression kids = children(expr); for kid = kids' % First recurse into child elements to catch nested functions sub_funs = get_all_user_symfuns(kid); funs = [funs, sub_funs]; % Check if current element is a symbolic function (symfun) if isa(kid, 'symfun') % Exclude built-in functions like sin, cos if ~isbuiltin(kid) funs = [funs, kid]; end end end % Remove duplicate entries to clean up the result funs = unique(funs); end
Test it with your example:
all_funs = get_all_user_symfuns(expr);
This will return [a(t), b(t), diff(a(t), t), diff(b(t), t)], which is exactly the full set of functions you mentioned wanting.
Quick Notes
symvar(expr, 'functions')is the simplest approach for base functions since it's built-in and handles filtering out non-user functions automatically.- The recursive function is ideal if you need to include derived
symfunobjects like derivatives that aren't picked up bysymvar. - Built-in functions are excluded using
isbuiltin(kid), which returnstruefor MATLAB's native symbolic functions andfalsefor your custom ones.
内容的提问来源于stack exchange,提问作者Alex44

