You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matlab 2016b:如何识别表达式中的未赋值符号函数

Solution for Extracting User-Defined Symbolic Functions in MATLAB R2016b

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 symfun objects like derivatives that aren't picked up by symvar.
  • Built-in functions are excluded using isbuiltin(kid), which returns true for MATLAB's native symbolic functions and false for your custom ones.

内容的提问来源于stack exchange,提问作者Alex44

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 08:22:36