Question

Title basically says it all. Here is my current code, but it's not quite correct. It puts \n rather than a new line.

I would like to go through a row of a matrix, put a space between each element in the row and then add a new line for the next row.

mat = [1,2,3,4;5,6,7,8]; %must work for arbitrary size matrix.. just an example
s = '';
for i = 1:size(mat,1)
  s = strcat(s,sprintf('%d ',mat(i,:)));
  s = [s,'\n']; %and many variations of trying to add this 
end

This currently yields: 1 2 3 4\n5 6 7 8\n

What I would like is (as a string):

1 2 3 4
5 6 7 8

I don't know how I haven't found someone asking this specific question before, but I have searched to no avail!

Was it helpful?

Solution

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 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top