Separating and reprinting a big string

조회 수: 1 (최근 30일)
bws1007
bws1007 2019년 9월 26일
댓글: bws1007 2019년 9월 26일
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!

채택된 답변

Robert U
Robert U 2019년 9월 26일
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
bws1007
bws1007 2019년 9월 26일
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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

태그

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by