index must be a positive integer or logical.

조회 수: 18 (최근 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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by