help-octave
[Top][All Lists]

## newbie, problem using ranges with function...

 From: John W. Eaton Subject: newbie, problem using ranges with function... Date: Fri, 3 May 2002 16:31:15 -0500

```On  3-May-2002, address@hidden <address@hidden> wrote:

| Hi,
|
| I wrote this script:
| #-------start-------
| function M=f(x)
| M=0;
| if (x<6)
| M=250*x;
| else
| M=250*x-2.5*250*(x-6);
| endif
| endfunction
|
| x=(0:.1:10)'
| data=[x, f(x)]
| gplot data
| #-------finish------
|
| When I test the function f(x) manually (ie. f(0)=f(10)=0, f(6)=1500)
| all is OK.  When I do f(x) as above I get an output that is 3750
| decreases monotonically by 37.5 for each value of x which is obviously
| wrong.
|
| Interestingly if I do sin(-pi:.1:pi) I get what would be expected.
|
| There is obviously something that I am not getting...

The IF statement doesn't work as you expect.

For example, given x = 1:10, x < 6 produces

ans =

1  1  1  1  1  0  0  0  0  0

and since this contains some false elements, the if condition is never
true (for IF (VECTOR), all the elements of VECTOR must be nonzero for
the test to be considered true).

Here's one way to vectorize your function:

function M = f (x)
cutoff = 6;
M = zeros (size (x));
idx = x < cutoff;
M(idx) = 250*x(idx);
idx = ! idx;
M(idx) = 250*x(idx)-2.5*250*(x(idx)-cutoff);
endfunction

or, for this particular function, maybe

function M = f (x)
cutoff = 6;
M = 250*x;
idx = x >= cutoff;
M(idx) = M(idx) -2.5*250*(x(idx)-cutoff);
endfunction

is better.  With Octave 2.1.x, you could also write the last line as

M(idx) -= 2.5*250*(x(idx)-cutoff);

jwe

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

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

```