R3E1W4
R3E1W4

Reputation: 129

Euler's method in MATLAB: code doesn't work

For my computing course, I am given the following function: y'(x) = -8y(x) + 0.5x + 1/16 and an initial value of y(0)=2.

Now, I am asked to solve this equation by using Euler's method, in MATLAB.

My code should give an output of 2 arrays: xar and yar, in which I see the x-values vs. the y-values, however, if I run my code, it says: "undefined variable x". Here's my code:

function [xar,yar] =  Euler(a,b,ybouco,N)
% a is the lower limit
% b is the upper limit
% ybouco is the initial value
% N is the number of intervals

a=0;
b=3;
ybouco=2;
N=10;
h=(b-a)/N;
T=a:h:b;

y(1)=ybouco;

f = @(x) -8*y(x) + 0.5x + (1/16);
y(x) = 2*exp(-8*x)+(1/16)*x;

for i = 1:N

y (i+1) = y(i)+h*f(T(i));

end

end

Can someone explain what is wrong with my code??

Upvotes: 1

Views: 473

Answers (2)

Cris Luengo
Cris Luengo

Reputation: 60474

The error message is because you have an assignment

y(x) = 2*exp(-8*x)+(1/16)*x;

where x is not defined. The x in y(x) indexes into the array y.

Maybe you intended to write

y = @(x) 2*exp(-8*x)+(1/16)*x;

to define an anonymous function. But that would clash with the array y you have already defined. Maybe just delete this line?

Also,

h=(b-a)/N;
T=a:h:b;

can be better written as

T = linspace(a,b,N);

Upvotes: 1

Mehrdad Zandigohar
Mehrdad Zandigohar

Reputation: 251

First of all, note that assigning argument parameters in the function block is wrong! (i.e. a,b,ybouco and N) should be passed through argument by calling the function. There is no use in writing arguments to be assigned by user beside assigning them in the script manually.

One way is to call the function and assign the value in the command window like below:

[x,y]=Euler(0,3,2,10)

where a=0, b=3, ybouco=2 and N=10 was passed to the function as an input and x and y returned by the function as output.

Plus, when you are solving an ODE numerically it means you do not know y analytically.

So you should omit the assigning part of the code and do a little change like below:

function [xar,yar] =  Euler(a,b,ybouco,N)
h=(b-a)/N;
T=a:h:b;
y(1)=ybouco;
for i = 1:N
    f(i) = -8*y(i) + 0.5*T(i) + (1/16);
    y(i+1) = y(i)+h*f(i);
end
xar=T;
yar=y;
end

Then by calling the function in the command window, you will get the following results:

x =

  Columns 1 through 8

         0    0.3000    0.6000    0.9000    1.2000    1.5000    1.8000    2.1000

  Columns 9 through 11

    2.4000    2.7000    3.0000

y =

  Columns 1 through 8

    2.0000   -2.7813    3.9575   -5.4317    7.7582  -10.6627   15.1716  -20.9515

  Columns 9 through 11

   29.6658  -41.1533   58.0384

You can also plot the result and get the following graph:

enter image description here

If you increase N from 10 to 100 you will have more accurate results and a smooth graph like below:

enter image description here

Upvotes: 2

Related Questions