Files: read & write

Read .csv files

mydata = readtable('mydata.csv')

mydata = readtable('mydata.csv','Format','%s%s%u%f%f%s')

% check column titles

mydata.Properties.VariableNames

{'SampleID'} {'Treatment'} {'Time'}

% get second column of 'Treatment'

x = mydata.Treatment % using column name

id = find(ismember(mydata.Properties.VariableNames,'Treatment'))

2

x = mydata(:,id); % using column index id=2

x = mydata(:,2);

% convert table to cell array

table2cell(mydata)

Read complete text-file

mytext = fileread('mytext.txt');

split lines by newline character \n

textlines = strsplit(mytext,'\n')

textlines{1}

'text of first line'

remove empty textlines ( → remove empty fields in cell array )

textlines( cellfun(@isempty, textlines) ) = []

remove newline characters \n

check for ending newline character \n

strcmp(mytext(end),sprintf('\n'))

remove ending character

mytext(end)=[]

remove all newline characters

strrep(mytext,sprintf('\n'),'')

Read line by line from a text file

fid = fopen('myfile.txt', 'r');

while ~feof(fid) % while not end-of-file

fileline = fgets(fid); % read line by line

... % do something with each file line

end

fclose(fid);

% example: search string "www" in each line of a text file

fid = fopen('myfile.txt', 'r');

while ~feof(fid) % while not end-of-file

fileline = fgets(fid); % read line by line

fileline = strrep(fileline,sprintf('\n'),''); % remove newline character

if ~isempty(strfind(fileline,'www')) % search string "www" in line

disp('Found string "www" in line')

disp(fileline)

end

end

fclose(fid);