Read data and make (x,y) coordinates from data

There is this data file that has the format where there is a letter x, space, then the x value, letter y, space, then the y value.
x 0 y 1
x 1.3 y 2.2
... (continued)
how can I write a script that will makes these x and y values into points and then plot them.
finally, it should close the file and say if it was closed successfully or not.
This is what I have so far:
load hw92.dat
FID = fopen(file, 'r');
if FID == -1
fprintf('ERROR CANNOT OPEN FILE TO READ!');
else
% I am not sure how to do make the (x,y) part
fclose(file);
end
Not sure how to do the rest of it.

 Accepted Answer

datacell = textscan(FID, 'x%fy%f', 'CollectData', 1);
xycoords = datacell{1};

8 Comments

I believe that helps to make the (x,y) coordinate but I am not able to check because something is wrong when I am loading the dat file. The error is:
EDU>> datahw92 Error using load Unable to read file 'hw92.dat': no such file or directory.
Error in datahw92 (line 5) load hw92.dat
Hi!
The error message says that the file does not exist. If you want to read the file with textscan (like Walter said), you don't load the file but open it. Replace
load hw92.dat
with
file = 'hw92.dat'
Be sure to be in the right folder or specify an absolute path!
And fclose(FID), not fclose(file)
I get a different outcome then I am needing. My script is:
file = 'hw92.dat';
FID = fopen(file, 'r');
if FID == -1
fprintf('ERROR CANNOT OPEN FILE TO READ!\n');
else
datacell = textscan(FID, 'x%fy%f', 'CollectData', 1);
xycoords = datacell{1};
fclose(FID);
end
I should get the (x,y) points that are converted to be plotted and displayed on a graph, however, I don't even know if it is being converted to (x,y) points?
Please attach your hw92.dat. Just to be clear, does hw mean homework ? If so, please "tag" your post with the "homework" tag above below your original question.
Trying not to give away the answer here: (1) if B were a numeric array with two columns, how would you extract the first column from it? (2) Consider using plot() with appropriate arguments.
x 0 y 1
x 1.3 y 2.2
x 2.2 y 6
x 3.4 y 7.4
x 4.2 y 5.5
x 4.4 y 4.5
x 6.2 y 7.8
x 7.7 y 11.1
x 8.2 y 11.5
x 9.9 y 15.2
x 7.2 y 9.5
x 8.9 y 12.5
Okay, and after you use the code that you posted, what does the variable xycoords contain?

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!