A newline is character code 10 (char(10)
). So, you can keep your current sprintf
and use char(10)
:
s = [s,char(10)];
Here is what happens with a simple example:
>> ['one' char(10) 'two']
ans =
one
two
It turned out that strcat
strips the newline, so replace the content of the loop with:
s = [s sprintf('%d ',mat(i,:)) char(10)];
From the strcat
documentation:
For character array inputs, strcat removes trailing ASCII white-space characters: space, tab, vertical tab, newline, carriage return, and form-feed. To preserve trailing spaces when concatenating character arrays, use horizontal array concatenation,
[s1, s2, ..., sN]
.
Also, num2str
might also do what you want, but if you have more than 1 digit in each number than your output would be a little different:
>> num2str(mat)
ans =
1 2 3 4
5 6 7 8
9 10 11 12
Another funky solution with no loop:
>> s = sprintf([repmat('%d ',1,size(mat,2)) '\n'],mat')
s =
1 2 3 4
5 6 7 8