matlab - Read multiple text files and import each of them as columns -


i have code have no idea how each of text files placed different columns in matrix.

for example, have 5 text files , of them have 1 column. how can each of columns single matrix? code wrote below isn't working:

for k = 1:5  textfilename = ['file' num2str(k) '.txt'];  fid = fopen(textfilename, 'rt');  textdata = fread(fid);  fclose(fid); end 

i assuming data read in of text files same length. if that's case, have create empty matrix, concatenate results column column. have add 2 lines.

 % store text data here  textdatamatrix = [];  k = 1:5   textfilename = ['file' num2str(k) '.txt'];   fid = fopen(textfilename, 'rt');   textdata = fread(fid);   % concatenate text file data column   textdatamatrix = [textdatamatrix textdata];   fclose(fid);  end 

at end of script, textdatamatrix contain text data wanted , placed in separate columns desired.


nb: poor practice create empty matrix , populate items after considered slow. if know how many characters / bytes / numbers in single data file before running code. when that, can preallocate right amount of memory need before run through for loop. creating right amount of space before populating matrix more efficient in matlab instead of concatenating elements. if want way, suppose number of elements have in data file called numelements. rewrite code wrote above in following way:

 % store text data here  textdatamatrix = zeros(numelements, 5);  k = 1:5   textfilename = ['file' num2str(k) '.txt'];   fid = fopen(textfilename, 'rt');   textdata = fread(fid);   % place k'th text data in k'th column   textdatamatrix(:,k) = textdata;   fclose(fid);  end 

however, if there aren't many elements in particular text file, first version of code have above fine.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -