加载混合数字和字符串数据

时间:2015-06-10 17:28:25

标签: matlab file-io

我是matlab的新手。我有一个名为iris.data的文件,我正在尝试将其内容加载到变量中。该文件包含以下内容:

5.1,3.5,1.4,0.2,Iris-setosa
4.9,3.0,1.4,0.2,Iris-setosa
4.7,3.2,1.3,0.2,Iris-setosa
4.6,3.1,1.5,0.2,Iris-setosa
5.0,3.6,1.4,0.2,Iris-setosa
5.4,3.9,1.7,0.4,Iris-setosa
4.6,3.4,1.4,0.3,Iris-setosa
5.0,3.4,1.5,0.2,Iris-setosa
4.4,2.9,1.4,0.2,Iris-setosa
4.9,3.1,1.5,0.1,Iris-setosa
5.4,3.7,1.5,0.2,Iris-setosa
4.8,3.4,1.6,0.2,Iris-setosa
4.8,3.0,1.4,0.1,Iris-setosa

我试过了:

load iris.data

但我得到了:

Error using load
Unknown text on line number 1 of ASCII file iris.data
"Iris-setosa". 

为什么它给了我这个错误,或者我完全走错了方向,而且还有更好的方法。

谢谢!

2 个答案:

答案 0 :(得分:1)

要阅读文件内容,您可以使用:

filename = 'filename.extension';
fileID = fopen(filename);
fileData = fread(fileID);
fclose(fileID);

数据现在位于工作区的fileData变量中。 要获取字符串中的数据,请使用fileStr = char(fileData)'

答案 1 :(得分:1)

如果您完全不知道如何导入数据,只需使用导入数据GUI 并生成脚本。 enter image description here

这就是你的案例:

%% Initialize variables.
filename = 'C:\Users\Robert Seifert\Desktop\SO\data.txt';
delimiter = ',';

%% Format string for each line of text:
%   column1: double (%f)
%   column2: double (%f)
%   column3: double (%f)
%   column4: double (%f)
% For more information, see the TEXTSCAN documentation.
formatSpec = '%f%f%f%f%*s%[^\n\r]';

%% Open the text file.
fileID = fopen(filename,'r');

%% Read columns of data according to format string.
% This call is based on the structure of the file used to generate this
% code. If an error occurs for a different file, try regenerating the code
% from the Import Tool.
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter,  'ReturnOnError', false);

%% Close the text file.
fclose(fileID);

%% Post processing for unimportable data.
% No unimportable data rules were applied during the import, so no post
% processing code is included. To generate code which works for
% unimportable data, select unimportable cells in a file and regenerate the
% script.

%% Create output variable
data = [dataArray{1:end-1}];
%% Clear temporary variables
clearvars filename delimiter formatSpec fileID dataArray ans;

你得到:

data =

    5.1000    3.5000    1.4000    0.2000
    4.9000    3.0000    1.4000    0.2000
    4.7000    3.2000    1.3000    0.2000
    4.6000    3.1000    1.5000    0.2000
    5.0000    3.6000    1.4000    0.2000
    5.4000    3.9000    1.7000    0.4000
    4.6000    3.4000    1.4000    0.3000
    5.0000    3.4000    1.5000    0.2000
    4.4000    2.9000    1.4000    0.2000
    4.9000    3.1000    1.5000    0.1000
    5.4000    3.7000    1.5000    0.2000
    4.8000    3.4000    1.6000    0.2000
    4.8000    3.0000    1.4000    0.1000

你得到的剧本评论得非常好,几乎可以在任何情况下应用它并学习;)