Reading Data from File in MATLAB
📂 Reading Data from File in MATLAB
This is a very common task in data analysis, engineering, research, and projects.
MATLAB is developed by MathWorks.
🔹 Why Read Data from Files?
-
Work with real-world datasets
-
Analyze experimental or survey data
-
Avoid manual data entry
-
Integrate MATLAB with Excel, sensors, databases
1️⃣ Reading Text Files (.txt) using load()
Best for numeric data only.
🔸 Example (data.txt)
🔸 MATLAB Code
Output
📌 File must contain only numbers.
2️⃣ Reading CSV Files using readmatrix()
Recommended modern function.
📌 Automatically detects delimiters like commas.
3️⃣ Reading Excel Files (.xlsx)
📌 Works directly with Excel files.
4️⃣ Reading Data as Table – readtable()
Best when data contains text + numbers + headers.
Output (example)
📌 Data stored in table format.
5️⃣ Reading Delimited Text using readtable()
📌 Useful for tab-separated files.
6️⃣ Reading MAT Files (.mat)
Used for MATLAB’s native data storage.
📌 Loads variables directly into workspace.
7️⃣ Reading Data using Low-Level Functions (fopen)
Used for advanced control.
📌 Suitable for custom file formats.
8️⃣ Checking File Existence
⚠️ Important Notes
-
Use
readmatrix()for numeric data -
Use
readtable()for mixed data -
load()works only for numeric files -
File should be in current folder or full path given
🎯 Interview Questions: Reading Data from File in MATLAB
🔹 Q1. Which function is best to read CSV files?
Answer: readmatrix() or readtable()
🔹 Q2. Difference between readmatrix() and readtable()?
Answer:readmatrix() → numeric datareadtable() → mixed data with headers
🔹 Q3. Which function reads Excel files?
Answer: readmatrix() or readtable()
🔹 Q4. What type of file does load() support?
Answer: Numeric .txt and .mat files.
🔹 Q5. How do you read MATLAB native files?
Answer: Using load().
🔹 Q6. Which function provides maximum file control?
Answer: fopen() with fscanf() / fgets().
✅ Summary
-
MATLAB supports many file formats
-
readmatrix()&readtable()are preferred -
load()for numeric & MAT files -
Essential for real-world data analysis
