【问题标题】:How to get arglist from a function handle?如何从函数句柄中获取 arglist?
【发布时间】:2015-06-29 07:21:37
【问题描述】:

我有以下函数句柄

 fun = @(x,y,z)[x.^3+y.^2+z.^2,x.^2-y.^3+sin(z)]

现在我正在使用该功能

jacobian(fun, [x,y,z])

返回函数的雅可比。要使用这个功能,我首先需要定义

syms x y z. 

如果函数变为

@(x,y,z,w)[x.^3+y.^2+z.^2+w,x.^2-y.^3+sin(z)+w] 

雅可比由

返回
jacobian(fun, [x,y,z,w]). 

现在我不想手动更改 jacobian 的第二个输入参数。 Matlab中是否有一个函数,它查看函数句柄并返回它们,或者返回有多少?

非常感谢!

【问题讨论】:

    标签: matlab function arguments handle


    【解决方案1】:

    你可以这样做:

    str = func2str(fun); %// get fun's defining string
    str = regexp(str, '^@\([^\)]+\)', 'match'); %// keep only "@(...)" part
    vars = regexp(str{1}(3:end-1), ',', 'split'); %// remove "@(" and ")", and  split by commas
    jacobian(fun, sym(vars)); %// convert vars to sym and use it as input to jacobian
    

    例子:

    >> clear all
    >> syms r s t
    >> fun = @(r,s,t) [r*s^t r+s*t]
    fun = 
        @(r,s,t)[r*s^t,r+s*t]
    >> str = func2str(fun);
       str = regexp(str, '^@\([^\)]+\)', 'match');
       vars = regexp(str{1}(3:end-1), ',', 'split');
       jacobian(fun, sym(vars))
    ans =
    [ s^t, r*s^(t - 1)*t, r*s^t*log(s)]
    [   1,             t,            s]
    

    【讨论】:

    • 感谢您纠正(完成)我的回答。我对符号工具箱非常缺乏经验,所以我不想冒险猜测。也不错的答案。我喜欢学习新事物。
    • 我也不经常使用符号工具箱。这是 Stack Overflow 的一件好事:它激励你去尝试和学习! :-)
    【解决方案2】:

    functions 函数和快速正则表达式可以帮助您:

    fun = @(x,y,z,w)[x.^3+y.^2+z.^2+w,x.^2-y.^3+sin(z)+w] ;
    
    s = functions(fun) ;
    strVar = strsplit( char( regexp(s.function, '\(([^\)]+)\)' , 'tokens' , 'once' )) ,',') ;
    nInput = numel(strVar) ;
    

    会得到你:

    >> strVar
    strVar = 
        'x'    'y'    'z'    'w'
    >> nInput
    nInput =
         4
    

    编辑:非常感谢 Luis Mendo 的评论。

    您需要添加如下内容:

    sym(strVar(:))
    

    将它们声明为符号变量,或直接:

    jacobian(fun, sym(strVar))
    

    计算你的雅可比。

    【讨论】:

    • 我认为您需要最后一步将strVar 转换为sym,因为jacobian 需要sym 输入。看我的回答。为该方法+1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    • 2022-01-16
    相关资源
    最近更新 更多