How do you get MATLAB to repeat the fgetl or fgets command n times
이전 댓글 표시
So my script is this, so far.
fid=fopen('mydata.csv');
a = fgets(fid);
fclose(fid);
This returns the first line of my .csv file.
But what I want is for the script to repeat the command for say the first n rows, then display only those rows. How can I do that?
채택된 답변
추가 답변 (1개)
fid=fopen('mydata.csv');\
s=input('How many lines do you wish to display? ', 's');
N=str2num(s);
for i=1:N
disp(fgetl(fid))
end
fid=fclose(fid);
Add error checking on input string for valid number, etc., etc., ...
댓글 수: 6
Sarutahiko
2013년 8월 2일
It's simply what fgetl() (*) does--it returns the next line in the file; that's all and it has no additional parameters other than the file handle from which to read that one record. Hence, there's no flexibility built into it; it's a one-note song.
Again, I commend to your attention
doc fgetl % for details
() I used *fgetl instead of fgets that you asked about because of the difference in how they handle the trailing \n -- for viewing I presumed you wouldn't want all the extra blank lines showing up as fgets returns it in the returned string whereas fgetl doesn't. Try replace fgetl w/ fgets to see the difference.
Again, read the documentation.
And, btw, when you look at writing the file you'll want to treat the \n differently in that new file than at the display for viewing--if you use fgetl to not see the blank lines on the screen then you'll need to use a \n in the format string when you write the new file to get the record terminaters therein. Or alternatively if you do use fgets instead, then the \n will be in the string already and you don't need to add it again--and in fact will not want to or you'll do the same thing in the file as the appearance is on the display.
Sarutahiko
2013년 8월 2일
편집: Sarutahiko
2013년 8월 2일
dpb
2013년 8월 2일
Chuckles... :)
Yeah, there is a lot to get a grasp on, granted...
Walter Roberson
2013년 8월 3일
Note,
s=input('How many lines do you wish to display? ')
should be
s=input('How many lines do you wish to display? ', 's');
if you are going to use str2num() on the result.
dpb
2013년 8월 3일
Yep, good catch...I'll edit it now...intended to avoid the eval() w/ possible unwanted side effects depending on what user happens to input.
카테고리
도움말 센터 및 File Exchange에서 Timetables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!