Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectorization and vector indexing

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

    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 vectorization, but unfortunately it does not seem to work as only the first entry of my vector i is used as an input in the vector indexing process:

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

The output is the following:

ref0 =

  106000      114000      122000      130000      138000

ref1 =

  106000

Is there any way to achieve that ref1 gives the same output as ref0 using the vectorization? It might be super obvious, but I do not seem to get further here. I am grateful for any help! Thanks a lot in advance.

like image 899
banan Avatar asked Dec 18 '22 10:12

banan


1 Answers

You can use movsum instead of your loop:

ref1 = movsum(vec(T+3:T+2*n+2),n+1,'Endpoints','discard');
like image 110
EBH Avatar answered Dec 31 '22 03:12

EBH