How do you get MATLAB to repeat the fgetl or fgets command n times
조회 수: 10 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
채택된 답변
Walter Roberson
2013년 8월 2일
fid=fopen('mydata.csv');
for K = 1 : n
a = fgets(fid);
fwrite(1, a); %display it
end
fclose(fid);
댓글 수: 2
dpb
2013년 8월 2일
편집: dpb
2013년 8월 3일
K is defined in the for loop--it takes on the values 1:n in sequence.
doc for % for details
Of course, in the above loop it's only used as the counter against the 'n' limit.
The form as Walter wrote it is a script so all variables are in the workplace. You already have/had a variable n defined or it would have errored--
>> clear n
>> for i=1:n,disp(i),end
Undefined function or variable 'n'.
>>
As for how a is "assuming" multiple values, a is assigned the returned value from the call to fgets on each pass thru the loop--which is the entity actually doing the work of reading a record from the file. After each read, the internal file position is left pointing to the beginning of the next record so the subsequent call picks up from there.
It's time to begin at the beginning... :) Open the doc's and start with the "Getting Started" topic and read thru the tutorials.
추가 답변 (1개)
dpb
2013년 8월 2일
편집: dpb
2013년 8월 3일
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
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Graphics Object Identification에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!