MATLAB: How to put a header in a txt file headerhelpputtext filetxt I'd like to put a header in my .txt file. I have a file with 744 lines like below. And I wanna put on the first line the header 'hora'. 001002003004005006...744 Best Answer Straight-forward solution would be like this:% Read the filefid = fopen('yourData.txt','r');str = textscan(fid,'%s','Delimiter','\n');fclose(fid);% Add your headerstr2 = [{'hola!'}; str{1}];% Save as a text filefid2 = fopen('output.txt','w');fprintf(fid2,'%s\n', str2{:});fclose(fid2); Related SolutionsMATLAB: Concatenate data using fgets You are closing the file in the loop. close the file after the loop. I assume the below should work.function read_datapattern(filename)fid = fopen(filename,'rt');if fid < 0 error('error opening file %s\n\n',filename);endpattern = fgets(fid);for n = 1:32767 nextline = fgets(fid); pattern = strcat(pattern, nextline);fprintf(pattern);fprintf('\n');endfclose(fid); MATLAB: How to remove some lines of a file Assuming your file is a text file, you can extract the first 744 lines ans save it like this:% Full path of the sample text filefilePath = fullfile(matlabroot,'examples','matlab','sonnets.txt');% Read the filefid = fopen(filePath,'r');str = textscan(fid,'%s','Delimiter','\n');fclose(fid);% Extract first 744 linesstr2 = str{1}(1:744);% Save as a text filefid2 = fopen('test.txt','w');fprintf(fid2,'%s\n', str2{:});fclose(fid2); Related QuestionI want to delete all the headerlines and delimiters from the data in the below attached text fileSave each result in different foldersRead text file and store in .mat fileFgetl, textscan, and the file position indicator
Best Answer