Unknown glitch when finding an exact array value
3 views (last 30 days)
Show older comments
Samuel Gaspar
on 12 Nov 2020
Commented: Star Strider
on 12 Nov 2020
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
0 Comments
Accepted Answer
Star Strider
on 12 Nov 2020
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 Comments
Star Strider
on 12 Nov 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.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!