📄 readdata.m
字号:
% Read data file including labels.
%
% [data,labels] = readdata(filename,dlm)
%
% filename name of file to be read
% dlm delimeter character
function [data,labels,classes] = readdata(filename,dlm)
delims = [',',' ',' '];
data = [];
labels = [];
no = 0; % Number of labels found
maxlength=50; % max length of label strings
eol = 10;
%%%%%%%%%%%%%%%%% Auto find delimeter character
file = fopen(filename);
if file ~= -1
l = fgets(file); % Obtain entire string of labels
i=1;
while isempty(findstr(delims(i),l))&i<=size(delims,2)
i=i+1;
end
if i>size(delims,2)
disp('Error couldnot determine delimting character!');
else
dlm = delims(i);
end
end
%%%%%%%%%%%%%%%%% Read labels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
file = fopen(filename);
if file ~= -1
l = fgets(file); % Obtain entire string of labels
if isempty(str2num(l))
is=1; % start index of current string
ie=1; % end index of current string
finished = 0; % flag to detect when end of line is reached
while(finished == 0)
while (l(ie) ~= dlm) & (l(ie) ~= eol) % find next delimeter
ie = ie+1;
end
no = no+1; % have found a new label
%labels = [labels;zeros(1,maxlength)];
labels(no,1:ie-is) = l(is:ie-1);
ie = ie+1; % move past delimeter
is = ie; % reset start index ready for nect string
if ie >= length(l)
finished = 1;
end
end
else
labels = [];
end
fclose(file);
labels = char(labels); % convert to character array format
%%%%%%%%%%%%%%%%% Read data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% data = dlmread(filename,dlm);
data = dlmread2(filename,dlm);
% Check that the first line contains labels
% Check to see if last column is a text label
NoColumns = countdlm(filename,dlm);
if (size(data,2)>NoColumns+1)
% Must have a string
class = data(:,NoColumns+1:size(data,2));
clabel=[];
clabel = char(class); % Copy labels as strings
data = data(:,1:NoColumns); % Remove labels from data
% Check that last string is not left with an EOF char making it different from otherwise identical labels
for j=1:size(clabel(size(clabel,1),:),2)
if abs(clabel(size(clabel,1),j)) < 32
clabel(size(clabel,1),j) = 13;
break
end
end
% Now assign numeric class labels for each text label
temp = clabel; % copy to a working variable
no = 0; % number of distinct class labels
while ~isempty(temp)
no=no+1;
classes(no,:) = temp(1,:); % find next distinct label
i=1;
while i<=size(temp,1)
if strcmp(temp(i,:),classes(no,:))
temp(i,:)=[]; % remove repetitions
else
i=i+1; %try next label
end
end
end
% Now augment data array with numeric class labels
% where number = index of label text in classes
for i=1:size(data,1)
for j=1:no
if strcmp(classes(j,:),clabel(i,:))
cnumber(i)=j;
end
end
end
data = [data,cnumber'];
% Replace non-printing chars with spaces
for i=1:no
for j=1:size(classes(i,:),2)
if abs(classes(i,j))<32
classes(i,j) = ' ';
end
end
end
else
classes=[];
end
else
disp('Error couldnot open file!');
end
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -