在MATLab中创建一个.csv文件,其中包含以下多列上方的一列标题信息

时间:2016-05-11 14:26:55

标签: matlab csv

我正在尝试更新数据库文件。文件结构有1列值,用于前40行(我将其视为字符串),然后是3-4列数据。我能够将数据导入MATLab并执行我需要的操作,但我不知道如何导出数据,从前40行中删除逗号并在顶部写入标题信息。

最终我想迭代这个来为文件夹中的所有文件替换所有负数到-999。

Example data of desired format:
/secchi_depth=3.2
/cloud_percent=NA
/wind_speed=24
/wave_height=0.3
!
! COMMENTS
!
!
!
!
!
/missing=-999
/delimiter=comma
/fields=wavelength,ag,ap,ad
/units=nm,1/m,1/m,1/m
/end_header
400,1.276121,0.335431,0.135773
402,1.231213,0.337944,0.133908
404,1.187686,0.340812,0.131316

到目前为止我写的代码:

filename = uigetfile;


%IMPORTFILE(FILETOREAD1)
%  Imports data from the specified file
%  FILETOREAD1:  file to read

%  Auto-generated by MATLAB on 10-May-2016 17:16:37

% Import the file
newData1 = importdata(filename);

% Create new variables in the base workspace from those fields.
vars = fieldnames(newData1);
for i = 1:length(vars)
    assignin('base', vars{i}, newData1.(vars{i}));

end

[r,~] = size(textdata)
[~,c] = size(data)

data(data<0) = -999


csvwrite('Test.csv',data,r,0)

1 个答案:

答案 0 :(得分:0)

比它看起来容易。使用dlmwrite ...

假设我们Header数组中的cell维度为Hx1,而Data位于数字数组中且维度为MxN。

%% Write Header
dlmwrite('Test.csv',Header{1},'');           %% Write first row with no delimiter
for line={Header{2:end}}'                    %% Assign rest of the Header to line and loop over its elements
  dlmwrite('Test.csv',line,'','-append');    %% Append every line with no delimiter
end

%% Write the Data
dlmwrite('Test.csv',Data,'-append')          %% Append Data with default delimiter - comma