# Math Help - Euler Method

1. ## Euler Method

Hi,
Im trying to write a code that will perform eulers method without using the inbuilt matlab functions.

What im struggling to manage is how to get it too work for any function (as in; i don't want to explicitly state what the variables are [x and y]). I think ive managed to make the values of x and y to change after each iteration, although im not sure, but i can't manage to get the inline function to work or give the correct answer.

Here's my code so far

h=pi/8 %step value (seconds)
y=pi/4 %initial value
x=pi/4 %intial value
for i=1:1:10
f=inline('y + (2.*(x.^2).*cos(2.*x))./x','s')
g=f(y,x)
y= y + f(y,x)*h
x=x+(pi/8)
end
If someone could help i would be ever so grateful

Code:
h=pi/8 %step value (seconds)
y=pi/4 %initial value
x=pi/4 %intial value

for i=1:1:10
f=inline('y + (2.*(x.^2).*cos(2.*x))./x','s')
g=f(y,x)
y= y + f(y,x)*h
x=x+(pi/8)
end
1. Take the inline declaration out of the loop

2. Always explicity declare the vatiable names in the inline.

3. Remove all lines that do nothing.

4. Do not use a variable to hold a value then explicity code that value somewhere, use the variable.

So lets try:

Code:
h=pi/8 %step value (seconds)
y=pi/4 %initial value
x=pi/4 %intial value

f=inline('y + (2.*(x.^2).*cos(2.*x))./x','y','x');

for i=1:1:10

y= y + f(y,x)*h;
x=x+h;

end
CB

4. When i try to plot this on a graph it will only plot the final point for some reason. Could anyone shed any light on this? Why isn't it plotting each value of x against the value of y?

h=pi/8 %step value (seconds)
y=pi/4 %initial value
x=pi/4 %intial value

f=inline('y + (2.*(x.^2).*cos(2.*x))./x','y','x');

for i=1:1:10

y= y + f(y,x)*h
x=x+h

end
plot(x,y)

5. Originally Posted by p123nky
When i try to plot this on a graph it will only plot the final point for some reason. Could anyone shed any light on this? Why isn't it plotting each value of x against the value of y?
Because that is all you have calculated, you will need to store the intermediate values to plot them.

CB

6. How would i go about this? i presumed (wrongly of course) that it was saving the values because it was giving me the values. There is obviously something missing in my knowledge of how this loop is working, could you please help explain