八度错误:调用函数时参数1没有默认值

时间:2015-01-31 19:52:43

标签: matlab octave

我需要按列查找每个值的normalized值。 所以我有这样的功能:

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

我试图以这种方式调用此函数:

>> X = [23 32 2 ; 23 23 1];
>> featureNormalize(X)

结果我得到了这样的错误:在调用函数时没有参数1的默认值。我不能在这里得到它的错误,有什么建议吗?

2 个答案:

答案 0 :(得分:2)

我认为您使用mean()std()函数的方式存在问题,也可能是下标分配问题。

我不确定,但请尝试以下代码作为您的功能定义:

<强> 1。基于行的规范化:

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。基于列的标准化:

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

答案 1 :(得分:2)

如果您针对每个meansigma值计算每个元素的规范化值,我认为您需要进行一些更改作为您的问题代码并没有真正反映出这一点,因为您使用的是meansigma值的数组。所以,我认为你需要做这样的事情 -

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

您可以使用 bsxfun -

轻松向量化上述代码
X_norm = bsxfun(@rdivide, bsxfun(@minus, X, mean(X,1)),std(X,[],1))