MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

# codes instead of 'for' loops to speed up

Asked by Coo Boo on 18 Aug 2012

Hi to all,

I have 3 'for' loop which make the excutation to be time-consuming. Is there any way to speed up? The code is:

``` ...
for i= 0:P
for j=0:P
ss=0;
for k=P:N-1
ss=ss+x(k-j+1,1)*x(k-i+1,1);
end
R(i+1,j+1)=ss;
end
end
...```

Thanks,

Matt Fig on 18 Aug 2012

What are P, N and X? Specifically what is the size of X?

Jan Simon on 18 Aug 2012

Hi Matt! I'm happy to see you back again.

Matt Fig on 18 Aug 2012

Hello Jan!

## Products

Answer by Jan Simon on 18 Aug 2012

as Matt has mentioned already, the question does not contain enough information to be answered exhaustively. The simple approach to vectorize the innermost loop is most likely not efficient:

```for i = 0:P
for j = 0:P
R(i+1, j+1) = sum(x(P-j+1:N-j, 1) .* x(P-i+1:N-i, 1));
end
end
```

Now the creation of the intermediate vectors x(P-j+1:N-j, 1) takes too much time - but this is a guess only, which I cannot prove due to the missing details in the question.

But you could try to store one of the vectors in a temporary variable:

```for i = 0:P
t1 = x(P-i+1:N-i, 1);
for j = 0:P
R(i+1, j+1) = sum(x(P-j+1:N-j, 1) .* t1);
end
end
```

Then you should exploit the symmetric structure of the result:

```for i = 0:P
t1 = x(P-i+1:N-i, 1);
R(i+1, i+1) = sum(t1 .* t1);  % Diagonal element
```
```   for j = i+1:P
t2          = sum(x(P-j+1:N-j, 1) .* t1);
R(i+1, j+1) = t2;
R(j+1, i+1) = t2;
end
end```

Again: I cannot test this code. Please post requests for optimizing code always with a set of usual test data. Most likely the SUM(vector1 .* vector2) approach is slower than a lean and clean loop. Therefore I assume that exploiting the symmetry is a more useful strategy.

Omitting the 2nd index in "x(k, 1)" saves time, if x is a vector. But perhaps x is a function and the 2nd input is important.

## 1 Comment

Coo Boo on 19 Aug 2012