Vectorization and Vector Indexing

I currently need to speed up my code a bit and therefore want to use a vector instead of loops. The following code is a (very) simplified version of the code that gets a lot of names during my calculation:

    T=10; n=5; w0 = 25000; w1 = 23000; b0 = 15000; 
    vec = zeros(1,T+2*n+1); vec(1:n+1) = w0; vec(n+2:n+T+1) = b0; vec(n+T+2:T+2*n+2) = w1;
    ref0=zeros(1,n);
    for i = 1:n
        ref0(i) = sum(vec(T+i+2:n+T+i+2));
    end

I tried to use the vector, but, unfortunately, it does not work, since only the first record of my vector is used as an input signal in the process of vector indexing:

i = 1:n;
ref1 = sum(vec(T+i+2:n+T+i+2));

The conclusion is as follows:

ref0 =

  106000      114000      122000      130000      138000

ref1 =

  106000

Is there a way to achieve this ref1 gives the same result as ref0 using a vector? It may be super obvious, but I don't seem to get any further. I am grateful for any help! Thank you very much in advance.

+4
source share
3

movsum :

ref1 = movsum(vec(T+3:T+2*n+2),n+1,'Endpoints','discard');
+5

, n T , vec - :

ref1 = cumsum(vec);
ref1 = ref1(T+n+3:end) - ref1(T+2:end-n-1);
+4

Convolution also works:

c = conv(ones(1,n+1), vec(T+3:2*n+T+2), 'same' );
ref2 = c(1:end-1);
+2
source

Source: https://habr.com/ru/post/1668539/


All Articles