简体   繁体   中英

Converting R code to MATLAB code: Stuck at sapply()

I have the following R code, which I am trying to convert to MATLAB. (No, I do not want to run the R code in MATLAB like shown here ).

The R code is here:

# model parameters
dt <- 0.001
t <- seq(dt,0.3,dt)
n=700*1000
D = 1
d = 0.5

# model
ft <- n*d/sqrt(2*D*t^3)*dnorm(d/sqrt(2*D*t),0,1)
fmids <- n*d/sqrt(2*D*(t+dt/2)^3)*dnorm(d/sqrt(2*D*(t+dt/2)),0,1)
plot(t,ft*dt,type="l",lwd=1.5,lty=2)

# simulation
#    
# simulation by drawing from uniform distribution
# and converting to time by using quantile function of normal distribution
ps <- runif(n,0,1)                
ts <- 2*pnorm(-d/sqrt(2*D*t))     
sumn <- sapply(ts, FUN = function(tb) sum(ps < tb))
lines(t[-length(sumn)],sumn[-1]-sumn[-length(sumn)],col=4)

And the MATLAB code I have done so far is

% # model
ft = (n*d)./sqrt(2*D.*t.^3).*normpdf(d./sqrt(2*D.*t),0,1);
fmids = (n*d)./sqrt(2*D*((t+dt)./2).^3).*normpdf(d./sqrt(2*D.*((t+dt)./2)),0,1);
figure;plot(t,ft.*dt);

% # simulation
% #    
% # simulation by drawing from uniform distribution
% # and converting to time by using quantile function of normal distribution
ps = rand(1,n);                
ts = 2*normcdf(-d./sqrt(2*D*t)); 

So, here is where I am stuck. I don't understand what function sumn = sapply(ts, FUN = function(tb) sum(ps < tb)) does and where the parameter ' tb ' came from. It is not defined in the given R code as well.

Could anyone tell me what the equivalent of that function R code is in MATLAB?

[EDIT 1: UPDATE]

So, based on the comments from @Croote, I came up with the following code for the function defined in sapply()

sumidx  = bsxfun(@lt,ps,ts');
summat  = sumidx.*repmat(ps,300,1);
sumn    = sum(summat,2);
sumnfin = sumn(2:end)-sumn(1:end-1);
plot(t(1:length(sumn)-1),sumnfin)

However, I am not getting the desired results. The curves should overlap with each other: the blue curve is correct, so the orange need to overlap with the blue curve .

在此处输入图片说明

What am I missing here? Is R's pnorm() equivalent to MATLAB's normcdf() as I have done here?

[EDIT 2: FOUND THE BUG!]

So, after fiddling around, I discovered that I all I had to do was obtain the number of occurrences of tb < pb . The line summat = sumidx.*repmat(ps,300,1) is not supposed to be there. After removing that line and keeping sumn = sum(sumidx,2); , I get the desired result.

在此处输入图片说明

So, based on the comments from @Croote and after fiddling around, I came up with the following code for the function defined in sapply()

sumidx  = bsxfun(@lt,ps,ts');
sumn    = sum(sumidx,2);

And for the plot, I coded it as

sumnfin = sumn(2:end)-sumn(1:end-1);
plot(t(1:length(sumn)-1),sumnfin)

Finally, I get the desired result

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM