逐行读取MATLAB中的文本文件

Hos*_*ein 17 csv file-io matlab file

我有一个CSV文件,我想阅读这个文件,并在每一行上做一些预计算,看看例如该行对我有用,如果是,我将它保存到一个新的CSV文件.有人可以举个例子吗?在更多细节中,这是我的数据的样子:(string,float,float)数字是坐标.

ABC,51.9358183333333,4.183255
ABC,51.9353866666667,4.1841
ABC,51.9351716666667,4.184565
ABC,51.9343083333333,4.186425
ABC,51.9343083333333,4.186425
ABC,51.9340916666667,4.18688333333333
Run Code Online (Sandbox Code Playgroud)

基本上我想在新文件中保存距离超过50或50的行.还应复制字符串字段.谢谢

gno*_*ice 9

你实际上可以xlsread用来完成这个.首先将上面的示例数据放在一个文件中之后'input_file.csv',下面是一个示例,说明如何从以下三个输出中获取文件中的数值,文本值和原始数据xlsread:

>> [numData,textData,rawData] = xlsread('input_file.csv')

numData =     % An array of the numeric values from the file

   51.9358    4.1833
   51.9354    4.1841
   51.9352    4.1846
   51.9343    4.1864
   51.9343    4.1864
   51.9341    4.1869


textData =    % A cell array of strings for the text values from the file

    'ABC'
    'ABC'
    'ABC'
    'ABC'
    'ABC'
    'ABC'


rawData =     % All the data from the file (numeric and text) in a cell array

    'ABC'    [51.9358]    [4.1833]
    'ABC'    [51.9354]    [4.1841]
    'ABC'    [51.9352]    [4.1846]
    'ABC'    [51.9343]    [4.1864]
    'ABC'    [51.9343]    [4.1864]
    'ABC'    [51.9341]    [4.1869]
Run Code Online (Sandbox Code Playgroud)

然后,您可以对数字数据执行所需的任何处理,然后使用将数据行的子集重新保存到新文件xlswrite.这是一个例子:

index = sqrt(sum(numData.^2,2)) >= 50;  % Find the rows where the point is
                                        %   at a distance of 50 or greater
                                        %   from the origin
xlswrite('output_file.csv',rawData(index,:));  % Write those rows to a new file
Run Code Online (Sandbox Code Playgroud)


Adr*_*ien 7

如果您真的想逐行处理文件,可能会使用fgetl以下解决方案:

  1. 用.打开数据文件 fopen
  2. 使用将下一行读入字符数组 fgetl
  3. sscanf在您刚刚阅读的字符数组上检索所需的数据
  4. 执行任何相关测试
  5. 将您想要的内容输出到另一个文件
  6. 如果尚未到达文件末尾,请返回第2点.

与前面的答案不同,这不是Matlab的风格,但它对非常大的文件可能更有效.

希望这会有所帮助.


yuk*_*yuk 7

您无法使用csvread读取文本字符串.这是另一个解决方案:

fid1 = fopen('test.csv','r'); %# open csv file for reading
fid2 = fopen('new.csv','w'); %# open new csv file
while ~feof(fid1)
    line = fgets(fid1); %# read line by line
    A = sscanf(line,'%*[^,],%f,%f'); %# sscanf can read only numeric data :(
    if A(2)<4.185 %# test the values
        fprintf(fid2,'%s',line); %# write the line to the new file
    end
end
fclose(fid1);
fclose(fid2);
Run Code Online (Sandbox Code Playgroud)


Adr*_*ian 5

只需在一个块中将其读入MATLAB即可

fid = fopen('file.csv');
data=textscan(fid,'%s %f %f','delimiter',',');
fclose(fid);
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用逻辑寻址处理它

ind50 = data{2}>=50 ;
Run Code Online (Sandbox Code Playgroud)

然后,ind50是第2列大于50的行的索引

data{1}(ind50)
Run Code Online (Sandbox Code Playgroud)

将列出感兴趣的行的所有字符串.然后只需使用fprintf将数据写入新文件