A = rand(50, 5);
% the simplest form
% folder data has to exist
dlmwrite('data/random_data.txt', A);
% really, anything can be an identifier
dlmwrite('data/random_data.txt', A, 'delimiter', '#', 'precision', 3);
Let's preview the file (just for demonstration). DO NOT use fileread for numeric data reading. Also, use a text editor or Excel for previewing files.
% to read data as string, not that useful
% I'm using it to just preview the file
fileread('data/random_data.txt')
Reading the file in.
% overwrite and use a normal delimiter (tab, comma, space, semicolon)
dlmwrite('data/random_data.txt', A, '\t');
% normal delimiter will be detected automatically, but we can explicit
B = dlmread('data/random_data.txt', '\t')
$\texttt{dlmread}$ will work with CSVs if they're only numbers
% CSVs typically contain the first line describing the data with strings
fileread('data/example.csv')
% dlmread will ignore text by using empty numbers (zeros)
% notice that the first row is just zeros instead of text
data = dlmread('data/example.csv', ',')
Using $\texttt{fprintf}$ to write formatted text to file.
% folder data has to exist
fid = fopen('data/custom_written.txt', 'w');
% reference to the file, doesn't mean anything, but identifies the file
fid
fprintf(fid, 'The day is %s\n', 'Thursday');
fclose(fid); % don't forget to close the file
fileread('data/custom_written.txt')
Using $\texttt{textscan}$ to read custom text.
fileread('data/custom_text.txt')
fid = fopen('data/custom_text.txt', 'r');
% use formatters
% %s - string, character
% %d - integer
% %f - floating point number (real number)
data = textscan(fid, '%s %d %f %s')
% if you opened a file, you have to close it
fclose(fid);
% data is organized into a cell array of columns
% strings are given in a cell array
data{1}
% numbers are given in a vector
data{2}