我有一个看起来像这样的符号功能
syms x y(x) h
fn(x) = y + (h^2*(diff(y(x), x) + 2))/2 + (h^5*diff(y(x), x, x, x, x))/120 + (h^3*diff(y(x), x, x))/6 + (h^4*diff(y(x), x, x, x))/24 + h*(2*x + y(x) - 1)
我想用其一阶导数替换y的导数的所有实例,即
subs(fn, sym('diff(y(x), x)'), dy)
其中dy
已定义为
dy(x) = 2*x + y(x) - 1
结果如下:
ans(x) =
y + (h^2*(2*x + y(x) + 1))/2 + (h^5*diff(y(x), x, x, x, x))/120 + (h^3*diff(y(x), x, x))/6 + (h^4*diff(y(x), x, x, x))/24 + h*(2*x + y(x) - 1)
它取代了一阶导数,而不是高阶导数。我想要的是h^5
字词(h^5*diff(dy(x), x, x, x)
。有没有办法做到这一点?
我当前的方法非常hackish,涉及将sym转换为字符串,用dy
替换一阶导数,然后转换回sym并评估将系列中每个项的顺序减少一,但是它必须是递归的,因为在每个阶段dy
的衍生物然后被包含diff(y, ...)
的东西取代。我希望有更清洁的方法来处理这个问题。
答案 0 :(得分:1)
您需要记住,Matlab将diff(y,x)
和diff(y,x,2)
之类的内容视为不同的变量。它不知道如何将diff(y,x)
替换为diff(y,x,2)
,因为抽象函数的一般操作(一个没有明确定义的操作,例如y(x)
)是不明确的
这样的事情如何从相反的一端执行替换,从最高阶导数开始:
syms y(x) h
dy(x) = 2*x + y - 1
fn(x) = y + (h^2*(diff(y, x) + 2))/2 + (h^5*diff(y, x, 4))/120 + (h^3*diff(y, x, 2))/6 + (h^4*diff(y, x, 3))/24 + h*(2*x + y - 1)
fn2 = subs(fn, diff(y, x, 4), diff(dy, x, 3));
fn2 = subs(fn2, diff(y, x, 3), diff(dy, x, 2));
fn2 = subs(fn2, diff(y, x, 2), diff(dy, x));
fn2 = subs(fn2, diff(y, x), dy);
返回
fn2(x) =
y(x) + (h^2*(2*x + y(x) + 1))/2 + (h^3*(2*x + y(x) + 1))/6 + (h^4*(2*x + y(x) + 1))/24 + (h^5*(2*x + y(x) + 1))/120 + h*(2*x + y(x) - 1)
或者您最初可以将dy(x)
作为抽象符号表达式:
syms y(x) dy(x) h
fn(x) = y + (h^2*(diff(y, x) + 2))/2 + (h^5*diff(y, x, 4))/120 + (h^3*diff(y, x, 2))/6 + (h^4*diff(y, x, 3))/24 + h*(2*x + y - 1)
fn2 = subs(fn, diff(y, x, 4), diff(dy, x, 3));
fn2 = subs(fn2, diff(y, x, 3), diff(dy, x, 2));
fn2 = subs(fn2, diff(y, x, 2), diff(dy, x));
fn2 = subs(fn2, diff(y, x), dy)
返回
fn2(x) =
y(x) + (h^4*diff(dy(x), x, x))/24 + (h^2*(dy(x) + 2))/2 + (h^5*diff(dy(x), x, x, x))/120 + (h^3*diff(dy(x), x))/6 + h*(2*x + y(x) - 1)