3

What does this call to typecast do in MATLAB?

y=typecast(x,'single');

what does it mean? When I run typecast(3,'single') it gives 0 2.1250.

I don't understand what that is.

I am trying to convert this to Java, how can I do that?

From the MATLAB manual:

single - Convert to single precision

Syntax

B = single(A)

Description

B = single(A) converts the matrix A to single precision, returning that value in B. A can be any numeric object (such as a double). If A is already single precision, single has no effect. Single-precision quantities require less storage than double-precision quantities, but have less precision and a smaller range.

SCFrench
  • 8,244
  • 2
  • 31
  • 61
Inv3r53
  • 2,929
  • 3
  • 25
  • 37

2 Answers2

4

typecast reinterprets the bytes used to represent a value of one type as if those same bytes were representing a different type. For example, the constant 3 in MATLAB is an IEEE double-precision value, meaning it takes 8 bytes to store it. Those eight bytes in this case are

40 08 00 00 00 00 00 00

A value of type single in MATLAB is an IEEE single-precision value, meaning it takes only 4 bytes to store it. So the eight bytes of the double will map to two 4-byte singles, those being

40 08 00 00, and
00 00 00 00

It turns out that 40 08 00 00 is the single-precision representation of the value 2.125, and as you might guess, 00 00 00 00 is the single-precision representation of 0. I believe they come out in reverse order due to the endian-ness of the machine, and on a big-endian machine I think you'd get 2.125 0 instead.

In C++ this would be something like a reinterpret_cast. In Java, there doesn't appear to be as direct a mapping, but the answers to this Stack Overflow question discuss some alternatives such as Serialization.

Community
  • 1
  • 1
SCFrench
  • 8,244
  • 2
  • 31
  • 61
1

From running help typecast it looks like it changes the datatype, but keeps the bit assignment the same, whereas single( ) keeps the number the same, but changes the bit arrangement.

If I understand it, you could think of it like you have two boxes, each containing up to 8 balls. Lets say, box 1 is full, whilst box 2 contains 3 balls. We now typecast this into a system where a box holds 4 balls.

This system will need three boxes to hold our balls. So we have boxes 1 and 2 which are full. Box 3 contains 3 balls.

So you'd have [8,3] converted to [4,4,3].

Alternatively, if you converted the number into our new system in the same way as single( ) works (e.g. for changing an int8 to a single), you'd change the number of balls, not the container.

n00dle
  • 5,949
  • 2
  • 35
  • 48