How to format in a CSV file

12 vues (au cours des 30 derniers jours)
Christopher Robin Johnson
Christopher Robin Johnson le 23 Mar 2017
Modifié(e) : Stephen23 le 23 Mar 2017
So I am attempting to place a cell array into a CSV file from my code. The issue is when it gets into the CSV file it is all wonky. I would like it to list out the cell arrays in the following way:
Name1 Name2
Country1 Country2
City1 City2
Height1 Height2
This is what my code looks like now:
fid = fopen('Masonry.csv', 'wt');
for n = 1:numel(numberRows)
fprintf(fid, '%s \n', NameofTypeMasonry{n});
fprintf(fid, '%s', CountryofTypeMasonry{n});
fprintf(fid, '%s', CityofTypeMasonry{n});
fprintf(fid, '%d', HeightofTypeMasonry(n));
end
fclose(fid);
Thank you in advance!

Réponses (1)

Stephen23
Stephen23 le 23 Mar 2017
Modifié(e) : Stephen23 le 23 Mar 2017
Loops are not required. To create a comma-separated file do something like this:
% fake data:
NameofTypeMasonry = {'anna','bob','cathy'};
CountryofTypeMasonry = {'angola','burundi','chad'};
CityofTypeMasonry = {'accra','banjul','cairo'};
HeightofTypeMasonry = [2,4,8];
% join cell arrays together:
C = [NameofTypeMasonry;CountryofTypeMasonry;CityofTypeMasonry]';
N = size(C,1);
% print to file:
fmt_s = [repmat('%s,',1,N),'\n'];
fmt_n = [repmat('%d,',1,N),'\n'];
fid = fopen('temp1.csv','wt');
fprintf(fid,fmt_s,C{:});
fprintf(fid,fmt_n,HeightofTypeMasonry);
fclose(fid);
which creates this file:
anna,bob,cathy,
angola,burundi,chad,
accra,banjul,cairo,
2,4,8
To create a fixed-column width (not recommended) use these format strings:
fmt_s = [repmat('%-12s ',1,N),'\n'];
fmt_n = [repmat('%-12d ',1,N),'\n'];
to get this file:
anna bob cathy
angola burundi chad
accra banjul cairo
2 4 8

Catégories

En savoir plus sur Data Import and Analysis dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by