Reading Data from File in MATLAB

MATLAB Tutorial

📂 Reading Data from File in MATLAB 

Reading data from files in MATLAB allows you to import external data (CSV, TXT, Excel, MAT files, etc.) for analysis, visualization, and processing.

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)

10 20 30
40 50 60

🔸 MATLAB Code


Output

10 20 30
40 50 60

📌 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)

Name Marks Age
____ _____ ___
John 85 20
Sara 90 21

📌 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 data
readtable() → 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

You may also like...