Using sscanf function in a for loop.
3 views (last 30 days)
Show older comments
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
on 18 Apr 2020
The statement of this question makes me think it is a task for a homework. What have you already tried?
Accepted Answer
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);
0 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!