When fprintf, I need a return (\r\n) after each line (with inconstant number of values per line)

34 ビュー (過去 30 日間)
  • I'm doing a loop to print many lines of data in a file, and I want a return after each line. I am ok with constant number of values per line. But when the number of values per line is not constant, the format of data in the file is not correct.
E.g. use following code to print 3 values (1st line) then 4 values (2nd line) per line
if true
fprintf(File,'%s,%i,%i\r\n',DataArray{:})
end
It shows
a,1,4
b,5,8,
9
What I want is:
a,1,4
b,5,8,9
I know the problem is because I set the number of value to be 3 in the code (%s,%i,%i), so Matlab deem each line has 3 values. But how can I get the format that I need??
  2 件のコメント
Tom
Tom 2013 年 6 月 26 日
Will the data always have one string, then some number of integers? e.g. '%s %i %i' or '%s %i %i %i' and so on?
yang
yang 2013 年 6 月 26 日
編集済み: yang 2013 年 6 月 26 日
No Tom..the first one is string, the next few are intergers, then with unknown number of strings. i.e.
'%s %i %i %i %s'
or '%s %i %i %i %s %s'
or '%s %i %i %i %s %s %s'
and so on.

サインインしてコメントする。

採用された回答

Tom
Tom 2013 年 6 月 26 日
編集済み: Tom 2013 年 6 月 26 日
Data = {'alpha', 1 , 2 , 3, 'beta' , 'gamma' , 'delta' , 4};
% find locations strings and numeric data:
str = cellfun(@ischar,Data);
num = cellfun(@isnumeric,Data);
t = num2str(str + (num*2)); %number 1 equates to string, 2 equates to numeric
formatStr = [regexprep(t,{'1','2'} , {'%s', '%i'}) ,'\r\n'];
fprintf(File,formatStr)

その他の回答 (1 件)

Image Analyst
Image Analyst 2013 年 6 月 26 日
How about
if length(DataArray) == 3
fprintf(File,'%s,%i,%i\r\n',DataArray{:})
else
fprintf(File,'%s,%i,%i %i\r\n',DataArray{:})
end
  2 件のコメント
yang
yang 2013 年 6 月 26 日
編集済み: yang 2013 年 6 月 26 日
Thanks. But the number of values per line could be any integer, not only 3 or 4....Any other idea?
Image Analyst
Image Analyst 2013 年 6 月 27 日
In the future, it helps to put in those kind of details/requirements in the original question. Otherwise, how would we know?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by