我的原始CSV文件看起来像第一张图片。我想用Matlab将其读入格式为第2张图片。我有超过1000个相同类型的CSV文件,如果我通过复制/粘贴这样做会很痛苦。我怎样才能做到这一点?任何例子?
原始数据:
输出数据:
答案 0 :(得分:0)
首先要意识到的是.csv文件的格式非常简单。您的上述文件实际上是一个纯文本文件,每行包含以下文本:
id,A001
height
a1,a2,a3
3,4,5
3,4,5
6,7,5
weight
a1,a2,a3
4,4,5
5,4,6
i6,7,5
因此,在Matlab中编写自己的解析器并不是那么难。您想使用
之类的命令fid = fopen('filename.csv','r');
L = fgetl(fid); % get a text line from the file
commas = find(L==','); % find where the commas are in the line
n1 = str2num(L(1:commas(1)-1); % convert the first comma-delimited number on line L
fidout - fopen('myfile.csv','w');
Lout = [ L(commas(2)+1:commas(3)-1) ', a1, a1'];
fwrite(fidout,Lout); % write a line out to the output file
fclose all; % close all open files.
首先读取各种变量中的各种值,然后安排它们写出你希望它们写出到输出文件的方式,这似乎很慢。但是一旦你开始滚动它将会非常快,你会发现自己非常了解文件中的内容,并且你会直接了解编写texscan.m
或csvwrite.m
之类的内容。等等。