Skip to content
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