index must be a positive integer or logical.

2 views (last 30 days)
I am getting the error : "Attempted to access x(1.01); index must be a positive integer or logical."
Help would be appreciated please :)
clc, clear all func = @(t,x) -t*x;
t = 0; x = 1; h = 0.01; N = 10 tarrays = zeros(1,N); xarrays = zeros(1,N);
for i = 1:h:N
x(i+1) = x(i) + h.*func(t(i),x(i));
tarrays = t(i)
xarrays = x(i+1)
end

Accepted Answer

Jose
Jose on 19 Aug 2014
Got the answer guys
I change the step into a length values of the steps :)
t = 0; %Initial Value
x = 1; %Initial Value
h = 0.1; %Step size
N = 10;
Nvec = [1:h:N];
step = length(Nvec);
tarrays = zeros(1,N)
xarrays = zeros(1,N)
for i = 1:step

More Answers (2)

Iain
Iain on 19 Aug 2014
The issue is that,
on the second time through the loop, i = 1.01, you need to make i into an integer.
I suggest having, instead of i and "i+1", you replace i with index, and set
index = (i-1)*1/h
  3 Comments
Cedric Gilbert
Cedric Gilbert on 19 Aug 2014
t = 0; x = 1; h = 0.01; N = 10
for i = 1:h:N
x(i+1) = x(i) +...
end
first occurence : x(2) = x(1) + ... second occurence: x(2.01) = x(1.01) + ... third occurence: x(2.02) = x(1.02) + ...
You can't specify a decimal number to index a matrix ! Doing as lain prescribe => x(i/h)
first occurence : x(0.01/0.01) => x(1) second occurence : x(0.02/0.01) => x(2) etc...
or add an other integer index into your loop.
Image Analyst
Image Analyst on 19 Aug 2014
index = (i-1)*1/h won't work. What happens when i equals 1? You can't have indexes with zero or fractional values. Try using a counter or use integer indexes and get the fractional numbers from that.

Sign in to comment.


Image Analyst
Image Analyst on 19 Aug 2014
I don't know exactly what you want to do, but this is closer, though it still doesn't work:
clc;
clear all
func = @(t,x) -t*x;
t = 0;
x = 1;
h = 0.01;
N = 10;
tarrays = zeros(1,N/h);
xarrays = zeros(1,N/h);
index = 1;
for i = 1:h:N
x(index + 1) = x(index) + h.*func(tarrays(index), i);
tarrays(index) = t(index)
xarrays(index) = x(index+1)
index = index + 1;
end

Tags

Community Treasure Hunt

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

Start Hunting!