R3E1W4
R3E1W4

Reputation: 129

How do I increase stepsize in MATLAB?

For my computing course, I am asked to solve an ODE, using Euler's method. My code runs, however, I am now asked the following:

"Increase N a number of times, according to N=100,200,400,800.... so you can obtain the answers y100,y200,y400,y800...."

Here's my code:

function [xar,yar] = eulsol(a,b,ybouco,N)
h=(b-a)/N;
T=a:h:b;
y(1)=ybouco;
for i = 100: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

Can someone help me with obtaining a nice table in MATLAB, which shows me the arrays x and y, according to an increasing N (100,200,400,800....)?

Upvotes: 0

Views: 165

Answers (1)

A. Renteria
A. Renteria

Reputation: 86

Let's define K as the number of steps. In your example, K=4 (N=100,200,400,800). If N=100,200,400,800,1600,3200 then K = 6

Note that the ith element of N correspond to 100*2^(i-1):

i = 1 => N = 100 * 2^(1-1) = 100
i = 2 => N = 100 * 2^(2-1) = 200
i = 3 => N = 100 * 2^(3-1) = 400

and so on...

So if you want to calculate for N=100,200,400,800, your code should be:

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

This answer if for creating the correct N inside the for loop, but you should review your code! As you can see: for i = 1, you have N = 100 and to calculate F(100) you need y(100), but you don't have y(100), just y(1). Maybe the correct answer is F(i) = -8*y(i) + 0.5*T(N) + (1/16); But again, want is T(N)?

Please, as noted by @Argyll , explain what you want, you shouldn't expect people to understand your question from a wrong code.

Upvotes: 2

Related Questions