writing bin data to *.dat file

8 次查看(过去 30 天)
Hey everybody,
again I couldn't find the right solution and need your wise counsel ;)
I have a binary vector i.e. like this: x = rand(50,1)*7; x = fi(x,false,3,0) x = bin(x);
Now I want to write this to a dat file. I acutally thought I could use dlmwrite('test.dat', x, 'newline', 'pc') but if x = [101 ; 110 ; 001 ; 011 ; ...]
the test.dat file looks like this: 1,0,1 1,1,0 0,0,1 0,1,1 . . .
and not like I would like to have it: 101 110 001 011 . . .
Any idea how I can teach dlmwrite to neglect the commas while still using the newline parameter? Should I probably use some other function?
Beste regards and thanks in advance,
Lennart

采纳的回答

Star Strider
Star Strider 2015-10-21
I don’t have the Fixed Point Designer, so I’m relying on the documentation for bin. The bin function returns a character array, and the dlmwrite function writes only numeric data. So it would seem that you have to convert the string to double-precision numeric, and use the 'precision' name-value pair argument.
See if this does what you want:
x = ['101' ; '110' ; '001' ; '011'];
xn = str2num(x);
dlmwrite('#TEST.txt', xn, 'precision','%03d')
type #TEST.txt
101
110
001
011
You will have to experiment to tweak it to your specifications, but this seems to be as close as dlmwrite can get to doing what you want.
  4 个评论
Lennart
Lennart 2015-10-22
There we go! It is not %3s because it is 3 bits right? I thought I would have to adjust that number to the number of bits but 3 as well works for values with i.e. 7 bits. Should it be that way?
Do you want to post that answer as a separate answer so I can accept it?
Thank you very much for your help!
Star Strider
Star Strider 2015-10-22
My pleasure!
Yes. The '%3s' format string guarantees a 3-character-wide text field.
If you want all the entries in your file to have a 7 (or larger character field), change the format string to accommodate it, for example '%7s' for a 7-character field. However, the string has to have the requisite number of leading zeros already in the string for that to display as you want it to. If it does not, the field will still be 7 characters long, but right-justified so the left positions are blank.
The '%3s' will accommodate larger fields, but shorter strings will be out of alignment, of varying length but at least 3 characters long. If you want them all in alignment in your file, use '%7s' (or '%8s' to print entire bytes).

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by