Attempted to access y(15); index must be a positive integer or logical.

조회 수: 17 (최근 30일)
Cloris
Cloris 2014년 9월 4일
댓글: Cloris 2014년 9월 5일
Here is my code:
clear;
for t=0:0.01:4;
i=t*100+1;
if t<2
y(i)=3.5*exp(-t/2)*cos(2*pi*t);
T(i)=t;
else
y(i)=3.5*exp(-1)*cos(6*pi*t);
T(i)=t;
end
plot(T, y,'g','linewidth',2)
end
As you can see, I want to plot the piecewise function. To store y and t as vectors, I created an index i . But when i equals 15, it reports 'Attempted to access y(15); index must be a positive integer or logical.' But when t=0.14, i=15 and it makes sense, I think.So how can it be wrong? Please help me with the problem. Thanks!

채택된 답변

Roger Stafford
Roger Stafford 2014년 9월 4일
편집: Roger Stafford 2014년 9월 4일
If you do a high accuracy check on what you think is an i-value of 15, you will find that it is off from the exact integer 15 by 1 bit or so at its least significant end. That is caused by the fact that since your computer is using binary numbers, it cannot represent 0.01 exactly, and multiplying this number by an integral multiple of 100, which you are doing, does not always yield an integer. Welcome to the world of binary numbers!
Instead of your "for t=0:0.01:4; i = t*100+1;" you should write:
for i = 1:401
t = (i-1)/100; % <-- or else t = linspace(0,4,401) or t = 0:0.01:4
etc.

추가 답변 (1개)

Iain
Iain 2014년 9월 4일
Its a floating point error down at the 15th significant figure. If you simply round "i", it'll work.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by