Hi all, I previously wrote a short simple script to copy the third column of a text file to a new csv sheet (as shown below).
fid = fopen('pvt-results_1496-023B.txt','r');parameters = textscan(fid, '%s%s%s\n','HeaderLines',4, 'Delimiter','\t');fclose(fid);gid = fopen('pvtsort.csv','wt');fprintf(gid,'%s\n','Trail');for k = parameters{1,3} i = 1:length(k) fprintf(gid,'%s\n',k{i})endfclose(gid)
So this worked fine. Now I'm trying to loop this script in order to copy the third column from multiple text files and put them all on a single csv sheet with headers (Trail [incremental numbers for each additional column]). My .m file is in the folder with all text files (same # of headerlines & columns, different # of rows), but I got stuck after loading multiple text files with
fid = dir('*txt') for i = 1:length(fid) files(i) = fopen(fid(i).name); fid(i).values = textscan(files(i), '%s%s%s\n','HeaderLines',4, 'Delimiter','\t'); fclose(files(i));endgid = fopen('pvtsort.csv','wt');
So I was trying to fprinf the third column from multiple text files to 'pvtsort.csv' but keep getting the error "Error using fprintf. Function is not defined for 'cell' inputs." So I tried loading the files differently using numel instead of length:
for k = 1:numel(fid) pvt = fopen(fid{k},'r'); content(k) = textscan(pvt,'%s%s%s\n','HeaderLines',4,'Delimiter','\t'); data{k} = content{3}; fclose(pvt); end
And got "Cell contents reference from a non-cell array object. " I guess I'm loading the txt files incorrectly here with the dir() function, which is why I can't even begin copy anything from the files, let along the specific column. When I tried to load the 16 txt files in my folder with fid = dir('*txt'), it throws the following info fid =16×1 struct array with fields:
- name
- date
- bytes
- isdir
- datenum
I think the struct array is the issue here? Perhaps I should not use fprintf function to copy a string of data from multiple txt files onto a csv?
Pointers appreciated.
Best Answer