Kahibaro
Discord Login Register

Data Types and Type Conversion

Overview of Data Types in MATLAB

MATLAB works with many types of data, not only numbers. Understanding the main data types helps you store information correctly and avoid confusing errors. Each variable in MATLAB has a specific class, such as double, single, char, or logical. You can always check the class of a variable with the function class.

For example, if you create a variable with

matlab
x = 3.5;
class(x)

MATLAB answers with double. This means x is a double precision floating point number.

MATLAB uses doubles as the default numeric type. Any time you write a numeric literal such as 1, 3.14, or -7.2, MATLAB creates a double unless you explicitly choose something else.

Some data types are numeric, meaning they support arithmetic operations in a natural way, and some are nonnumeric, such as text or containers. Although many different types exist, beginners usually work mostly with double, logical, and simple text types.

Numeric Data Types

Numeric data types represent numbers that you can use in calculations. The most common numeric types in MATLAB are double, single, and several integer types.

The double type is the standard choice. It stores real or complex numbers using double precision. This precision is enough for most engineering and scientific work. Operations between doubles, and between a double and a literal number, usually behave as you expect.

MATLAB also supports single precision numbers, with class single. They use less memory but offer less precision. To create a single precision variable, you can write

matlab
a = single(5);
class(a)

Now a is single precision. If you mix single and double in expressions, MATLAB often converts to double in the result, but you can control the type explicitly.

Integer types store whole numbers without a fractional part. MATLAB has signed and unsigned integers with 8, 16, 32, and 64 bits, such as int8, uint8, int16, uint16, and so on. Each type has a fixed range. For instance, uint8 can store integers from 0 to 255. To create a variable of type uint8 you can write

matlab
b = uint8(200);
class(b)

If you attempt to store a value outside the allowed range, MATLAB clips or wraps it according to the rules of that type. For example

matlab
uint8(300)

returns 255, because 255 is the maximum for uint8. Arithmetic with integer types follows integer rules and does not allow fractions. If a result is not an integer, it is rounded or truncated to fit the integer representation.

You also have numeric types for complex numbers, but these still rely on double or single underneath. A complex number like 3 + 4i still has class double.

Logical Type

The logical type represents true or false values. Logical arrays are very important for indexing and for control flow. A logical value can be true or false, or numerically 1 or 0.

You can create logical values explicitly:

matlab
flag = true;
class(flag)

or by using relational operators, for example

matlab
x = 5;
y = 3;
z = (x > y);

Now z is logical and has the value true, because the expression x > y is true.

Logical arrays combine naturally with indexing and arithmetic. For instance, if A is a numeric vector, then A > 0 produces a logical vector that marks positive entries. Although MATLAB sometimes treats logicals as numbers 0 and 1, they are a separate data type. When you add a logical array to a numeric array, MATLAB converts the logical values to 0 and 1 during the operation, then returns a numeric result.

Text‑Related Types

Text in MATLAB can be stored in at least two basic ways at the beginner level: as character arrays or as string arrays. Character arrays, of class char, represent text as rows of characters. String arrays, of class string, represent text using objects that behave more naturally for many text operations.

A character array can be created with single quotes:

matlab
c = 'Hello';
class(c)

The variable c is a row vector of type char. Each element stores one character code.

String arrays are created with double quotes:

matlab
s = "Hello";
class(s)

Now s has class string. String arrays let you hold multiple pieces of text in a single array, and many modern MATLAB functions like to work with string inputs.

Character arrays and string arrays are not the same type. This often matters when you pass them to functions or concatenate them. MATLAB provides functions to convert between these forms, for example string and char, which are part of type conversion and will be discussed later in this chapter.

Even though both can represent text, they behave differently in indexing, size, and some operations, so it is important to know which one you are using.

Other Common Container Types

Besides basic scalars, vectors, and matrices, MATLAB offers several container data types that group data together. At this stage, you only need a quick sense of how they differ.

Cell arrays are containers that can hold values of any type in each element. Their class is cell. You can think of a cell array as a flexible container that can store numbers, text, or even other arrays in the same overall structure. They are particularly useful when different entries have different sizes or types.

Structures, with class struct, group related pieces of data into fields identified by names. For example, you might store measurements and labels together in one structure, with each field holding a different aspect of the data. Structures are a convenient way to keep related information together without relying on positions in a numeric array.

