简体   繁体   中英

matlab, how to export text and numerical data to a excel csv file?

When I use the code below. I get the numerical data exported correctly however the first row is blank when there should be titles(headers) on the first row of each column. Any solutions?

clc 
clear

filename = 'file.csv'; 
fileID = fopen(filename,'wt');
%**************************************************************************
%Sample data (note sample data are transposed row, i.e. columns) 

sample1 = [1,2,3,4]';
sample2 = [332.3, 275.8, 233.3, 275]';
sample3 = [360, 416.7, 500, 360]';
sample4= [-0.9, -0.9, -0.9, -0.9]';
sample5 = [ 300000, 0, 0, 0]';

A ={'text1','text2', 'text3', 'text4', 'text5'}; %'

%***************************************************************************
%write string to csv

[rows, columns] = size(A);
for index = 1:rows    
    fprintf(fileID, '%s,', A{index,1:end-1});
    fprintf(fileID, '%s\n', A{index,end});
end 

fclose(fileID);

%***************************************************************************
%write numerical data to csv

d = [sample1, sample2, sample3, sample4, sample5];

csvwrite(filename, d, 1);

You are erasing strings when writing numerical data ,run your script just up to numerical data - it works fine. Simply switch order of operations- first write numbers, and then write strings, it will work.

EDIT: Solution above won't work because writing string overwrites previously written numerical data, simpler and more intuitivesolution would be to replace

csvwrite(filename, d, 1);

by

dlmwrite(filename, d,'-append', 'delimiter', ',');

in original example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM