Gugu
Gugu

Reputation: 17

Convert operator from Matlab to R

I have below code in Matlab:

alpha=5.5; beta=3.1; a=0; b=1; c=2.5;
X=0; Y=c; % Initial values
while Y > gamma(alpha+beta)/gamma(alpha)/gamma(beta)...
* X.^(alpha-1).* (1-X).^(beta-1);
U=rand; V=rand; X=a+(b-a)*U; Y=c*V;
end; 
X;

and I want to convert to R. This is my attempt (something is wrong in operators):

alpha <- 5.5
beta <- 3 .1
a <- 0
b <- 1
c <- 2.5
X <- 0
Y <- c
while(Y > gamma(alpha+beta)/gamma(alpha)/gamma(beta)) 
{
*X.^(alpha-1).*(1-X).^(beta-1) # incorrect line
U=runif(1, 0, 1)
V=runif(1, 0, 1)
X=a+(b-a)*U
Y=c*V
}
print (X)

Upvotes: 0

Views: 90

Answers (1)

mlegge
mlegge

Reputation: 6913

The beta had an invalid assignment and you needed the { on the same line as the while:

alpha <- 5.5
beta <- 3.1
a <- 0
b <- 1
c <- 2.5
X <- 0
Y <- c
while (Y > gamma(alpha + beta)/gamma(alpha)/gamma(beta) * X^(alpha - 1) * (1 - X)^(beta - 1)) {
    U <- runif(1, 0, 1)
    V <- runif(1, 0, 1)
    X <- a + (b - a) * U
    Y <- c * V
} 

Check your code to make sure you are doing what you think you are doing, no assignment is being done on the line after the while, the loop kept exiting immediately for me (but running without error) and printing 0 for X.

EDIT: Runs correctly now thanks to the nice spot by @Khashaa

Upvotes: 1

Related Questions