Reputation: 5791
I need to find normalized value for each value by column. So I have such function:
function [X_norm, mu, sigma] = featureNormalize(X)
X_norm = X;
mu = zeros(1, size(X, 2));
sigma = zeros(1, size(X, 2));
for x = 1:size(X, 1)
mu(1,x) = mean(:, x)
sigma(1,x) = std(:, x)
for y = 1:size(X, 2)
X_norm(x,y) = (X(x,y) - mu)/sigma
end
end
end
And I`m trying to call this function this way:
>> X = [23 32 2 ; 23 23 1];
>> featureNormalize(X)
As a result I get such error: no default value for argument 1 while calling function. I can't get what it's wrong here, any suggestions?
Upvotes: 0
Views: 1550
Reputation: 1631
I think there is a problem in way how you use the mean()
and std()
functions and also maybe subscripted assignment is an issue too.
I am not sure but please try these codes below as your function definition:
1. Row based normalization:
function [X_norm, mu, sigma] = featureNormalize(X)
X_norm = zeros(size(X));
mu = zeros(1, size(X, 1));
sigma = zeros(1, size(X, 1));
for x = 1:size(X, 1)
mu(x) = mean( X(x, :) );
sigma(x) = std( X(x, :) );
for y = 1 : size(X, 2)
X_norm(x, y) = ( X(x, y) - mu(x) ) / sigma(x);
end
end
end
2. Column based normalization:
function [X_norm, mu, sigma] = featureNormalize(X)
X_norm = zeros(size(X));
mu = zeros(1, size(X, 2));
sigma = zeros(1, size(X, 2));
for y = 1:size(X, 2)
mu(y) = mean( X(:, y) );
sigma(y) = std( X(:, y) );
for x = 1 : size(X, 1)
X_norm(x, y) = ( X(x, y) - mu(y) ) / sigma(y);
end
end
end
Upvotes: 2
Reputation: 221754
If you are calculating normalized values for each element with respect to the mean
and sigma
values for each column, I think you need to make some changes as your problem code doesn't really reflect that because you are using an array of mean
and sigma
values. So, I think you need to do something like this instead -
%// Initialize array for final normalized values
X_norm = zeros(size(X));
for x = 1:size(X, 2)
%// Store mean and standard deviation values for each column
mu = mean(X(:, x))
sigma = std(X(:, x))
%// Use an innermost loop to calculate the normalized values
%// for all the elements in each column.
%// Thus, for all these elements, you need to use the same mean
%// and standard deviation calculated in the previous step
for y = 1:size(X, 1)
X_norm(y,x) = (X(y,x) - mu)/sigma
end
end
You can very easily vectorize the above code with bsxfun
-
X_norm = bsxfun(@rdivide, bsxfun(@minus, X, mean(X,1)),std(X,[],1))
Upvotes: 2