dlmwriter puts space between each character

698 Views Asked by At

I am trying to write a quite large binary array to text file. My data's dimension is 1 X 35,000 and it is like :

0 0 0 1 0 0 0 .... 0 0 0 1

What I want to do is first add a string in the beginning of this array let's say ROW1 and then export this array to a text file with space delimiter.

What I have tried so far:

fww1 = strcat({'ROW_'},int2str(1));
fww2 = strtrim(cellstr(num2str((full(array(1,:)))'))');

new = [fww1 fww2];

dlmwrite('text1.txt', new,'delimiter',' ','-append', 'newline', 'pc'); 

As a result of this code I got:

R O W _ 1 0 0 0 0 1 ....

How can I get it as below:

ROW_1 0 0 0 0 1 ....
1

There are 1 best solutions below

1
On BEST ANSWER

The most flexible way of writing to text files is using fprintf. There is a bit of a learning curve (you'll need to figure out the format specifiers, i.e. the %d etc.) but it's definitely worth it, and many other programming languages have some implementation of fprintf.

So for your problem, let's do the following. First, we'll open a file for writing.

fid = fopen('text1.txt', 'wt');

The 'wt' means that we'll open the file for writing in text mode. Next, let's write this string you wanted:

row_no = 1;
fprintf(fid, 'ROW_%d', row_no);

The %d is a special character that tells fprintf to replace it with a decimal representation of the given number. In this case it behaves a lot like int2str (maybe num2str is a better analogy, since it also works on non-integers).

Next, we'll write the row of data. Again, we'll use %d to specify that we want a decimal representation of the boolean array.

fprintf(fid, ' %d', array(row_no,:));

A couple thing to note. First, we the format specifier also includes a space in front of every number, so that takes care of the delimiter. Second, we only specified a single format but an array of numbers. When faced with this, fprintf will just go on repeating the format until it runs out of numbers.

Next, we'll write a newline to indicate the end of the row (\n is one of the special characters recognized by fprintf):

fprintf(fid, '\n');

If you have more lines to write, you can put a for loop over these fprintf statements. Finally, we'll close the file so that the operating system knows we're done writing to it.

fclose(fid);