Text Files in MATLAB

MATLAB Tutorial

📄 Text Files in MATLAB

Text files (.txt) in MATLAB are commonly used to store simple data, logs, and reports.

MATLAB provides high-level and low-level functions to read from and write to text files efficiently.
MATLAB is developed by MathWorks.


🔹 What Is a Text File?

A text file stores data in plain text format, such as:

  • Numbers

  • Characters

  • Words

  • Lines of text

Example:

Name: Amit
Marks: 85

1️⃣ Reading Numeric Text Files — load()

Used when the text file contains only numeric data.

🔸 Example (data.txt)

10 20 30
40 50 60

🔸 MATLAB Code



 

Output

10 20 30
40 50 60

📌 Works only for numeric data.


2️⃣ Reading Text Files — fopen() + fscanf()

Used for formatted numeric data.



 

Output

10
20
30
40
50
60

3️⃣ Reading Line-by-Line — fgets()

Best for text content.

🔸 Example (info.txt)

Hello MATLAB
Welcome to File Handling

🔸 MATLAB Code


 

Output

Hello MATLAB
Welcome to File Handling

4️⃣ Reading Entire File — fileread()

Reads the whole text file at once.



 

📌 Simple and fast for small files.


5️⃣ Writing to a Text File — fprintf()



 

Output (report.txt)

Student Report
Marks: 85

6️⃣ Appending Data to a Text File



 

📌 'a' mode adds data without deleting existing content.


7️⃣ Writing Multiple Lines



 


8️⃣ Closing Files Properly



 

📌 Always close files to avoid memory leaks.


⚠️ Important Notes

  • 'r' → read mode

  • 'w' → write (overwrites file)

  • 'a' → append

  • Always check file ID:



 


🎯 Interview Questions: Text Files in MATLAB

🔹 Q1. Which function opens a text file?

Answer: fopen()


🔹 Q2. Which function reads formatted data?

Answer: fscanf()


🔹 Q3. How do you read a full text file at once?

Answer: fileread()


🔹 Q4. Which function writes formatted text?

Answer: fprintf()


🔹 Q5. Difference between fgets() and fscanf()?

Answer:
fgets() → reads one line as text
fscanf() → reads formatted data


🔹 Q6. Why is fclose() important?

Answer:
To release file resources and avoid data corruption.


Summary

  • Text files store plain data

  • MATLAB supports low-level file handling

  • fopen, fscanf, fgets, fprintf are key functions

  • Essential for logs, reports & custom data formats

You may also like...