Cast variable to different data type


B = cast(A,newclass)
B = cast(A,'like',p)


B = cast(A,newclass) converts A to class newclass, where newclass is the name of a built-in data type compatible with A. The cast function truncates any values in A that are too large to map into newclass.

B = cast(A,'like',p) converts A to the same data type and sparsity as the variable p. If A and p are both real, then B is also real. Otherwise, B is complex.


collapse all

Convert Numeric Data Type

Convert an int8 value to uint8.

Define a scalar 8-bit integer.

a = int8(5);

Convert a to an unsigned 8-bit integer.

b = cast(a,'uint8');
ans =

Match Data Type and Complex Nature of p

Define a single precision vector p that is complex valued.

p = single([1+i 2]);

Define a 2-by-3 matrix of ones.

A = ones(2,3);

Convert A to the same data type and complexity (real or complex) as p.

B = cast(A,'like',p)
B =

   1.0000 + 0.0000i   1.0000 + 0.0000i   1.0000 + 0.0000i
   1.0000 + 0.0000i   1.0000 + 0.0000i   1.0000 + 0.0000i

Check the class of B.

ans =


See Also


Introduced before R2006a

Was this topic helpful?