help-octave
[Top][All Lists]
Advanced

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

Re: Trying to avoid loops when adjusting two variables.


From: Geordie McBain
Subject: Re: Trying to avoid loops when adjusting two variables.
Date: Wed, 18 Apr 2007 10:25:01 +1000

On Tue, 2007-04-17 at 14:30 +0200, Harbinson, Jeremy wrote:
> Hi, 
> This is one of those how-do-I-avoid loops questions.
> 
> Simple case of one variable in a function: 
> 
> if I have a vector (A) and a function (eg y=2*x^2) I can easily apply
> the function to the vector without looping as follows 
> 
> 2.*A.^2 
> and I get an output in which the function has been applied
> sequentially to every element of the input vector.
> 
> More complicated case (the one for which I would like to avoid a for
> loop):
> 
> I now have 2 vectors A and B and a function with two variables (eg
> y=z*x^2). I want to apply the function to both A and B, using B for
> variable z and A for variable x, and get an output which is a grid
> within which each element is the result of applying the function to a
> particular pair of elements from A and B. At the moment the only way I
> can think of doing this is to use a loop in which I first calculate
> B(1).*A.^2, then calculate B(2).*A.^2 etc until I have cycled through
> every element in B. Can this procedure be vectorised or is looping
> over one of the variables the only solution?

Carlo's, Kim's, & Jordi's three different answers are all correct and
all generalize to more complicated functions of two vector arguments.
In this particular example though you could also do

        B * (A .^2).' 

assuming B and A are columns of equal lengths; for rows, use 

       B.' * (A .^2) .

I think vectorization is often about tricks, like this one.

A fourth general solution is the function outer written by Muthiah
Annamalai last April; see
http://www.cae.wisc.edu/pipermail/octave-sources/2006-April/000000.html .




reply via email to

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