R - Convert this nested for loop (MATLAB) to R -
this question has answer here:
i need convert loop r
for ii = 100:(size(start,1)-n) if start(ii) == 1 && mean(start(ii-11:ii-1)) == 0 count = count + 1; sif(count,:) = s(ii:ii+n-1); time(count) = ii*1/fs; end end
the start vetor single dimension vector of true , false values 3 million elements in total.
as loops in r take long time, take 3 hours execute code, needs vectorized.
if really appreciate it.
edit
here r code simple count (which takes hours execute)
for(ii in 100:sp) { if(start(ii) == 1 && mean(start(ii-11:ii-1)) == 0) { count = count + 1 } }
edit-2
here dummy values:
start
:
[1] true true true true true true true true true true true true [13] true true true false false false false false false false false false
n
:
[1] 882
fs
:
[1] 44100
s
:
[1] 1.762390e-01 1.797791e-01 1.826172e-01 1.795044e-01 1.724243e-01 [6] 1.665039e-01 1.640625e-01 1.634827e-01 1.628723e-01 1.606750e-01
i created dummy data:
set.seed(1234) start = sample(c(true,false), 300000, replace=true) n = 882 count = 0
your r
code takes:
system.time( for(ii in 100:(length(start)-n)) { if(start(ii) == 1 && mean(start((ii-11):(ii-1))) == 0) { count = count + 1 } }) ## user system elapsed ## 15.42 0.00 15.43
there function in r
called start
, getting called instead of indexing vector start
. correct , faster way is:
system.time( for(ii in 100:(length(start)-n)) { if(start[ii] == 1 && mean(start[(ii-11):(ii-1)]) == 0) { count = count + 1 } }) ## user system elapsed ## 2.04 0.00 2.04
Comments
Post a Comment