Unknown glitch when finding an exact array value

조회 수: 10 (최근 30일)
Samuel Gaspar
Samuel Gaspar 2020년 11월 12일
댓글: Star Strider 2020년 11월 12일
All,
I am experiencing a strange glitch within the following code. I understand this was probably not the best way to execute what i was looking to do, and have since re-worked the code to avoid this error.
In the following code, Matlab is failing to recognize t=0.3 within the t array. That is, T=find() skips over 0.3000 when the step size h is 0.05 or 0.025 in the t array. T=find() DOES correctly find 0.3000 in the t array when the step size h is <=0.01. I can also call for an indexing array:
a=t==0.3;
that fails to find the index of 0.3 within t, when the step size h is 0.05 or 0.025. Again, this indexing array works with step size h=0.01.
This has been verrified to happen on two machines running two different releases of Matlab. Mine is R2020a
clc
clear
h=0.05;%when h <=0.01, the error does not occur
t=0:h:2;
y=zeros(size(t));
y(1)=1;
n=numel(y);
%syms x real
%Y(x)=0.25*x-(3/16)+(19/16)*exp(4*x); %actual solution
for i=1:n-1
f=1-t(i)+4.*y(i);
y(i+1) = y(i)+h*f;
end
T=find(t==0.1 | t==0.2 | t==0.3 | t==0.4 | t==0.5 | t==1 | t==1.5 | t==2);
for j=1:numel(T)
fprintf('y=%.6f\n',y(T(j)));
end
%plot(t,y,t,Y(t)); grid on
The code following the first loop was re-written and will properly find t=0.3 with step size h=0.05:
inds = [0.1,0.2,0.3,0.4,0.5,1,1.5,2];
T=zeros(size(inds));
for i=1:length(inds)
T(i)=find(t>=inds(i),1);
end
for j=1:length(T)
fprintf('y=%.5f\n',y(T(j)));
end

채택된 답변

Star Strider
Star Strider 2020년 11월 12일
That reflects the way the colon operator works to calculate the vector elements. See the documentation section on Floating-Point Numbers for an illustrative discussion.
Include a tolerance with find, as you did in the version that worked.
  댓글 수: 2
Samuel Gaspar
Samuel Gaspar 2020년 11월 12일
Thanks! Defining t using linspace also appears to fix it.
Star Strider
Star Strider 2020년 11월 12일
As always, my pleasure!
The linspace function produces more exact elements, however it requires a bit of forethought to produce exact integers with it.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by