Is there a way to force MATLAB to use single
precision as default precision?
I have a MATLAB code, whose output I need to compare to C code output, and C code is written exclusively using floats
, no doubles
allowed.
Short answer: You can't.
Longer answer: In most cases, you can get around this by setting your initial variables to single. Once that's done, that type will (almost always) propagate down through your code. (cf. this and this thread on MathWorks).
So, for instance, if you do something like:
>> x = single(magic(4));
>> y = double(6);
>> x * y
ans =
4×4 single matrix
96 12 18 78
30 66 60 48
54 42 36 72
24 84 90 6
MATLAB keeps the answer in the lower precision. I have occasionally encountered functions, both built-in and from the FileExchange, that recast the output to be a double, so you will want to sprinkle in the occasional assert
statement to keep things honest during your initial debugging (or better yet put the assertion as the first lines of any sub-functions you write to check the critical inputs), but this should get you 99% of the way there.