help-octave
[Top][All Lists]

Re: Vectorizing for loops .. can't get the hang of it

 From: Juan Pablo Carbajal Subject: Re: Vectorizing for loops .. can't get the hang of it Date: Tue, 6 Nov 2012 17:57:25 +0100

```On Tue, Nov 6, 2012 at 5:31 PM, Joza <address@hidden> wrote:
> I understand I should REALLY try use vectors instead of for loops ... anyone
> care to explain how to do it? I come from a CS programming background so
> traditional for loops always seem the easiest to me.
>
> A piece of code I've used recently is below. I couldn't figure out how to
> vectorize it. Where do i start?
>
> for i=1:n
>                 sum = 0.0;
>
>                 if i==1
>                         for j=1:2
>                                 sum = sum + A(i,j)*x(j);
>                         end
>                 elseif i==n
>                         for j=n-1:n
>                                 sum = sum + A(i,j)*x(j);
>                         end
>                 else
>                         for j=i-1:i+1
>                                 sum = sum + A(i,j)*x(j);
>                         end
>                 end
>
>
>
> --
> View this message in context:
> http://octave.1599824.n4.nabble.com/Vectorizing-for-loops-can-t-get-the-hang-of-it-tp4646169.html
> Sent from the Octave - General mailing list archive at Nabble.com.
> _______________________________________________
> Help-octave mailing list
> https://mailman.cae.wisc.edu/listinfo/help-octave

The loops and the conditions could be written (assuming x is a column vector)

# do not use sum you are overwirting a function
ss = A(1,1:2)*x(1:2);

ss += A(n,n-1:n)*x(n-1:n);

ss += sum ( A(2:n-1,1:n)*x(1:n) );

Now you see a pattern. The first line of A, whatever is A is using
only the first two cols. Similarly, the last line of A uses only the
last two cols, so you could do it in one shot

A(1,3:end) = 0;
A(n,1:n-2) = 0;
ss = sum (A*x)

I did not check this gives the same result as your code, but it should
give you an idea... or not :D

```