writing different datatypes to files

1 visualizzazione (ultimi 30 giorni)
Patrick Laux
Patrick Laux il 2 Lug 2021
Commentato: Patrick Laux il 2 Lug 2021
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);

Risposte (1)

Walter Roberson
Walter Roberson il 2 Lug 2021
Modificato: Walter Roberson il 2 Lug 2021
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 Commenti
Walter Roberson
Walter Roberson il 2 Lug 2021
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 il 2 Lug 2021
Yes, you are right. Cannot reproduce the comma-separation again.
Very helpful, thanking you!

Accedi per commentare.

Categorie

Scopri di più su Dates and Time in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by