Tables and categorical arrays are also important container types, but they are covered in dedicated chapters later. For now, it is enough to know that different data types exist to represent tabular data, text categories, or mixed content, and they are not automatically interchangeable with basic numeric matrices.

Each of these container types is its own class, and MATLAB provides specific functions and indexing rules for them. When you work with containers, you need to keep track of whether you are dealing with numeric arrays, cell arrays, structures, or other types, because operations that work on numeric arrays may not apply directly to other classes.

Implicit Type Conversion in Expressions

When you perform operations on variables of different types, MATLAB sometimes converts one type to another automatically. This is called implicit conversion. It can be convenient, but you should be aware of when it happens and what result type you obtain.

If you combine a double and an integer in an arithmetic expression, MATLAB usually promotes the result to double. For example

matlab
d = 10;          % double
u = uint8(5);    % uint8
r = d + u;
class(r)

The result r is double, because MATLAB converts the integer to double to perform the arithmetic. This promotion is generally safe, because it gives you more precision, not less.

In contrast, arithmetic between two integer arrays of the same type stays in that integer type. If the mathematical result lies outside the valid range, MATLAB clips or wraps it. Implicit conversion here does not promote to double, so you must be careful with possible overflow.

Operations between numeric and logical types often convert the logical values to 0 or 1 as needed. For example

matlab
a = [1 2 3];
mask = [true false true];
result = a .* mask;
class(result)

The result is numeric. The logical values are converted to 1 for true and 0 for false during the multiplication. The final type is double.

With text, implicit conversion is far more limited. You cannot add a string to a number and expect an automatic conversion. Instead you must perform an explicit conversion to a common type before combining them.

Understanding when MATLAB automatically converts types helps you interpret results and avoid hidden bugs. If you rely too much on implicit rules, your code can become harder to predict, especially when types change.

Explicit Type Conversion

Explicit type conversion happens when you intentionally change the class of a variable using a conversion function. This is a very common operation in MATLAB, and it gives you control over how values are represented.

To convert a value to double, you can use the double function. For example

matlab
x = uint8(200);
y = double(x);
class(y)

The variable y is now double. The numeric value is the same, but the type has changed. You can then use y safely in operations that expect double precision.

Similarly, you can convert to other numeric classes with functions like single, int16, uint16, int32, uint32, and so on. For example

matlab
a = 3.7;
b = int16(a);

In this case, MATLAB converts 3.7 to an integer value that fits into int16. It does this by rounding toward zero. If the original value lies outside the allowed range, MATLAB clips it at the minimum or maximum for that type.

Conversions between character arrays and string arrays use char and string. For instance

matlab
s = "hello";
c = char(s);
t = string(c);

Now c is char and t is string. The textual content is the same, but the types differ. This kind of conversion is often needed when you call older functions that work with char or newer ones that prefer string.

Conversions involving logical values use logical to create logical arrays from numbers or other types, and numeric functions to move from logical back to numbers. For example

matlab
v = [0 1 2 3];
L = logical(v);

Here, L is logical. The value 0 becomes false, and any nonzero value becomes true. If you convert a logical array to numeric using double(L), you obtain an array of 0 and 1.

When you convert containers, such as a cell array containing numeric data, you may use functions like cell2mat or other specific conversion tools. These do not apply universally, and careless conversions can fail or change data layout, so it is important to choose the correct function for the type you are working with.

Converting Between Numeric and Logical Types

Converting between numeric types and logical is especially important because logical arrays are used frequently for indexing, conditions, and masks.

When you convert from numeric to logical using the logical function, MATLAB treats any zero element as false and any nonzero element as true. For example

matlab
a = [-2 0 3];
L = logical(a);

The result L is a logical array with values [true false true]. This makes it easy to turn a numeric vector into a mask. If you then use L to index another array, you select elements corresponding to nonzero or positive entries, depending on how you defined the numeric values.

Converting from logical to numeric is just as simple. When you apply a numeric conversion function like double to a logical array, MATLAB creates an array of 0 and 1. For instance

matlab
L = [true false true];
n = double(L);

Now n is [1 0 1] of class double. This is useful if you want to count how many elements satisfy a condition. You can sum the numeric array, or use functions like sum(L) directly since MATLAB automatically promotes logical to numeric during these operations.

When you combine logical arrays with numeric arrays in arithmetic expressions, MATLAB often applies these conversion rules implicitly. However, it is often clearer to perform explicit conversion when you want to emphasize that you are treating booleans as numbers and not simply as conditions.

