0
0
MATLABdata~5 mins

Type conversion functions in MATLAB

Choose your learning style9 modes available
Introduction

Type conversion functions change data from one type to another. This helps when you need to work with different kinds of data together.

When you want to convert a number to text to display it.
When you need to change text to a number to do math.
When you want to convert a floating-point number to an integer.
When you want to store data in a specific format for a function.
When you want to convert logical true/false to numbers.
Syntax
MATLAB
newVar = functionName(oldVar);

Replace functionName with the conversion function like double, int32, char, or logical.

The input variable oldVar is converted to the new type and stored in newVar.

Examples
Converts integer 5 to double precision number.
MATLAB
x = int32(5);
y = double(x);
Converts text '123' to number 123.
MATLAB
str = '123';
num = str2double(str);
Converts floating number 3.7 to integer 3 by truncation.
MATLAB
val = 3.7;
intVal = int32(val);
Converts logical true to number 1.
MATLAB
flag = true;
numFlag = double(flag);
Sample Program

This program converts a string to a double number, then to an integer, and finally converts that integer to a character. It prints each step.

MATLAB
str = '45.67';
num = str2double(str);
intNum = int32(num);
charNum = char(intNum);

fprintf('Original string: %s\n', str);
fprintf('Converted to double: %.2f\n', num);
fprintf('Converted to int32: %d\n', intNum);
fprintf('Converted int32 to char: %s\n', charNum);
OutputSuccess
Important Notes

When converting from floating-point to integer, MATLAB truncates the decimal part (does not round).

Converting numbers to characters uses ASCII codes, so the result may not be a digit.

Use str2double to convert strings to numbers safely; it returns NaN if conversion fails.

Summary

Type conversion functions change data types to help with different operations.

Common functions include double, int32, char, and str2double.

Be careful with conversions that may lose information, like float to int or number to char.