How do I load data files starting wih strings?

For class I was assigned to create a script that would read a .dat file and plot the data contained within. The problem I am having is that the data file is formated as follows:
x 0 y 0
x 1 y 1
x 2 y 4
x 3 y 9
However when I attempt to load the file into the workspace to work with it MATLAB returns the following error:
clear, clc
load xypts.dat
Error using load
Unknown text on line number 1 of ASCII file xypts.dat
"x".
Error in HW_9_13 (line 2)
load xypts.dat
I have read elsewhere that ASCII files connot contain strings, does this mean I am approaching the problem wrong? Is there another way to get the neccessary data into the workspace?

 采纳的回答

I'm not sure what you call ASCII files. Perhaps you meant text file. ASCII is a particular text encoding (which only allows 127 different characters), nowadays unicode is often used to encode text files.
I'm also not sure what you call string. A string is usually simply several characters together. Of course, any text file is simply a string of characters, so they're definitively allowed.
load however will only load text files that contain textual representation of numbers only, so indeed it cannot load your text file.
There are many options available to you. You could use textscan (with a format string of '%s%d%s%d') but probably the simplest would be to use readtable:
data = readtable('xypts.dat', 'ReadVariableNames', false); %not even sure the 'ReadVariableNames', false is needed

更多回答(1 个)

>> str = fileread('temp.txt');
>> str = regexprep(str,'\s+','');
>> mat = reshape(sscanf(str,'x%fy%f'),2,[]).'
mat =
0 0
1 1
2 4
3 9

类别

帮助中心File Exchange 中查找有关 Standard File Formats 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by