Unknown glitch when finding an exact array value

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

 Respuesta aceptada

Star Strider
Star Strider el 12 de Nov. de 2020

0 votos

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 comentarios

Samuel Gaspar
Samuel Gaspar el 12 de Nov. de 2020
Thanks! Defining t using linspace also appears to fix it.
Star Strider
Star Strider el 12 de Nov. de 2020
As always, my pleasure!
The linspace function produces more exact elements, however it requires a bit of forethought to produce exact integers with it.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Productos

Versión

R2020a

Preguntada:

el 12 de Nov. de 2020

Comentada:

el 12 de Nov. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by