【问题标题】:matlab, how to export text and numerical data to a excel csv file?matlab,如何将文本和数值数据导出到excel csv文件?
【发布时间】:2012-12-19 09:48:33
【问题描述】:

当我使用下面的代码时。我正确导出了数字数据,但是当每列的第一行应该有标题(标题)时,第一行是空白的。有什么解决办法吗?

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);

【问题讨论】:

    标签: excel matlab text csv export


    【解决方案1】:

    您在写入数字数据时正在擦除字符串,只运行您的脚本直到数字数据 - 它工作正常。只需切换操作顺序——先写数字,再写字符串,就可以了。

    编辑: 上面的解决方案是行不通的,因为写入字符串会覆盖之前写入的数值数据,更简单直观的解决方案是替换

    csvwrite(filename, d, 1);
    

    通过

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

    在原始示例中

    【讨论】:

    • 标头工作正常,但数据写入不正确。我只得到 2 行随机数据
    • 没错,它会覆盖数字数据,看起来 dlmwrite 无论如何都是更好的选择...
    • 您是否有运气让文本和数字数据都正确显示在 csv 文件中?我可以得到或。但并非两者都正确。谢谢!
    • 是的,如果我只是替换 csvwrite(filename, d, 1); by dlmwrite(filename, d,'-append', 'delimiter', ',');在您的原始示例中(不修改任何其他内容) - 它显示正确。
    • 完美运行。多谢。我将不得不查找 dlmwrite 以了解它的作用。欣赏它!
    猜你喜欢
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多