Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print concatenated string to screen and text file using matlab

Tags:

printf

matlab

This is a very basic question, but since I'm new to Matlab, I'm struggling to find a good way to do so. I just want to print some concatenated strings to screen and to a text file. Matlab is "eating" the \n !!

str1 = sprintf('Line 1\n');
str2 = sprintf('Line 2\n');
finalStr = strcat(str1,str2);
% Print on screen
fprintf('%s',finalStr );
% Result: Line 1Line 2. What happened to the \n ?? !!!!

% Print on file
[curPath,name,ext] = fileparts(mfilename('fullpath'));
infoPath = fullfile(curPath,'MyFile.txt');
fid = fopen(infoPath,'w'); % Write only, overwrite if exists
fprintf(fid,finalStr);
fclose(fid);

I also need to save finalStr to a text file. What I'm missing here?

like image 379
Pedro77 Avatar asked Dec 04 '25 07:12

Pedro77


1 Answers

The function strcat ignores white spaces. In order to perform this operation, use:

finalStr = [str1, str2];
fprintf('%s',finalStr );

result:

Line 1 
Line 2

Edit: To write the text on a text file in a "Notepad" way:

% Notepad needs \r also.
newline = sprintf('\n');
newlineNotepad = sprintf('\r\n');
strB = strrep(strA, newline, newlineNotepad);
like image 50
ibezito Avatar answered Dec 07 '25 17:12

ibezito