Writing Data to File in MATLAB
💾 Writing Data to File in MATLAB
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)
6️⃣ Append Data to Existing File
7️⃣ Save MATLAB Variables — save()
Creates MATLAB’s native .mat file.
📌 Load later with:
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 onlywritecell() → 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
