I have made an array of doubles and when I want to use the find command to search for the indices of specific values in the array, this yields an empty matrix which is not what I want. I assume the problem lies in the precision of the values and/or decimal places that are not shown in the readout of the array.
command:
peaks=find(y1==0.8236)
array readout:
y1 =
Columns 1 through 11
0.2000 0.5280 0.8224 0.4820 0.8239 0.4787 0.8235 0.4796 0.8236 0.4794 0.8236
Columns 12 through 20
0.4794 0.8236 0.4794 0.8236 0.4794 0.8236 0.4794 0.8236 0.4794
output:
peaks =
Empty matrix: 1-by-0
I tried using the command
format short
but I guess this only truncates the displayed values and not the actual values in the array.
How can I used the find command to give an array of indices?
By default, each element of a numerical matrix in Matlab is stored using floating point double precision. As you surmise in the question
format shortandformat longmerely alter the displayed format, rather than the actual format of the numbers.So if
y1is created using something likey1 = rand(100, 1), and you want to find particular elements iny1usingfind, you’ll need to know the exact value of the element you’re looking for to floating point double precision – which depending on your application is probably non-trivial. Certainly,peaks=find(y1==0.8236)will return the empty matrix ify1only contains values like0.823622378...So, how to get around this problem? It depends on your application. One approach is to truncate all the values in
y1to a given precision that you want to work in. Funnily enough, a SO matlab question on exactly this topic attracted two good answers about 12 hours ago, see here for more.If you do decide to go down this route, I would recommend something like this:
Note that I use the
findcommand withy1Roundin integer form. This is because integers are stored exactly when using floating point double, so you won’t need to worry about floating point precision.An alternative approach to this problem would be to use
findwith some tolerance for error, for example:Which path you choose is up to you. However, before adopting either of these approaches, I would have a good hard look at your application and see if it can be reformulated in some way such that you don’t need to search for specific “real” numbers from among a set of “reals”. That would be the most ideal outcome.
EDIT: The code advocated in the other two answers to this question is neater than my second approach – so I’ve altered it accordingly.