help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: vectorial IF


From: John W. Eaton
Subject: Re: vectorial IF
Date: Mon, 15 May 2000 22:39:03 -0500 (CDT)

On 15-May-2000, John Smith <address@hidden> wrote:

| I offer a bit of code that does the sort of thing you are 
| describing:
| 
|   Given a matrix of integers, double the even ones and
|   multiply the odd ones by -1. 
| 
| -----------------------------------------------------------
| 
| ## create a matrix with some integers
| 
| a = floor(100*rand(3,5)) ;
| 
| ## first, it is easier to work if everything is a vector
| ## -- so reshape it to a vector
| a_vec = vec(a) ;
| 
| ## make a boolean array marking the even values
| evens = ( rem(a_vec,2) == 0 ) ;
| 
| ## and the odd values
| odds  = 1-evens ;
| 
| ## make an array to put the answers into (speeds things up slightly)
| b_vec =  zeros(size(a_vec)) ;
| 
| ##
| ## do the evens
| ##
| if ( any(evens) )
|   idx = find(evens) ;
|   b_vec(idx) = a_vec(idx) * 2 ;
| endif
|   
| ##
| ## do the odds
| ##
| if ( any(odds) )
|   idx = find(odds) ;
|   b_vec(idx) = -a_vec(idx) ;
| endif
| 
| ##
| ## recast b_vec back to the shape of a
| ##
| b = reshape( b_vec, rows(a), columns(a)) ;
| 
| ##
| ## print out the matrices
| a
| b
| -----------------------------------------------------------------
| Its all magic, and has no FOR loops.

With the current development sources, you can shorten this to

  a = floor (100 * rand (3, 5));

  evens = rem (a, 2) == 0;

  odds  = ! evens;

  b = zeros (size (a));

  b(evens) = 2 * a(evens);
  b(odds) = -a(odds);

There is no need for the if blocks, find, or reshaping because Octave
2.1.x will always allow a single boolean matrix to be used as an index
for any shape matrix.

This still works even if there are no odd values or no even values in
the matrix.

Note also that `odds' is generated using a boolean operation so that
it is a boolean object -- subtracting `evens' from 1 results in a
numeric object, which doesn't have the same special indexing
properties.

jwe



-----------------------------------------------------------------------
Octave is freely available under the terms of the GNU GPL.

Octave's home on the web:  http://www.che.wisc.edu/octave/octave.html
How to fund new projects:  http://www.che.wisc.edu/octave/funding.html
Subscription information:  http://www.che.wisc.edu/octave/archive.html
-----------------------------------------------------------------------



reply via email to

[Prev in Thread] Current Thread [Next in Thread]