x 0 y 1
x 1.3 y 2.2
The format of every line in the file is the letter ‘x’, a space, the x value,
space, the letter ‘y’, space, and the y value. First, create the data file
with 10 lines in this format. Do this by using the Editor/Debugger, then
File Save As xypoints.dat. The script will attempt to open the data file
and error-check to make sure it was opened. If so, it uses a for loop
and fgetl to read each line as a string. In the loop, it creates x and y
vectors for the data points. After the loop, it plots these points and
attempts to close the file. The script should print whether or not the
file was successfully closed.
Ch9Ex12.m
%Read data points from "xypoints.dat" and plot them
fid = fopen('xypoints.dat');
if fid == -1
disp('File open not successful')
else
%Initialize x vector and y vector
xvec = 1:10;
yvec = 1:10;
for i = 1:10
aline = fgetl(fid);
%Separate each line into two parts: x and y
[x, rest] = strtok(aline,'y');
x(1:2) = []; %Removes the "x" and the space
[let, y] = strtok(rest);
xvec(i) = str2num(x);
yvec(i) = str2num(y);
end
plot(xvec,yvec,'ko')
xlabel('x')
ylabel('y')
title('Points from file "xypoints.dat"')
%Error-check file close
closeresult = fclose(fid);
if closeresult == 0
disp('File close successful')
else
disp('File close not successful')
end
end
need an explanation for this answer? contact us directly to get an explanation for this answer