Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

normpdf behaves strangely

In the following manner,

function ret = f(pIx5, dS)
    sigma = 1;    

    rho = dS(1);
    theta = dS(2);

    mu_x = rho*cos(theta);

    display(pIx5);
    display(mu_x);

    pdf = normpdf(pIx5, mu_x, sigma);

    ret = max(pdf);
end

I get the following error message,

pIx5 =
       54   65   11    0    0

mu_x =
       11.9218

Error using normpdf (line 36) Non-scalar arguments must match in size.

Error in f (line 11)

        pdf = normpdf(pIx5, mu_x, sigma);

But, it works fine in the following manner,

function ret = f(pIx5, dS)
    sigma = 1;    

    rho = dS(1);
    theta = dS(2);

    pIx5 = [54,65, 11, 0, 0];

    mu_x = 11.9218;

    display(pIx5);
    display(mu_x);

    pdf = normpdf(pIx5, mu_x, sigma);

    ret = max(pdf);
end

What is going on here?

like image 393
user366312 Avatar asked Dec 23 '22 16:12

user366312


1 Answers

I'm willing to bet significant amounts of money that the problem is with the type of your input pIx5. Note this:

>> pdf = normpdf([54 65 11 0 0], 11.9218, 1);  % Works fine
>> pdf = normpdf(uint8([54 65 11 0 0]), 11.9218, 1);
Error using normpdf (line 36)
Non-scalar arguments must match in size.

Why does it give a size error for what should be something related to the type? Taking a look at the code for normpdf answers that. From lines 33-37, R2016b:

...
try
    y = exp(-0.5 * ((x - mu)./sigma).^2) ./ (sqrt(2*pi) .* sigma);
catch
   error(message('stats:normpdf:InputSizeMismatch'));
end

Basically, any error in evaluating that equation is reported as a size mismatch error. In this case, it is actually an issue with exp not working for integer data types (it only support single and double types):

>> x = uint8([54 65 11 0 0]);
>> mu = 11.9218;
>> sigma = 1;
>> y = exp(-0.5 * ((x - mu)./sigma).^2) ./ (sqrt(2*pi) .* sigma);
Undefined function 'exp' for input arguments of type 'uint8'.

The solution then? Just cast your offending inputs to single or double first:

pdf = normpdf(double(pIx5), mu_x, sigma);
like image 151
gnovice Avatar answered Dec 29 '22 23:12

gnovice