MATLAB Type Conversion
🔄 MATLAB Type Conversion
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
📌 MATLAB converts int8 to double automatically.
2️⃣ Explicit Type Conversion
You manually convert data types using conversion functions.
🔢 Numeric Type Conversion
🔸 Double → Integer
Output
📌 Decimal part is truncated, not rounded.
🔸 Integer → Double
Output
🔸 Double → Single
Output
🔤 Numeric ↔ String Conversion
🔸 Number → String
Output
🔸 String → Number
Output
🔤 char ↔ string Conversion
🔸 char → string
Output
🔸 string → char
Output
🔘 Logical Type Conversion
🔸 Logical → Numeric
Output
🔸 Numeric → Logical
Output
🧬 Check Data Type
⚠️ Important Notes
-
Integer conversion removes decimals
-
Default numeric type is
double -
str2double()returnsNaNif 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() |
