Using sscanf function in a for loop.

1 次查看(过去 30 天)
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