Im having trouble with the forward eulers method.
Show older comments
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.
Answers (2)
John D'Errico
on 30 Nov 2018
0 votes
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.
James Tursa
on 30 Nov 2018
Edited: James Tursa
on 30 Nov 2018
0 votes
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.
Categories
Find more on Multidimensional Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!