index must be a positive integer or logical.

12 Ansichten (letzte 30 Tage)
Jose
Jose am 19 Aug. 2014
Beantwortet: Image Analyst am 19 Aug. 2014
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

Akzeptierte Antwort

Jose
Jose am 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

Weitere Antworten (2)

Iain
Iain am 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 Kommentare
Cedric Gilbert
Cedric Gilbert am 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 am 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.

Melden Sie sich an, um zu kommentieren.


Image Analyst
Image Analyst am 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

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by