writing different datatypes to files

1 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Dates and Time 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by