Unknown glitch when finding an exact array value

9 ビュー (過去 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 Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by