MATLAB: Separating and reprinting a big string

fwriteMATLAB

I have a text file with about 45000 entries all on one line seperated by "//"
I would like to read this huge line from juneweather.txt, seperate it into seperate strings and write them onto a new file, each one on a new line. i keep getting the error
Error using fwrite
Cannot write value: nonscalar strings are unsupported.
Error in weather02 (line 16)
fwrite(fid1, john);
fid1=fopen('JuneWeather2.txt','at');
fid2=fopen('JuneWeather.txt'); %…. open the file, MATLAB assigns an ID
line=fgets(fid2);
greg=strsplit(line,'//');
%disp(greg);
for i=1:length(greg)
corey = {greg(i),'\r'};
john = string(corey);
fwrite(fid1, john);
end
Any ideas? thanks so much!

Best Answer

Hi bws1007:
The string to write needs to be scalar. The command fwrite() is used to write into binary format, thus it does not make any difference whether it is in one line or not. You would not see the difference unless you read the binary file and parse the string including any formating commands as '\n'. If you want to write text files, use fprintf(). Below you find a small example using your variable names (maybe you consider to change these names):
TestString = 'Do not write strings // in one line // because it annoys // the user.';
greg=strsplit(TestString,'//');
corey = cellfun(@(cIn) [cIn,'\n'],greg,'UniformOutput',false);
john = string(corey);
% Binary file
fileID = fopen('myTestFile.bin','w');
arrayfun(@(dIn) fwrite(fileID,dIn),john);
fclose(fileID);
% test read
TestID = fopen('myTestFile.bin','r');
TestInput = fread(TestID,'*char')';
fclose(TestID);
% text file
fileID = fopen('myTestFile.txt','w');
fprintf(fileID,'%s\n',strrep(john,'\n','')');
fclose(fileID);
% you can check the text file output with your text editor or matlab
Kind regards,
Robert