" Attempted to access t(2); index out of bounds because numel(t)=1."

3 次查看(过去 30 天)
Need your help once again :) I am getting this error which I dont know what it means. I am trying to write a code on Euler's method for my homework. " Attempted to access t(2); index out of bounds because numel(t)=1."
%%Tasks
clc, clear all
func = @(t,x) -t.*x;
t = 0; %Initial Value
x = 1; %Initial Value
h = 0.1; %Step size
N = 10;
tarrays = zeros(1,N)
xarrays = zeros(1,N)
for i = 1:N
x(i+1) = x(i) + h.*func(t(i),x(i));
tarrays = t(i)
xarrays = x(i+1)
end

回答(3 个)

Matt J
Matt J 2014-8-19
It means you've done something like this,
>> t=1:5; a=t(6)
Attempted to access t(6); index out of bounds because numel(t)=5.
Use the dbstop command and its cousins to locate the error.

Jose
Jose 2014-8-19
I still cant figure it out :(
  5 个评论
Matt J
Matt J 2014-8-19
编辑:Matt J 2014-8-19
It just says "index exceeds matrix dimensions" I dont know how and where
The error message tells you where the error is (line 15). It also tells you why (my Answer above).
But you clearly didn't use DBSTOP or refer to the other debugging commands I pointed you to if you haven't reached a K>> prompt.

请先登录,再进行评论。


Guillaume
Guillaume 2014-8-19
编辑:Guillaume 2014-8-19
There are lots of problems with your loop:
x(i+1) = x(i) + h.*func(t(i),x(i));
is the cause of the error. You've defined t as a scalar (t=0; %Initial Value) and then access it as an array. t only has one element, therefore t(i) when i==2 is invalid.
tarrays = t(i)
Even if t was array, t(i) would be a scalar. You would then overwrite your predefined tarrays with that scalar. Each loop tarrays would just be a scalar containing t(i). At the end tarrays would just be t(N).
xarrays = x(i+1)
Same problem as with tarrays.
  1 个评论
Jose
Jose 2014-8-19
编辑:Jose 2014-8-19
so I rewrote
%%Tasks
clc, clear all
%func = @(t,x) -t.*x;
func = @(t,x) sinh(x ./ (t+1));
% func = @(t,x) (t*x.^2)*cos(x.^2);
t0 = 1; %Initial Value
x = 1; %Initial Value
h = 0.1; %Step size
N = 10;
tarrays = zeros(1,N)
xarrays = zeros(1,N)
for i = 1:N
t = t0
x(i+1) = x(i) + (h*func(t(i),x(i)))
xarrays = x
tarrays = t
end
I am not sure what to do about your first statement though.

请先登录,再进行评论。

标签

Community Treasure Hunt

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

Start Hunting!

Translated by