Error using sum.Invalid data type. First argument must be numeric or logical.

I want to calculate the mean value but its cannot calculate that and giving error.
%%%%%%%%%%%%%%%%error%%%%%%%%%%%%%
Error using sum
Invalid data type. First argument must be numeric or logical.
Error in mean (line 116)
y = sum(x, dim, flag) ./ size(x,dim);
Error in featureNormalize (line 7)
mu = mean (X);
Error in trynsl (line 14)
X_n = featureNormalize(X);
%%%%functioncode%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function[X_norm,mu,sigma] = featureNormalize(X)
X_norm = X;
mu = zeros(1, size(X, 2));
sigma = zeros(1, size(X, 2));
mu = mean (X);
for i=1:size(X, 2)
X(:,i) = X(:,i) - mu(i);
end
sigma = std (X);
for i=1:size(X, 2)
X(:,i) = X(:,i) ./ sigma(i);
end
X_norm = X;
end

6 个评论

What is class(X) ?
I predict that X is a cell array.
this the code in which i call that function.X was cell array but further i convrt it into table.
%%%%%%%%Code%%%%%%%%%%
fid = fopen('KDDTrain+.txt','r');
data = textscan(fid,repmat('%s',1,43),'delimiter',',','CollectOutput',true);
data = data{1};
fclose(fid);
data(:,1) = num2cell(str2double(data(:,1)) );
data(:,5:41) = num2cell(str2double(data(:,5:41)) );
data(:,43) = num2cell(str2double(data(:,43)) );
%X = cell2mat(data); % convert cell to matrix
X= cell2table(data);
% Before normalization separate the output from the file
y = X(:,42);
X(:,42) = [ ];
X_n = featureNormalize(X);
%If there is any column with NaN values, remove it
X_n = X_n(:,all(~isnan(X_n)));
X_n = [ones(length(X_n), 1) X_n]; %add a new column with 1's
Thankyou for your help now it's given this error
at doing this %% X_n = featureNormalize(X{:,:});
Error using trynsl (line 15)
Unable to concatenate the table variables 'data1' and 'data2', because their types are double and cell
Your columns 2, 3, and 4 are character vectors. You cannot normalize character vectors.
Note that your y is a table that contains a single variable that is character vectors.
Note by the way that you can do things like,
fmt_cell = repmat({'%d'}, 1, 43);
fmt_cell([2:4, 42]) = {'%s'};
fmt = [fmt_cell{:}];
data = textscan(fid,fmt,'delimiter',',','CollectOutput',true);
d1 = data{1}; %numeric
d2_4 = data{2}; %character
d5_41 = data{3}; %numeric
y = data{4}; %character
d43 = data{5};
X = [d1, d5_41, d43];
X_n = featureNormalize(X);
it stills not working properly
Error in featureNormalize (line 12)
sigma = std (X);
Error in trynsl (line 25)
X_n = featureNormalize(X);
code
function[X_norm,mu,sigma] = featureNormalize(X)
X_norm = X;
mu = zeros(1, size(X, 2));
sigma = zeros(1, size(X, 2));
mu = mean (X);
for i=1:size(X, 2)
X(:,i) = X(:,i) - mu(i);
end
sigma = std(X);
for i=1:size(X, 2)
X(:,i) = X(:,i) ./ sigma(i);
end
X_norm = X;
end

请先登录,再进行评论。

回答(0 个)

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by