How can I import ordered pairs of data from a text file?

3 views (last 30 days)
I'm a beginner with Matlab and I have file that looks like the following (but with more data points eventually):
(1,2) (3,4)
(5,6) (7,8)
How can I important this data into matlab?

Accepted Answer

dpb
dpb on 18 Oct 2015
Alternatively to Per's "most excellent" answer and perhaps a little easier for the neophyte to see on the format string--
dat=cell2mat(textscan(fid,'(%f,%f) (%f,%f)','collectoutput',1));
a=dat(:,1:2);
b=dat(:,3:4);
cell2mat goes ahead and removes the cell array so don't need the {} addressing for the cells and the format string matches the embedded characters in the file excluding the data fields.
  2 Comments
per isakson
per isakson on 18 Oct 2015
Edited: per isakson on 18 Oct 2015
This is better because it is easier to read.
dpb
dpb on 18 Oct 2015
@per -- don't know about "better", just the "dead-ahead" solution instead of the more general. No idea if one would have any advantage over the other on parsing speed in a large file, for example.
I DO very much wish there was, however, a 'matrixoutput','true'|'false' named parameter pair, however, to let one return the data results as ordinary array instead of only cell arrays being possible, however.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!