help-octave
[Top][All Lists]
Advanced

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

Re: Apply function to vector


From: HomeRun4711
Subject: Re: Apply function to vector
Date: Wed, 22 Jun 2011 18:54:50 +0200
User-agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.17) Gecko/20110424 Lightning/1.0b2 Thunderbird/3.1.10

Thanks for your replies. I will rewrite my
function to support vectors and scalars.

Kind regards,
Walter


Am 21.06.2011 09:15, schrieb Mike Miller:
On Mon, 20 Jun 2011, Jordi GutiƩrrez Hermoso wrote:

On 20 June 2011 04:59, Fritz Fischer <address@hidden> wrote:
For convenient reasons to plot functions I would like to apply a
function to
a vector:

e.g.

x = 0:1:2*pi
y = sin(x)
plot(x,y)

So far, everything works fine.
But if I want to apply one of my functions the same way,
e.g.

x = 0:1:40
y = rayleigh_optical_density(x) %contains just some simple calculations

I get the following message:

error: for A^b, A must be square

I read about element-wise operations, but I guess this is of no use
here,
isn't it?

It depends how you wrote rayleigh_optical_density. Did you vectorise
it? What functions does it call? You need to either rewrite it to use
elementwise calculations or to call arrayfun on it:

arrayfun(@rayleigh_optical_density, x)


For example, if you have scalars w, x, y and z, You could do this:

(w*x/y)^z

And if all four variables became vectors of, say, length four, you might
want to do something like this:

output=zeros(4,1); # initialize output vector
for i=1:4, output(i) = (w(i)*x(i)/y(i))^z(i) ; end

But that is slow and awkward and unnecessary. This does the same thing
(assuming these are column vectors):

output = (w.*x./y).^z ;

If they were column vectors, the output would be a column vector. The
"for" loop above will produce a column vector as output no matter which
kinds of vectors were used as input.

Another plus: When all four vectors are scalars, (w*x/y)^z and
(w.*x./y).^z provide the same output. Therefore, when writing code,
consider the possibility that you might use vectors or matrices instead
of scalars and write the code accordingly.

Mike

--
Michael B. Miller, Ph.D.
Minnesota Center for Twin and Family Research
Department of Psychology
University of Minnesota


reply via email to

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