0

I wrote the following code. The problem is that at the specific value of 0.288, T turns to zero for no obvious reason. Any explanation? The weird thing is that when I change it to 0.28 it works fine.

   time=(0:0.002:0.560);
   time_f=reshape(time,281,1);

   time1=0;
   time2=0;
   for i=1:1
       for j=1:281
           T=time_f(j,i);

           if (i==1) && (T==0.288);
              time1=T;
           end

        end
    end

If you test the code you will find that the time1 value will be zero and if you change T to 0.28 it will work.

horchler
  • 18,384
  • 4
  • 37
  • 73

2 Answers2

2

The answer is simple

>> time_f(time_f == 0.288)

ans =

   Empty matrix: 0-by-1

Your matrix doesn't contain the value 0.288

This is due to float precision, so instead of being 0.288, your value is 0.287999999 for example.

Just use roundn, which round to a specified number of significant digits

>> time_f = roundn(time_f,-3);
>> find(time_f == 0.288)

ans =

   145

If you don't have Mapping toolbox you can do

>> time_f = round(time_f * 1000) / 1000
Ikaros
  • 1,048
  • 11
  • 19
1

You are using floating point arithmetic, which has certain precision errors. Your matrix does not contain exactly the value 0.288.

Daniel
  • 36,610
  • 3
  • 36
  • 69
  • It contains it for sure, I can see the value by myself. It is logic because i created a matrix from 0 to 0.56 every 0.002 !!! – user3049408 Jul 04 '15 at 14:25
  • 1
    No it does not. There is a small precision error and you have a value slightly off the expected value. Get the value from your matrix and calculate the difference, it is not zero – Daniel Jul 04 '15 at 14:29
  • 1
    Thanks so much Daniel. I got the point and i fixed it. – user3049408 Jul 04 '15 at 14:43