help-octave
[Top][All Lists]
Advanced

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

Re: vectorial IF


From: John Smith
Subject: Re: vectorial IF
Date: Mon, 15 May 2000 23:32:12 +0100 (BST)

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.

John


On Sat, 13 May 2000, Cezar Diaconu wrote:

> Hi,
> 
> I have a question here.
> 
> I'm interested about a vectorial IF.
> something like:
> 
> IF expr                   % here 'expr' is a matrix of 0 and 1
>     statements1        % for any 1 do statements1
> ELSE
>     statements2        % for any 0 do statements2
> END
> 
> In fact I want to transfer implicit the pozition of 'expr' elements to the
> statements (using (:,:) in place of (i,j) in FOR loops)
> 
> Suppossing there is a command which can do this faster then using normal IF
> and FOR loops
> please tell me.   Also I am interested about similar commands in Matlab and
> Scilab.
> 
> I should say I'm quite new with Octave (normally I'm using Matlab).
> 
> Thank you,
> Best regards
> 
> Cezar



-----------------------------------------------------------------------
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]