Converting Between Numeric and Text

Sometimes you must convert numbers to text, or text to numbers. This happens, for example, when you read numeric data from a file stored as text, or when you want to display numeric results as part of messages.

To convert from numbers to text as string arrays, MATLAB provides the string and num2str functions. The string function converts numeric arrays directly into string arrays. For example

matlab
x = 3.14159;
s = string(x);
class(s)

The variable s is now a string that contains the characters "3.14159". If you use num2str instead, it returns a character array rather than a string array:

matlab
c = num2str(x);
class(c)

The variable c is a char array. Both functions create text representations of numeric values, but they return different text types, and you should choose the one that fits the rest of your code.

The reverse conversion, from text to numbers, uses functions such as str2double. This function interprets the content of text as numeric values where possible:

matlab
s = "42.5";
y = str2double(s);
class(y)

Here, y becomes a double with value 42.5. If the text cannot be interpreted as a number, str2double returns NaN. When you work with character arrays instead of strings, you can still pass them to str2double, which accepts both.

Conversions between numeric and text types do not happen implicitly in MATLAB. You must always call an explicit conversion function. For example, if you try to add a number to a string without converting, you get an error. This is a deliberate design, because text representations of numbers are not the same as numeric values internally.

Type Conversion and Overflow

When you convert a value to a type that cannot represent it exactly, you can run into overflow or loss of information. Overflow usually occurs when the target type has a smaller range than the source. Precision loss occurs when the target type has fewer bits or cannot represent fractions.

For integer types, each class has a fixed minimum and maximum. For instance, int8 has a range from -128 to 127, while uint8 has a range from 0 to 255. When you convert a double that lies outside these limits, MATLAB clips the value to the nearest allowed endpoint. For example

matlab
x = 300;
y = uint8(x);

The variable y becomes 255, which is the largest value allowed by uint8. If you convert a negative value to uint8, MATLAB clips it to 0. This clipping behavior can silently change data when you are not careful.

Even when a value lies inside the numeric range, converting from double to an integer type will remove the fractional part by rounding toward zero. For example

matlab
a = -3.9;
b = int16(a);

The variable b becomes -3, not -4, because the conversion truncates instead of rounding to the nearest integer. If you need specific rounding behavior, you should apply a rounding function, such as round or floor, before converting.

Converting from double to single reduces precision. The range of single can still represent very large and very small numbers, but with fewer significant digits. When you move from single back to double, MATLAB can represent the number with more bits, but the original fine details are already lost.

Understanding how overflow and precision loss occur during type conversion helps you avoid subtle problems, especially when you work with large or small values, or when you compress data to save memory.

Inspecting and Managing Data Types

To work confidently with different data types, you should know how to inspect and manage them. The most basic tool is the class function, which returns the type of a variable:

matlab
x = 10;
t = class(x);

The variable t now contains the text 'double'. This is often enough to check that your variable has the expected type before you perform operations.

MATLAB also provides a set of isa checks. The function isa lets you test if a variable is of a particular class. For example

matlab
x = uint8(5);
isa(x, 'uint8')
isa(x, 'double')

The first call returns true, the second returns false. You can use isa inside your code to choose different behavior depending on the type.

There are also specialized checks for common categories. For example, isnumeric tests if a variable is any numeric type, such as double, single, or an integer class. The function islogical tests for logical arrays, and ischar and isstring test for character arrays and string arrays.

You can use these checks to write code that behaves properly when input types change. For example, you might accept both string and char inputs and then convert them to a single preferred type at the beginning of a function.

If you later move to more advanced data structures, there are similar functions such as iscell, istable, and isstruct that help you discover what kind of data you are working with. The general pattern is to inspect the type, convert explicitly when needed, and avoid relying on hidden implicit conversions.

Important points to remember:

  1. MATLAB uses double as the default numeric type, but many other types exist, including single, integers, logical, and various container types.
  2. Implicit conversion can promote integers and logicals to double in mixed expressions, but does not safely prevent overflow inside integer arithmetic.
  3. Use explicit conversion functions like double, single, int16, logical, string, and char when you need a specific type.
  4. Conversions can clip values or lose precision, especially when converting to smaller or integer types, so check ranges and rounding behavior.
  5. Use class, isa, and type tests such as isnumeric, islogical, ischar, and isstring to inspect and manage data types in your code.

Views: 4

Comments

Please login to add a comment.

Don't have an account? Register now!