MATLAB
File I/O
Read and write .mat, .csv, and text files.
By EZ4Code Team
fileiocsv
Code
% Save/Load .mat files
A = rand(5);
save('data.mat', 'A'); % save variable A
load('data.mat'); % load into workspace
% CSV
M = csvread('data.csv'); % read (legacy)
M = readmatrix('data.csv'); % read (modern)
writematrix(M, 'out.csv'); % write
% Text files
fid = fopen('data.txt', 'r');
content = fscanf(fid, '%s');
fclose(fid);
% Table (recommended for tabular data)
T = readtable('data.csv');
T.Height(1) = 175; % modify column
writetable(T, 'out.csv');Explanation
Use .mat for native MATLAB binary format. readtable/writetable are modern functions that handle headers and types automatically — prefer over csvread (deprecated). For text files, use fopen/fscanf/fclose. Always close file handles to avoid leaks.
More MATLAB Snippets
Matrix Creation and Operations
Create and operate on matrices in MATLAB.
2D Plotting
Create line plots with labels, legends, and styling.
Functions and Scripts
Define functions in separate files or at end of scripts.
Cell Arrays and Structs
Heterogeneous data containers in MATLAB.
ODE Solvers
Solve ordinary differential equations with ode45.
Signal Processing (FFT)
Compute and visualize the FFT of a signal.