How to resolve floating point numbers in if condition?

6 views (last 30 days)
I want to find max(cor). And when I do this:
for k = 1 : length(theFiles) % files are alreaady defined in code
p=0;
t=0;
for q=.1:20
if(arr(p)<1)
if(arr(p)>0.85)
cor(t)=arr(p); %cor(t) already defined in code
t=t+1;
end
end
p=p+1;
end %end of q loop
[val1,idx1] = max(cor) ;
idx2 = find(abs(arr-val1)<10^-3) ;
end % end of k loop
Again, it shows idx2 for some of the inputs when printed, but for some it shows blank. such as:
idx2 is
I don't know whether it is relevent information or not, but the file for which the output above is shown(That is blank idx2), has the minimum of all the val1 of other files, such as, the values of val1 for other files are as follows:
9.554158e-01
9.634148e-01
9.750799e-01
9.841079e-01
9.753829e-01
9.764703e-01
Where the value for blank idx2, the val1 is:
9.243360e-01
How do I fix it?
  15 Comments
Tawsif Mostafiz
Tawsif Mostafiz on 6 Jul 2021
Edited: Tawsif Mostafiz on 6 Jul 2021
@dpb mx=max(cor). It is the single maximum value of cor which is the values found when arr >0.85 and <1.
dpb
dpb on 6 Jul 2021
Edited: dpb on 6 Jul 2021
>> load work mx arr
>> whos arr mx
Name Size Bytes Class Attributes
arr 1x41 328 double
mx 0x0 0 double
>> ixa=find(arr==mx,1)
Error using ==
Matrix dimensions must agree.
>>
mx is empty so you haven't solved all the problems of including the case where there may not be any values within the bounds selected.
>> MN=0.85;MX=1;
>> cor=arr((arr>MN) & (arr<(MX)));
>> whos cor
Name Size Bytes Class Attributes
cor 1x0 0 double
>> isempty(cor)
ans =
logical
1
>> ixa=find(arr==mx,1)
Error using ==
Matrix dimensions must agree.
>>
So, == also fails if both are empty.
With the data for this particular sample, there are no values that satisfy the condition; you need to code for that possibility.
That's where a try...catch...end block could be useful
try
ixa=find(arr==mx,1);
catch ME
ixa=0;
end
You'll have to then also ensure you don't try to use the zero-valued index later on, of course....or have some other way of handling the case.
ADDENDUM:
But, at least with the data we can prove what happened...see how easy that was??? :)

Sign in to comment.

Answers (0)

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!