MATLAB获取文本的行数

有时会需要获取文本的行数,matlab虽然没有提供直接的函数,但是实现也来也很简单。

下面给出代码。


function lines = get_lines(fid)
% This function can be used to get the lines of a plain text file.
% Input:
% fid: id of the file
% Output:
% lines: lines of the input file.
% Powered by Xianbao Duan
% Email: Xianbao.d@gmail.com
% Website: http://www.52souji.net/

lines = 0;
while ~feof(fid)
fgetl(fid);
lines = lines + 1;
end


使用时,需要先打开文件,将文件的ID传递给该函数。类似以下:

fid = fopen('test.txt');
lines = get_lines(fid);

如果你有更简单的方法,请告诉我。谢谢!

标签: matlab

相关文章推荐

添加新评论 (无需注册,可直接评论)