Matlab evaluate ODE at initial condition

Viewed 27

Suppose I have dy/dx=xy+1, y(1)=2

How can I evaluate it with the initial condition of y(1)=2?

When I try ode(1) it outputs y(1) + 1 but I want it to return 3 because y(1)=2

It is entirely possible that my whole approach is wrong

What I have tried

close all;
clear all;
syms y(x);
ode = diff(y,x) == x*y+1;
ode(1)

ans =
 
subs(diff(y(x), x), x, 1) == y(1) + 1

Ultimately I want to be able to continue up the order, for example, fpp = diff(ode) and continue to do the same

y' = 3
y'' = 5
y''' = 11
an so on

PS: I am not trying to solve the equation. I can do that with

cond = y(1) == 2;
dsolve(ode,cond)

ans =
 
exp(x^2/2)*(2*exp(-1/2) - (2^(1/2)*pi^(1/2)*erf(2^(1/2)/2))/2) + (2^(1/2)*pi^(1/2)*exp(x^2/2)*erf((2^(1/2)*x)/2))/2

Update:

This is horrendously bad code but I put it together to get my point accross. I want to do this but without string manipulations

syms y(x)
ode = diff(y,x) == x*y+1;
order = 6;
keyValue = ["Dummy","Dummy";"Dummy","Dummy";];
y=ode;
value=0;

for i=1:order
    current = char(y);

    for j=1:(length(keyValue))
        current = replace(current,keyValue(j,1),keyValue(j,2));
    end
    
    pos = strfind(current,"==");
    leftText =  extractBefore(current,pos-1);
    rightText = extractAfter(current,pos+2);
    
    % Initial Value for x
    rightText = replace(rightText,"x","1");
    
    % Initial Value for y
    rightText = replace(rightText,"y(1)","2");
    
    % Take text and create function handle
    f1 = eval(['@(x)' rightText]);
    
    % Call function (input doesn't matter, there's no x)
    value = f1(24353);
    
    % Add to key value
    keyValue(i,1) = leftText;
    keyValue(i,2) = num2str(value);
    
    % Move to next
    y=diff(y);
    
end
keyValue

    "diff(y(x), x)"                   "3"  
    "diff(y(x), x, x)"                "5"  
    "diff(y(x), x, x, x)"             "11" 
    "diff(y(x), x, x, x, x)"          "26" 
    "diff(y(x), x, x, x, x, x)"       "70" 
    "diff(y(x), x, x, x, x, x, x)"    "200"
0 Answers
Related