Index exceeds matrix dimensions

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?

Answers (1)

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.

This question is closed.

Asked:

on 9 Apr 2019

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!