Writing Data to File in MATLAB

MATLAB Tutorial

💾 Writing Data to File in MATLAB

Writing data to files in MATLAB lets you export results (numbers, text, tables) to formats like TXT, CSV, Excel, and MAT for sharing, reporting, or later use.

MATLAB is developed by MathWorks.


🔹 Why Write Data to Files?

  • Save computation results

  • Share data with Excel/other tools

  • Create logs and reports

  • Preserve MATLAB variables (.mat)


1️⃣ Write Numeric Data to TXT/CSV — writematrix()

Best for numeric arrays.

🔸 Example


📌 For CSV:


Result: File created with matrix values.


2️⃣ Write Data to Excel — writematrix()


📌 Writes to the first sheet by default.


3️⃣ Write Tables (Mixed Data) — writetable()

Best when you have headers + mixed types.


 

Result: CSV with column headers.


4️⃣ Write Cell Arrays — writecell()

Useful for text + numbers without table semantics.



5️⃣ Write Text Files (Formatted) — fprintf()

Gives full control over formatting.


Result (report.txt)

Student Report
Marks: 85

6️⃣ Append Data to Existing File



7️⃣ Save MATLAB Variables — save()

Creates MATLAB’s native .mat file.


📌 Load later with:

load('mydata.mat')

8️⃣ Specify Delimiters & Options



⚠️ Important Notes

  • writematrix() → numeric arrays

  • writetable() → tables with headers

  • writecell() → mixed cell data

  • fprintf() → custom formatting

  • Files are saved in the current folder unless a path is given


🎯 Interview Questions: Writing Data to File in MATLAB

🔹 Q1. Which function writes numeric data to a file?

Answer: writematrix()


🔹 Q2. How do you write mixed data with headers?

Answer: Using writetable().


🔹 Q3. Which function provides formatted output?

Answer: fprintf().


🔹 Q4. How do you save MATLAB variables?

Answer: Using save() to create a .mat file.


🔹 Q5. How do you append data to a file?

Answer: Open file with fopen(...,'a').


🔹 Q6. Difference between writematrix() and writecell()?

Answer:
writematrix() → numeric only
writecell() → text + numbers


Summary

  • MATLAB supports writing to TXT, CSV, Excel, MAT

  • Choose function based on data type

  • save() is best for MATLAB-only storage

  • Essential for reporting and data exchange

You may also like...