Im having trouble with the forward eulers method.

This is the Diff eq that was given to solve.
x'(t) = 4x(t) -3t+2 x(0)=1 t= [0,.5] with a step size of .1
I understand the basic code for the Eulers mehtod but when I enter x(0)=1 MATLAB says array indicies must be positive and logical values.
Not really sure what to do.

Respuestas (2)

John D'Errico
John D'Errico el 30 de Nov. de 2018

0 votos

An array or vector index indicates where in memory you want to stuff some information.
MATLAB uses a 1-based index scheme. So x(1) tells MATLAB to stuff something into the FIRST element of a vector. What happens when you try to index with x(0)?
The first element IS the first element. So the zero'th element does not exist in MATLAB, and an error happens. (Some programming languages use a 0-based index, but that is not true for MATLAB.)
By the way, I would bet that your next error will be when you try to access x(0.1). Again, you can't stuffsomething into the 0.1'th element of a vector. It won't fit. But that will be your NEXT error. I guess we'll just need to worry about that when you get past this first error.

2 comentarios

Thank you that makes sense but im not sure on how to solve the problem when I am only given that one initial condition of x(0)=1.
Torsten
Torsten el 30 de Nov. de 2018
Editada: Torsten el 30 de Nov. de 2018
x(0) = 1 in the problem formulation does not mean that the first element of a vector x is equal to 1, but that the solution x at time t=0 equals 1.

Iniciar sesión para comentar.

James Tursa
James Tursa el 30 de Nov. de 2018
Editada: James Tursa el 30 de Nov. de 2018

0 votos

A basic outline would be:
dt = _____; % the step size, you fill this in
n = _____: % number of steps, you fill this in
x = zeros(1,n); % pre-allocate x
t = zeros(1,n); % pre-allocate time
t(1) = 0; % the first time value, using 1-based indexing
x(1) = 1; % the first x value at time t(1), using 1-based indexing
for k=1:n-1
x(k+1) = _____; % you fill this in
t(k+1) = _____; % you fill this in
end
Alternatively, you could use the linspace( ) function to pre-fill the t vector instead of iteratively filling in the values.
Just remember to index into the x and t vectors on the rhs of the assignments in the loop. I.e., you should be using x(k) and t(k) on the rhs, not simply x and t.

Categorías

Preguntada:

el 29 de Nov. de 2018

Editada:

el 30 de Nov. de 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by