MATLAB: Euler Method array problem ‘Unable to perform assignment because the left and right sides have a different number of elements.’

euleriteration

Hello everyone.
I'm new to matlab and tried to create euler method code on my own.
function [t,y] = eulerian13th(t0,y0,n,b,a)
t= t0
for i = 1:n
f = (-t)*y0
h = (b - a)/n
t(i+1) = h + t0
y(i+1) = y0 + h*f
t0 = t(i+1);
y0 = y(i+1);
hold on;
plot(t,y);
grid on;
chuzkun = [t;y];
fprintf('%6s %12s\n','t','y');
fprintf('%6.f %12.f\n',chuzkun);
end
end
This is the line of my code that i have a problem with
y(i+1) = y0 + h*f
I know what my problem is coming from the function itself, because it has (-t) and y0, when it only has y0, the error didn't appear.
f = (-t)*y0
i have done read some forum regarding this problem, its because array and cell probem, but i still cant find the solution.
Hopefully i can get the answer and sugestion from you all.
Thank you very much.

Best Answer

't' is a vector, Change the line
f = (-t)*y0
to
f = (-t0)*y0
Also, plotting inside for loop like your code is very efficient and you will find that your code will run very slow. The proper way is like this
function [t,y] = eulerian13th(t0,y0,n,b,a)
t= t0
f = figure();
ax = axes();
hold(ax);
grid on
l = line(nan, nan);
for i = 1:n
f = (-t0)*y0
h = (b - a)/n
t(i+1) = h + t0
y(i+1) = y0 + h*f
t0 = t(i+1);
y0 = y(i+1);
l.XData(end+1) = t0;
l.YData(end+1) = y0;
chuzkun = [t;y];
fprintf('%6s %12s\n','t','y');
fprintf('%6.f %12.f\n',chuzkun);
end
end
Related Question