MATLAB Answers

Henk
0

Index exceeds matrix dimensions

Asked by Henk
on 9 Apr 2019
Latest activity Answered by James Tursa
on 9 Apr 2019
clear all; close all;
tend = 0.1;
h = 0.025;
n = tend/h; %number of timesteps
w = 1; %y(0)=1
wE = w;
t = 0;
for j = 1:n
wE = wE + h*(1+(t-wE)^2); %Forward Euler Method
t = t + h;
disp([num2str(t,10),' & ', num2str(wE,10), '\\']); %display every iteration
end
disp([ num2str(wE(2)-wE(1))]);
I want to display the difference between the first and the second iteration of the for loop, but I get the "Index exceeds matrix dimensions" error. What is wrong with this code?

  0 Comments

Sign in to comment.

1 Answer

Answer by James Tursa
on 9 Apr 2019

You don't index wE in your loop when you are doing the iterations, so each iteration overwrites the previous iteration. Looks like you need something like this:
wE(j+1) = wE(j) + h*(1+(t-wE(j))^2); %Forward Euler Method
t = t + h;
disp([num2str(t,10),' & ', num2str(wE(j+1),10), '\\']);
And consider pre-allocating wE.

  0 Comments

Sign in to comment.