Euler's method to solve an ODE using Matlab

64 Views Asked by At

I am trying to implement the following script to solve an ODE of the form $\ y'=f(t,y)\ $ for $\ a<t<b$:

function [t,y] = Euler(fstring,a,b,y0,N)
h = (b-a)/N; % defines h
t = a:h:b; % defines the array t0, t1, ..., tN
d = length(y0); % defines the size of y0
y0 = y0(:); % ensures that y0 is a column vector
y = zeros(1,N+1); % allocate the output array y
y(:,1) = y0; % assign y0 to the first column of y
for n = 0:N-1
    tn=h*n;
    y(n+2) = y(n+1)+h*fstring(tn,y(n+1));
end

However, the following error is displayed:

"Unable to perform assignment because the size of the left side is $1$-by-$1$ and the size of the right side is $2$-by-$1$.

Error in Euler (line $30$) y(:,1) = y0; % assign y0 to the first column of y".

How can this be resolved?

1

There are 1 best solutions below

1
On BEST ANSWER

This is not really on-topic.

Matlab interprets y(n) as the $n$th element in the unstructured data of y, counting down along columns first.

What you want is a computation and assignment with the column vectors of y as matrix/list of vectors. For that you need to write

y(:,n+2) = y(:,n+1)+h*fstring(tn,y(:,n+1));

You might want to check if the last element of t is actually b. Also, why not just loop for n=1:N?