MATLAB Type Conversion

MATLAB Tutorial

🔄 MATLAB Type Conversion

Type conversion in MATLAB means changing one data type into another (e.g., numeric → string, double → integer, logical → numeric).

MATLAB is developed by MathWorks.


🔹 Why Type Conversion Is Needed?

  • To match function requirements

  • To save memory

  • To format output

  • To avoid runtime errors

MATLAB supports both implicit and explicit type conversion.


1️⃣ Implicit Type Conversion

MATLAB automatically converts data types when required.

🔸 Example


Output

ans = double

📌 MATLAB converts int8 to double automatically.


2️⃣ Explicit Type Conversion

You manually convert data types using conversion functions.


🔢 Numeric Type Conversion

🔸 Double → Integer


Output

12

📌 Decimal part is truncated, not rounded.


🔸 Integer → Double


Output

ans = double

🔸 Double → Single


Output

ans = single

🔤 Numeric ↔ String Conversion

🔸 Number → String


Output

100
ans = char

🔸 String → Number


Output

25

🔤 char ↔ string Conversion

🔸 char → string


Output

ans = string

🔸 string → char


Output

ans = char

🔘 Logical Type Conversion

🔸 Logical → Numeric


Output

1

🔸 Numeric → Logical


Output

logical
0
logical
1

🧬 Check Data Type

class(variable)
whos

⚠️ Important Notes

  • Integer conversion removes decimals

  • Default numeric type is double

  • str2double() returns NaN if conversion fails

  • Use explicit conversion to avoid errors


🎯 Interview Questions: MATLAB Type Conversion

🔹 Q1. What is type conversion in MATLAB?

Answer: Converting one data type into another.


🔹 Q2. What is implicit type conversion?

Answer: Automatic conversion done by MATLAB during operations.


🔹 Q3. Which function converts number to string?

Answer: num2str()


🔹 Q4. Which function converts string to number?

Answer: str2double()


🔹 Q5. What happens when double is converted to integer?

Answer: Decimal part is truncated.


🔹 Q6. How do you check data type in MATLAB?

Answer: Using class() or whos.


🔹 Q7. Can logical values be converted to numbers?

Answer: Yes (true → 1, false → 0).


🔹 Q8. What is the default numeric data type after conversion?

Answer: double


Summary Table

Conversion Function
double → int int8, int16, int32
int → double double()
number → string num2str()
string → number str2double()
char → string string()
string → char char()
logical → numeric double()
numeric → logical logical()

You may also like...