【问题标题】:In Matlab, what is the difference in class between sym('x') and sym('1-x')?在 Matlab 中,sym('x') 和 sym('1-x') 的类有什么区别?
【发布时间】:2016-05-10 13:03:39
【问题描述】:

我定义了以下函数:

function y = pos(c)
% function outputs the maximum of c and 0 
%ie. pos(c)=0 if c is negative, and pos(c)=c if c is positive
if isa(c,'sym')
    y=sym(strcat('pos(',c,')'));
elseif isa(c,'double')
    y=max(c,0);
else
    y='not defined';
end

如果我输入 sym('x') 形式的符号,它就可以正常工作:

>> pos(sym('x'))

ans =

pos(x) 

但是,如果我将其应用于 sym('1-x') 形式的符号,则会出现错误:

>> pos(sym('1-x'))
In an assignment  A(:) = B, the number of elements in A and B must be the same.

Error in strcat (line 94)
        s(pos:pos+len-1) = str;

Error in pos (line 6)
    y=sym(strcat('pos(',c,')'));

这是为什么?我认为 sym('x') 和 sym('1-x') 的性质有所不同?

【问题讨论】:

  • 谢谢,你知道我将如何将我的函数应用于 1-x,x 符号?我试过:pos(1-sym('c')) 无济于事。
  • 我推荐 using the debugger 来查看您要连接的 c 的值。
  • 这给了我我需要的答案(即 pos(1-x)),但我认为将变量存储为字符串会导致在我需要 x 的另一个函数中调用函数时出现问题保持象征性?函数 y = pos(c) % 函数输出 c 和 0 %ie 的最大值。如果 c 为负数,则 pos(c)=0,如果 c 为正数,则 pos(c)=c 如果 isa(c,'sym') y=sym(strcat('pos(',char(c),')' )); elseif isa(c,'double') y=max(c,0); else y='未定义';

标签: matlab function compiler-errors symbolic-math


【解决方案1】:

使用字符串操作来替换变量并不是一个好主意。

为相关部分提供替代方案:

if isa(c,'sym')
    %create a symbolic function pos
    f=symfun(sym('pos(h)'),sym('h'))
    %substitute the parameters
    y=f(c)
elseif

【讨论】:

    猜你喜欢
    • 2019-09-16
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    相关资源
    最近更新 更多