How to get the length of a file in MATLAB?

痴心易碎 提交于 2019-11-30 22:56:31

Row Counter -- only loads one character per row:

Nrows = numel(textread('mydata.txt','%1c%*[^\n]'))

or file length (Matlab):

datfileh = fopen(fullfile(path, filename));
fseek(datfileh, 0,'eof');
filelength = ftell(datfileh);
fclose(datfileh);

I'm assuming you are working with text files, since you mentioned finding the number of rows. Here's one solution:

fid = fopen('your_file.dat','rt');
nLines = 0;
while (fgets(fid) ~= -1),
  nLines = nLines+1;
end
fclose(fid);

This uses FGETS to read each line, counting the number of lines it reads. Note that the data from the file is never saved to the workspace, it is simply used in the conditional check for the while loop.

It's also worth bearing in mind that you can use your file system's in-built commands, so on linux you could use the command

[s,w] = system('wc -l your_file.dat');

and then get the number of lines from the returned text (which is stored in w). (I don't think there's an equivalent command under Windows.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!