writing different datatypes to files

1 回表示 (過去 30 日間)
Patrick Laux
Patrick Laux 2021 年 7 月 2 日
コメント済み: Patrick Laux 2021 年 7 月 2 日
Dear all,
I know there is a lot available already about this problem. I tried several ways but do not see the solution yet :-).
Just to give an example. I create 1 date vector (which I converted from char to string) for 1 year and a random matrix (365,2). I want to write these two variables (containing 3 colomns) into 1 file (tab seperated).
What am I doing wrong? Maybe the solution is via cell arrays only? Thanks in advance.
Here is the code:
% create rand data matrix
A=rand(365,2);
% create Date vector
n1 = datenum(2006, 1, 1);
n2 = datenum(2006, 12, 31);
n3=n1:1:n2;
formatOut='yyyy-mm-dd';
Outdate=datestr(n3,formatOut,'local');
%%% re-format B to string
for i=1:365;
BB(i)=convertCharsToStrings(Outdate(i,:)');
end
BB=BB';
%%
fid = fopen('testfile.txt','wt+');
% [nrows,ncols] = size(BB);
% for rwo = 1:nrows
% fprintf(fid,'%s %5.1f %5.1f \n',BB(row), A(row));
% end
fprintf(fid,'%s %5.1f %5.1f \n',BB, A);
fclose(fid);

回答 (1 件)

Walter Roberson
Walter Roberson 2021 年 7 月 2 日
編集済み: Walter Roberson 2021 年 7 月 2 日
fprintf() "uses up" all of BB before going on to A.
I suggest that you use compose() to construct string objects of the lines and fprintf() those. Or compose() and strjoin() them into one long string and fwrite() it.
  3 件のコメント
Walter Roberson
Walter Roberson 2021 年 7 月 2 日
compose() does not use comma. But if you want tab then
A=["a";"b" ]; B=[1 2;3 4]
compose("%s\t%d\t%d", A, B)
Patrick Laux
Patrick Laux 2021 年 7 月 2 日
Yes, you are right. Cannot reproduce the comma-separation again.
Very helpful, thanking you!

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

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by