Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing MATLAB to use `single` precision as default?

Tags:

matlab

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.

like image 203
Danijel Avatar asked Dec 12 '25 05:12

Danijel


2 Answers

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.

like image 185
craigim Avatar answered Dec 13 '25 19:12

craigim


You can convert any object A to single precision using A=single(A);

The Mathworks forums show that in your case: system-specific('precision','8'); should do it. Try this in the console or add at the top of your script.

like image 34
Celebrian Avatar answered Dec 13 '25 20:12

Celebrian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!