Casting fi Objects

Overwriting by Assignment

Because MATLAB® software does not have type declarations, an assignment like A = B replaces the type and content of A with the type and content of B. If A does not exist at the time of the assignment, MATLAB creates the variable A and assigns it the same type and value as B. Such assignment happens with all types in MATLAB—objects and built-in types alike—including fi, double, single, int8, uint8, int16, etc.

For example, the following code overwrites the value and int8 type of A with the value and int16 type of B:

A = int8(0);
B = int16(32767);
A = B 

A =

  32767

class(A) 

ans =

int16

Ways to Cast in MATLAB® Software

You may find it useful to cast data into another type—for example, when you are casting data from an accumulator to memory. There are two ways to cast data in MATLAB:

Casting by Subscripted Assignment

The following subscripted assignment statement retains the type of A and saturates the value of B to an int8:

A = int8(0);
B = int16(32767);
A(:) = B

A =

  127

class(A)

ans =

int8

The same is true for fi objects:

fipref('NumericTypeDisplay', 'short', 'FimathDisplay', 'none');
A = fi(0, true, 8, 0);
B = fi(32767, true, 16, 0);
A(:) = B

A =
 
   127
      s8,0

Casting by Conversion Function

You can convert from one data type to another by using a conversion function. In this example, A does not have to be predefined because it is overwritten.

B = int16(32767);
A = int8(B)

A =

  127

class(A)

ans =

int8

The same is true for fi objects:

B = fi(32767, true, 16, 0)
A = fi(B, 1, 8, 0)

B =
 
       32767
      s16,0
 
A =
 
   127
      s8,0

Using a numerictype Object in the fi Conversion Function

Often a specific numerictype is used in many places, and it is convenient to predefine numerictype objects for use in the conversion functions. Predefining these objects is a good practice because it also puts the data type specification in one place.

T8 = numerictype(1,8,0)

T8 =
 

          DataTypeMode: Fixed-point: binary point scaling
                Signed: true
            WordLength: 8
        FractionLength: 0

T16 = numerictype(1,16,0)

T16 =
 

          DataTypeMode: Fixed-point: binary point scaling
                Signed: true
            WordLength: 16
        FractionLength: 0

B = fi(32767,T16)

B =
 
       32767
      s16,0

A = fi(B, T8)

A =
 
   127
      s8,0
  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS