Clear Filters
Clear Filters

Using sscanf function in a for loop.

1 view (last 30 days)
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 Comments
Ameer Hamza
Ameer Hamza on 18 Apr 2020
The statement of this question makes me think it is a task for a homework. What have you already tried?
Mark Coughlin
Mark Coughlin on 18 Apr 2020
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);

Sign in to comment.

Accepted Answer

Ameer Hamza
Ameer Hamza on 18 Apr 2020
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);

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!