0
0
MATLABdata~5 mins

Converting between types in MATLAB

Choose your learning style9 modes available
Introduction

Sometimes you need to change data from one form to another so your program can work correctly. This is called converting between types.

When you want to change a number stored as text into a real number to do math.
When you need to turn a decimal number into a whole number.
When you want to convert a number into text to show it on the screen.
When you have data in one format but a function needs it in another format.
When you want to save memory by changing a large number type to a smaller one.
Syntax
MATLAB
newVariable = typeName(oldVariable);

Replace typeName with the type you want, like double, int32, or char.

This creates a new variable with the converted value.

Examples
Convert text '123' to the number 123.
MATLAB
x = '123';
y = str2double(x);
Convert decimal 3.7 to whole number 3 by cutting off the decimal part.
MATLAB
a = 3.7;
b = int32(a);
Convert number 65 to character 'A' using ASCII code.
MATLAB
num = 65;
charVal = char(num);
Sample Program

This program shows how to convert a string to a number, then to an integer, and also how to convert a number to a character.

MATLAB
strNum = '45.67';
num = str2double(strNum);
intNum = int32(num);
charVal = char(65);

fprintf('Original string: %s\n', strNum);
fprintf('Converted to double: %.2f\n', num);
fprintf('Converted to int32: %d\n', intNum);
fprintf('Number 65 as char: %c\n', charVal);
OutputSuccess
Important Notes

When converting from string to number, use str2double instead of just double.

Converting from decimal to integer cuts off the decimal part, it does not round.

Converting numbers to characters uses ASCII codes, so 65 becomes 'A'.

Summary

Converting types helps your program use data correctly.

Use functions like str2double, int32, and char to convert data.

Be careful: converting decimals to integers cuts off decimals, it does not round.