help-octave
[Top][All Lists]

## Re: Apply function to vector

 From: Mike Miller Subject: Re: Apply function to vector Date: Tue, 21 Jun 2011 02:15:53 -0500 (CDT) User-agent: Alpine 2.00 (DEB 1167 2008-08-23)

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