Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing variable type in MATLAB

Tags:

types

matlab

I have variables which are of double type I want them to be float. Is there a way to force a variable to be float and not double, also, Is there a way to do it in some global way for all functions and sub functions with few lines at the start of the main function? I have many functions and they use many temporary variables and create variables that they return. Going over all of my functions and changing them will be very difficult.

My rational for this request:

I'm writing the MATLAB program in order to simulate an algorithm which I'll then implement in hardware, I want to make sure that using 32bit as the size of my signals will not cause calculation errors.

like image 828
SIMEL Avatar asked Feb 02 '11 10:02

SIMEL


People also ask

How do you change the type of a variable in MATLAB?

In the Modeling tab, in the Design section, click Model Explorer. In the Model Hierarchy pane select the MATLAB Function block. Click the variable you want to modify. Select the data type from the Type property.

What is the default variable type in MATLAB?

By default, MATLAB® stores all numeric variables as double-precision floating-point values. Additional data types store text, integer or single-precision values, or a combination of related data in a single variable.

How do I convert one data type to another in MATLAB?

You must specify newclass as a character vector or a string of lowercase letters that represents the new data type. For example, to convert a double value to the int8 data type, you must use cast(1.234,"int8") . The command cast(1.234,"Int8") now errors.


2 Answers

Using B=single(A) as suggested by @cbz, or defining arrays as SINGLE, such as by calling B=zeros(3,3,'single') creates "floats" in Matlab.

There is no way to globally turn Matlab into a "float" environment. Although most lower-level functions are implemented for single as well (with a few exceptions, for example those mentioned in the help to DOUBLE), many high-level builtin functions will only work with double.

In other words, you'll have to manually define your variables as single, you'll have to periodically check that the variables haven't been quietly converted to double, and in the end, your code might not work if it needs a function that isn't implemented for single yet.

like image 54
Jonas Avatar answered Sep 29 '22 00:09

Jonas


The MATLAB equivalent to 'float' is 'single. You can convert using

B = single(A).

That said, your assumption that this amounts to 32-bit might need revisiting. It's not as simple as that.

like image 20
cbz Avatar answered Sep 29 '22 00:09

cbz