필터 지우기
필터 지우기

Use dlmwrite without \n

조회 수: 3 (최근 30일)
Kian
Kian 2015년 8월 13일
댓글: Kian 2015년 8월 13일
I am trying to use dlmwrite. My foo.obs has 3 rows of text before my data starts: 2 lines of title, and then my header line. I want each line to start at a new line, but then my header line to be tab delimited.
I don't want to use \n as it will cause a ^M to show up when I open the file on Unix.
The following code almost does that, expect that my headers also goes into different lines. I want all my header in the same line and tab delimited.
fnam='foo.obs';
title1 = {'Line 1'};
title2= {'Here is a new line'};
hdr={'H1','H2','H3'};
txt=sprintf('%s\n',title1{:},title2{:},hdr{:});
txt(end)='';
dlmwrite(fnam,txt,'');
Any ideas would be greatly appreciated.
Thanks
  댓글 수: 2
per isakson
per isakson 2015년 8월 13일
Replace
txt=sprintf('%s\n',title1{:},title2{:},hdr{:});
by
txt=sprintf('%s\n%s\n%s,%s,%s\n',title1{:},title2{:},hdr{:});
returns
>> txt
txt =
Line 1
Here is a new line
H1,H2,H3
Is that what you want?
Kian
Kian 2015년 8월 13일
편집: Kian 2015년 8월 13일
Thank you and yes, sort of.
Just that I don't want comma but tab between my headers. I can replace , with \t in there. But is there any way I instead of tab I can insert a single space between my headers?

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2015년 8월 13일
dlmwrite() does not support mixing text with numeric values. It does not support text headers followed by numeric data.
The workaround is to create the file ahead of time writing whatever header you want to it. Then dlmwrite() the numeric data specifying the '-append' option.
The default line terminator for dlmwrite is \n with no carriage return, and it opens the output for binary not for text so it does not automatically use \r\n on text files if you are running on MS Windows. If you want \r\n used as the end of line then you need to use the option 'newline', 'pc' .
\n does not become ^M on Unix: only \r shows up as ^M. If you open a file for writing on MS Windows as a text file (e.g. you specified 'wt' or 'at' but not just 'w' or 'a'), then each \n will be converted to \r\n by the I/O library. This does not apply on OS-X or Linux (Unix systems), and does not apply to dlmwrite() because dlmwrite() opens the files in binary rather than as text.
  댓글 수: 1
Kian
Kian 2015년 8월 13일
Thanks a lot for your explanations. Actually that's what I was initially doing. I had my file with text created ahead of time, and append my data to it. The problem was that I was creating my file using 'wt'. I changed it to 'w' and ^M goes away.
Thank a lot for your input,
Kian

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by