How to create a function that can solve and graph Euler's equations

3 views (last 30 days)
Hey guys, I'm trying to create a function that can take a differential equation and show the numerical solution via graph using Euler's Method. I have the code and it works on it's own. I just can't figure out how to get it to a function format. I tried looking at the help page but it only confused me more. I know you need to give the function inputs in order for you to get outputs, I just can't figure out where they go inside the function. Here is the code, hopefully this helps explain it.
%Section 1: Single Differential Equations.
h=0.1; % step's size
N=10; % number of steps
y(1)=1;
for n=1:N
y(n+1)= y(n)+h*(-6*y(n));
x(n+1)=n*h;
end
plot(x,y); %plots the first soltuion
hold on
h1=0.001; % step's size
N1=1000; % number of steps
y1(1)=1;
for n1=1:N1
y1(n1+1)= y1(n1)+h1*(-6*y1(n1)); %-6y1 is the differential equation, dy/dx = -6y. I had to use y1 because y is already used.
x1(n1+1)=n1*h1;
end
plot(x1,y1); % plots the second numerical solution
hold on
x3=0:0.001:1;
y3=exp(-6.*x3); %This is the solution to dy/dx = -6y
plot(x3,y3); % plots the exact solution to this differential equation
legend('h=0.1','h=0.001','Exact');

Accepted Answer

KALYAN ACHARJYA
KALYAN ACHARJYA on 22 Sep 2019
I have the code and it works on it's own. I just can't figure out how to get it to a function format.
function plot_test()
data=input('Please enter how many numerical solution going to plot: ');
for i=1:data
h=input('Enter the Step size: ');
N=input('Number of Steps: ');
y(1)=1;
for n=1:N
y(n+1)= y(n)+h*(-6*y(n));
x(n+1)=n*h;
end
plot(x,y); %plots the first soltuion
hold on;
end
x3=0:0.001:1;
y3=exp(-6.*x3); %This is the solution to dy/dx = -6y
plot(x3,y3); % plots the exact solution to this differential equation
legend('h=0.1','h=0.001','Exact');
end
Command Window:
345.png
Hope it helps!

More Answers (0)

Categories

Find more on Mathematics in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!