help-octave
[Top][All Lists]

## Re: loops vs vectorization

 From: Ozzy Lash Subject: Re: loops vs vectorization Date: Wed, 5 Jul 2006 23:43:15 -0500

```On 7/5/06, Robert A.Macy <address@hidden> wrote:
```
```On Wed, 5 Jul 2006 18:20:40 -0500
> On 7/5/06, Robert A.Macy <address@hidden> wrote:
> > Would somebody be kind enough to refresh my memory how
> to
> > avoid a "for" loop when there are a lot of conditional
> >
> > for example, the simple act of replacing every item
> that is
> > less than negative with the value zero.
> >
> > Can't remember all the nuances on writing 'vectorized'
> > versions of those types of conversions.
> >
> >              - Robert -
> >
> One way to do what you ask is:
>
> octave:6> A=rand(5)-0.5
> A =
>
>    0.172279   0.035958   0.236123   0.472645   0.278473
>   -0.143212  -0.459838   0.450752   0.460015  -0.332292
>    0.126755  -0.047737   0.044301   0.338564  -0.118386
>   -0.245099  -0.466291  -0.498579   0.164236  -0.155360
>   -0.252265   0.239568  -0.298967   0.435878  -0.153951
>
> octave:7> A(A<0)=0
> A =
>
>   0.17228  0.03596  0.23612  0.47265  0.27847
>   0.00000  0.00000  0.45075  0.46002  0.00000
>   0.12675  0.00000  0.04430  0.33856  0.00000
>   0.00000  0.00000  0.00000  0.16424  0.00000
>   0.00000  0.23957  0.00000  0.43588  0.00000
>
> octave:8>

Thanks, that's it?  All these years...doing for loops

you say 'one way' are there others?
```
```
Well, a different way would be:

A=A.*(A>=0)

I think Rafael's solution (A>=0) will have all of the negative values
replaced by 0, but will also have all of the positive values replaced
by 1.  This can also be handy, but I don' t think that was what you

There is probably a way to use find() to do the same thing.

```
```
so how to do 'if, else' without doing two statements in a
row?
```
```
I think it really depends what the if clause would be doing and what
the else clause would be doing. Let's say you wanted to multiply all
of the positive values by 2 and all of the negative values by 3, you
could do the following:

B=2*A(A>=0) + 3*A(A<0)

or if you wanted to know the number of negative and positive values:

numnegs=sum(sum(A<0))
numpos=sum(sum(A>=0))

Octave (and matlab) are good at doing matrix math, so it seems to me
that usually, the best way to do vectorization is to try to change the
problem into one that uses matrix math. Sometimes you really have to
look for a way to do that, and even change the way your data are
represented.

Bill

```