在MATLAB中逐行读取文本文件 [英] Reading a text file in MATLAB line by line
问题描述
我有一个CSV文件,我想读取这个文件,并对每行进行一些预先计算,看看例如该行对我有用,如果是的话,我将其保存到一个新的CSV文件。
有人能给我一个例子吗?
更多细节这是我的数据如何:(string,float,float)数字是坐标。
I have a CSV file, I want to read this file and do some pre-calculations on each row to see for example that row is useful for me or not and if yes I save it to a new CSV file. can someone give me an example? in more details this is how my data looks like: (string,float,float) the numbers are coordinates.
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
基本上我想保存一个新文件中距离大于50或50的行。字符串字段也应该被复制。
感谢
basically i want to save the rows that have for distances more than 50 or 50 in a new file.the string field should also be copied. thanks
推荐答案
您可以使用 XLSREAD 来完成此操作。首先将上面的示例数据放在一个文件'input_file.csv'
中,这里是一个如何获取数值,文本值和原始数据的示例来自 XLSREAD 的三个输出中的文件:
You could actually use XLSREAD to accomplish this. After first placing your sample data above in a file 'input_file.csv'
, here is an example for how you can get the numeric values, text values, and the raw data in the file from the three outputs from 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]
需要对数字数据,然后使用 XLSWRITE 。例如:
You can then perform whatever processing you need to on the numeric data, then resave a subset of the rows of data to a new file using XLSWRITE. Here's an example:
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
这篇关于在MATLAB中逐行读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!