I have a symbolic function that looks like this
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)
I'd like to replace all instances of derivatives of y with its first derivative, i.e.
subs(fn, sym('diff(y(x), x)'), dy)
where dy is already defined as
dy(x) = 2*x + y(x) - 1
The result is the following:
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)
It replaces the first derivative, but not the higher derivatives. What I want is for the h^5 term to have (h^5*diff(dy(x), x, x, x). Is there any way to do that?
My current method is pretty hackish and involves converting the sym to a string, replacing first derivatives with dy, then converting back to a sym and evaluating to reduce the order of each term of the series by one, but it has to be recursive because at each stage derivatives of dy are then replaced by something containing diff(y, ...). I was hoping there would be a cleaner way to deal with this.
You need to keep in mind that Matlab treats things like
diff(y,x)anddiff(y,x,2)as distinct variables. It doesn't know how to substitutediff(y,x)intodiff(y,x,2)because such a general operation for an abstract function (one with out an explicit definition, e.g.,y(x)) is ill-defined.How about something like this that performs substitution from the opposite end, starting with the highest order derivatives:
This returns
Or you can leave
dy(x)as an abstract symbolic expression initially:which returns