我有一个 for 循环的以下代码,其中包含一个条件 if 语句,其中包括最后 10 个循环周期,以搜索逻辑模式的变化,并在 true 时增加一个计数器:
for(ii in 100:sp)
{
if(start(ii) == 1 && mean(start(ii-11:ii-1)) == 0)
{
count = count + 1
}
}
sp 的值为3,560,400;意味着循环超过 300 万次。加载时间很长,执行循环大约需要 40 分钟。
如何使用矢量化优化此代码?
谢谢您的帮助。
编辑
我在这里包含了我的所有代码,所以每个人都可以看到发生了什么:
# store the current directory
initial.dir<-getwd()
# change to the new directory
setwd("H:/R/range")
# load the necessary libraries - sound
library(sound)
library(TTR)
#####################################################
# LOAD .WAV FILE / SET OUTPUT FILE
#####################################################
# set the output file
sink("rangetmp3.out")
# load the dataset
sndSample <- loadSample('range.wav')
FS <- rate(sndSample)
nBits <- bits(sndSample)
# assign sound wave
Y <- sound(sndSample)
#####################################################
# CONSTANTS
#####################################################
#(m/s) speed of light
c <- 3E8
############################
# |- Radar parameters
############################
#(s) pulse time
Tp <- 20E-3
# number of samples per pulse
N <- Tp*FS
#(Hz) LFM start frequency for example
fstart <- 2260E6
#(Hz) LFM stop frequency for example
fstop <- 2590E6
#(Hz) LFM start frequency for ISM band
fstart <- 2402E6
#(Hz) LFM stop frequency for ISM band
fstop <- 2495E6
#(Hz) transmti bandwidth
BW <- fstop-fstart
#instantaneous transmit frequency
f <- seq(fstart, fstop, length=N/2)
#range resolution
rr <- c/(2*BW)
max_range <- rr*N/2
#####################################################
# RANGE
#####################################################
############################
# |- The input appears to be inverted
############################
trig <- -1*Y[1,]
s <- -1*Y[2,]
#reset Y
#Y = 0
############################
# |- Parse the data here by triggering off rising edge of sync pulse
############################
# reset counter / threshold
count <- 0
thresh <- 0
# assign logical vector that meets thresh
start <- (trig > thresh)
sp <- NROW(start)-N
for(ii in 100:sp)
{
if(start(ii) == 1 && mean(start(ii-11:ii-1)) == 0)
{
count = count + 1
}
}
编辑#2:Matlab 循环
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