필터 지우기
필터 지우기

Using sscanf function in a for loop.

조회 수: 1 (최근 30일)
Mark Coughlin
Mark Coughlin 2020년 4월 18일
답변: Ameer Hamza 2020년 4월 18일
Write a script which will use the function uigetfile to read in the name of a file to open in the script. The function fopen is used to open the file, the contents of this file is shown below. The function fgetlis used to read in a line, as can be seen below; this line will contain the character 7. The function sscanfshould be used to convert this to an integer. This will be used to form a for loop which will read in the rest of the lines. The contents of these lines will be converted to the points of the sine curve using sscanf. The function should then plot the data contained in the file as a 2-D line plot.
The file contains the data:
7
0 0.000
15 0.2588
30 0.5000
45 0.7071
60 0.8660
75 0.9659
90 1.0000
  댓글 수: 2
Ameer Hamza
Ameer Hamza 2020년 4월 18일
The statement of this question makes me think it is a task for a homework. What have you already tried?
Mark Coughlin
Mark Coughlin 2020년 4월 18일
Hi Ameer,
This is a practice question in a previous exam paper for which I will not get the solution for. I have tried the following:
[filename,pathname]=uigetfile('*.txt');
if filename==0
return
end
fileID=fopen([pathname,filename]);
textline=fgetl(fileID);
n=sscanf(textline,'%f',[1 1]);
linecount=1;
for i=1:n
textline=fgetl(fileID);
[output]=sscanf(textline,'%f %f',[1 2]);
end
x(i,1)=output(1);
sinx(i,2)=output(2);
xmin=min(x);
xmax=max(x);
plot(x,sinx);
xlabel('x');
ylabel('sinx');
title('Sine Curve');
xlim([xmin xmax]);
fclose(fileID);

댓글을 달려면 로그인하십시오.

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 4월 18일
Compare it with your code to find the differences.
[filename,pathname]=uigetfile('*.txt');
if filename==0
return
end
fileID=fopen([pathname,filename]);
textline=fgetl(fileID);
n=sscanf(textline,'%f',[1 1]);
linecount=1;
output = zeros(n,2);
for i=1:n
textline=fgetl(fileID);
output(i,:)=sscanf(textline,'%f %f',[1 2]);
end
x=output(:,1);
sinx=output(:,2);
xmin=min(x);
xmax=max(x);
plot(x,sinx);
xlabel('x');
ylabel('sinx');
title('Sine Curve');
xlim([xmin xmax]);
fclose(fileID);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by