Search code examples
matlabfloating-pointscanffractions

How to determine if input is a ratio or float in Matlab?


I need to batch-process text files of mixed units, i.e. integer ratios and floating-point numbers (which are scaled logarithmic approximations of unknown rational or irrational numbers). How can Matlab detect which input is which? Would scanning for a '.' or '/' character be best?

252.63

4/3

757.89

2/1

In this example I recognize that the numbers represent values in increasing order (but in mixed units, which is typical in my field of study), and I would process 252.63 and 757.89 differently from 4/3 and 2/1.

I haven't found a function in Matlab like isa(x, 'rat') where x is any one of the lines in the above list, and 'rat' would be ratio.


Solution

  • Matlab can search strings for specific characters pretty trivially.

    slashmask     = str == '/'; % returns false for every character in str that's not a slash, and true for every one that is.
    slashdetected = any(slashmask); % returns false if no character is a slash.
    

    if all you need to do is take the ratio and evaluate it and then use it in the same way as the floats, you could just simply use the "eval" function to retrieve the float equivalent.