index must be a positive integer or logical.

7 ビュー (過去 30 日間)
Jose
Jose 2014 年 8 月 19 日
回答済み: Image Analyst 2014 年 8 月 19 日
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

採用された回答

Jose
Jose 2014 年 8 月 19 日
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

その他の回答 (2 件)

Iain
Iain 2014 年 8 月 19 日
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 件のコメント
Cedric Gilbert
Cedric Gilbert 2014 年 8 月 19 日
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 2014 年 8 月 19 日
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.

サインインしてコメントする。


Image Analyst
Image Analyst 2014 年 8 月 19 日
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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by