Single Precision Math
This example shows how to perform arithmetic and linear algebra with single precision data. It also
shows how the results are computed appropriately in single-precision or double-precision, depending
on the input.
Create Double Precision Data
Let's first create some data, which is double precision by default.
Ad = [1 2 0; 2 5 -1; 4 10 -1]
Ad = 3×3
1
2
0
2
5
-1
4
10
-1
Convert to Single Precision
We can convert data to single precision with the single function.
A = single(Ad); % or A = cast(Ad,'single');
Create Single Precision Zeros and Ones
We can also create single precision zeros and ones with their respective functions.
n = 1000;
Z = zeros(n,1,'single');
O = ones(n,1,'single');
Let's look at the variables in the workspace.
whos A Ad O Z n
Name
Size
Bytes Class
Attributes
A
3x3
36 single
Ad
3x3
72 double
O
1000x1
4000 single
Z
1000x1
4000 single
n
1x1
8 double
We can see that some of the variables are of type single and that the variable A (the single precision
version of Ad) takes half the number of bytes of memory to store because singles require just four
bytes (32-bits), whereas doubles require 8 bytes (64-bits).
Arithmetic and Linear Algebra
We can perform standard arithmetic and linear algebra on singles.
B = A'
% Matrix Transpose
B = 3x3 single matrix
1
2
4
4 Numeric Classes
4-26
This example shows how to perform arithmetic and linear algebra with single precision data. It also
shows how the results are computed appropriately in single-precision or double-precision, depending
on the input.
Create Double Precision Data
Let's first create some data, which is double precision by default.
Ad = [1 2 0; 2 5 -1; 4 10 -1]
Ad = 3×3
1
2
0
2
5
-1
4
10
-1
Convert to Single Precision
We can convert data to single precision with the single function.
A = single(Ad); % or A = cast(Ad,'single');
Create Single Precision Zeros and Ones
We can also create single precision zeros and ones with their respective functions.
n = 1000;
Z = zeros(n,1,'single');
O = ones(n,1,'single');
Let's look at the variables in the workspace.
whos A Ad O Z n
Name
Size
Bytes Class
Attributes
A
3x3
36 single
Ad
3x3
72 double
O
1000x1
4000 single
Z
1000x1
4000 single
n
1x1
8 double
We can see that some of the variables are of type single and that the variable A (the single precision
version of Ad) takes half the number of bytes of memory to store because singles require just four
bytes (32-bits), whereas doubles require 8 bytes (64-bits).
Arithmetic and Linear Algebra
We can perform standard arithmetic and linear algebra on singles.
B = A'
% Matrix Transpose
B = 3x3 single matrix
1
2
4
4 Numeric Classes
4-26
