在 MATLAB 中替换符号导数

Replacing symbolic derivatives in MATLAB

我有一个像这样的符号函数

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)。有什么办法吗?

我目前的方法很老套,涉及将符号转换为字符串,用 dy 替换一阶导数,然后转换回符号并评估以将系列中每一项的顺序减少一个,但它必须是递归的,因为在每个阶段 dy 的导数然后被包含 diff(y, ...) 的东西替换。我希望有一种更简洁的方法来处理这个问题。

您需要记住,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);

这个returns

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)

哪个returns

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)