[R] Matlab code to R code

Berend Hasselman bhh at xs4all.nl
Mon Oct 22 10:29:03 CEST 2012


On 22-10-2012, at 09:49, Roslina Zakaria wrote:

> Dear r-users,
> 
> I would like to convert my Matlab code to R-code, however it dies not work as expected.  Hope somebody can help me to match Matlab and r codes.
> 
> R code:
> 
> rr <- function(r,cxn)
> {
> tol <- 1E-4;
> 
> for(i in 1:n)
> {
> t1 <- (1+(i-1)*r)*log((1+(i-1)*r))
> t2 <- (i-1)*(1-r)*log(1-r)
> rri <- ((t1+t2)/i*log(i))-cxn

The first ( in the expression for rri is misplaced and should be moved to just after the / by comparing to the expression for f in the Matlab code.


> rr <- rri > tol
> }
> round(rr,4)
> }
> rr1 <- rr(0.5,0.0242) ; rr1
> 

What is this function supposed to do? Incomprehensible.
In the for with i rri is compared to tol and rr becomes a logical.
After the loop is finished rr is equal to the last value of rr for i==n.
So you could just as well have set i to n and then you could dispense with the for loop.
Why is the function returning round(rr,4) when rr is a logical?

> 
> Matlab code:
> 
> function F = cxncnr(r)
> n = 4;
> % terms
> t1 = (1+(n-1)*r)*log((1+(n-1)*r));
> t2 = (n-1)*(1-r)*log(1-r);
> 
> %f = term - cxn
> f = (t1+t2)/(n*log(n)) - 0.05011007
> 
> F = [f];
> % r0 = [0.5] ; r = fsolve(@cxncnr,r0)

From this code I gather that you are trying to solve an equation with one variable.
Some code:

cxncnr <- function(r) {
    n <- 4
    t1 <- (1+(n-1)*r)*log((1+(n-1)*r))
    t2 <- (n-1)*(1-r)*log(1-r)
    X <- (t1+t2)/(n*log(n)) - 0.05011007
    X
}

# a plot to determine endpoints
curve(cxncnr,from=0.0,to=.5)

sol <- uniroot(cxncnr,c(.01,.50))
sol
cxncnr(sol$root)


Berend




More information about the R-help mailing list