1

I have an example R script for spectrum calculation. I divide the signal into several blocks and do the calculation for each block.

spect=function(x,samplingfrequency=1,blocksize=2^12)
{
    T=length(x)
    blocks=trunc(T/blocksize)

    localfreq=c() ; localspec=c() 
    for(i in 1:blocks){localfreq[[i]]=c() ; localspec[[i]]=c() }

    for(i in 1:blocks)
    {
        time=c( (1+(i-1)*blocksize) : (i*blocksize) )
        localspectrum=spectrum(x[time],plot=FALSE)
        localfreq[[i]]=localspectrum$freq
        localspec[[i]]=localspectrum$spec
    }

    averagespec=rep(0,(blocksize/2))

    for(freq in 1:(blocksize/2))
    {
        for(block in 1:blocks)
        {
            averagespec[freq]=(averagespec[freq]+localspec[[block]][freq])
        }
        averagespec[freq]=averagespec[freq]/blocks

    }


    par(mar=c(5.1,5.1,2.5,1.5))
    plot(c(1:(blocksize/2))/(blocksize/2)*samplingfrequency/2,averagespec,log="xy",t="l",xlab="frequency [Hz]",ylab="average spectrum [a.u.]",cex.lab=1.8,cex.axis=1.8)

    abline(v=(samplingfrequency/2),col=2)
    abline(v=(1/blocksize*samplingfrequency),col=4)

}

here x is your time series input. I don't use the spectrum function from R directly since the result is too noisy. I was wonder if I could somehow avoid those forloops in my script?

Haribo
  • 2,071
  • 17
  • 37
  • @Konrad. Alright. – Axeman Aug 09 '18 at 14:17
  • If anything, this question should be moved to [Code Review](https://codereview.stackexchange.com). It's not asking for debugging and isn't overly broad. It could do with some example data, but that's cause for a comment to the author, not anonymous downvoting and close-voting. – AkselA Aug 09 '18 at 14:33
  • @AkselA You missed the (now deleted) comments discussing this: *No*, the question is completely fine here: it asks a specific, technical question. Codereview.SE is for general code style critique. – I agree about the rest, it‘s a totally valid question, it’s neither too broad nor vague, contrary to the claims of the close voters. – Konrad Rudolph Aug 09 '18 at 14:43
  • 1
    @KonradRudolph: Maybe an idea to let comments like those linger for a bit longer? – AkselA Aug 09 '18 at 14:49

0 Answers0