Separating and reprinting a big string

4 views (last 30 days)
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!

Accepted Answer

Robert U
Robert U on 26 Sep 2019
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
  1 Comment
bws1007
bws1007 on 26 Sep 2019
Haha i apologise for the variable names, I find it easier to look for an out of place "greg" than an out of place 'x'. It worked! Thank you

Sign in to comment.

More Answers (0)

Products


Release

R2017b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!