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.

답변 (2개)

John D'Errico
John D'Errico 2018년 11월 30일

0 개 추천

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

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 2018년 11월 30일
편집: Torsten 2018년 11월 30일
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.

댓글을 달려면 로그인하십시오.

James Tursa
James Tursa 2018년 11월 30일
편집: James Tursa 2018년 11월 30일

0 개 추천

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.

카테고리

도움말 센터File Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

질문:

2018년 11월 29일

편집:

2018년 11월 30일

Community Treasure Hunt

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

Start Hunting!

Translated by