Effacer les filtres
Effacer les filtres

Using sscanf function in a for loop.

1 vue (au cours des 30 derniers jours)
Mark Coughlin
Mark Coughlin le 18 Avr 2020
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 commentaires
Ameer Hamza
Ameer Hamza le 18 Avr 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 le 18 Avr 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);

Connectez-vous pour commenter.

Réponse acceptée

Ameer Hamza
Ameer Hamza le 18 Avr 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);

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by