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

Loading mixed numeric and string data

我是 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". 

为什么会出现这个错误,或者我完全走错了方向,还有更好的方法。

谢谢!!

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

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

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

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

这就是您的情况:

%% 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

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