0

I am not sure why this code wouldn't run. PLEASE HELP

function y = PdfMixUnfmBeta(x,alpha)
    if x < 0 
y = (1-alpha).*1/2;
    elseif x >= 0 
y = (1-alpha).*1/2 + alpha.*6*x*(1-x);
end;

when I execute this function as follows, there is an error

EDU>> x=-1:0.01:1;
EDU>> a=PdfMixUnfmBeta(x,0.4)
Error in PdfMixUnfmBeta (line 2)
if x < 0 
1
  • I'm guessing you typed it in at the command line, or maybe you tried to "run" the function. It is time to start reading the manuals. Learn what functions are and how to define them. Commented Jun 2, 2013 at 1:48

1 Answer 1

0

The problem with your function is that you have written it assuming that x is a single value, and then you have passed it a vector. Your code cannot cope with this.

If you try to run your code with a single value, eg: a=PdfMixUnfmBeta(15,0.4) your function should run.

Lets look at what is actually wrong with your code, when I tried running your code I was given the following error:

Output argument "y" (and maybe others) not assigned during call

This indicates that the lines which assign to y are never actually executed. This indicates that neither of the conditional statements (x < 0 and x >= 0) ever evaluate as true. The if statements expects a scalar logical value, but in your example it is provided with a vector of logical.

So, to fix this you either need to deal with your x values one at a time by wrapping it in a for loop, e.g.:

function y = PdfMixUnfmBeta(x_vec, alpha)
  for x = x_vec
    %do your function here
  end
end

Alternatively, you can vectorize your code, which is by far the preferable solution:

y = zeros(1,length(x));
% where x is < 0 use this formula
y(x < 0) = (1-alpha) .*(1/2); 
% where x is >= 0 use this formula instead.
y(x >= 0) = (1-alpha) .* (1/2) + (alpha .* 6 .* x .* (1-x)); 

In the above solution I use logical indexing and change some of the * to .*. You may find it useful to look up the difference between * and .* and to read up on vectorization.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.