How to format in a CSV file

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!

Respuestas (1)

Stephen23
Stephen23 el 23 de Mzo. de 2017
Editada: Stephen23 el 23 de Mzo. de 2017

0 votos

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

Categorías

Más información sobre Data Import and Analysis en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 23 de Mzo. de 2017

Editada:

el 23 de Mzo. de 2017

Community Treasure Hunt

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

Start Hunting!

Translated by