help-octave
[Top][All Lists]
Advanced

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

Re: if-tests being ignored?


From: Søren Hauberg
Subject: Re: if-tests being ignored?
Date: Sat, 05 Jan 2008 00:10:31 +0100

Hi,
  and welcome to Octave :-)  Replies are below...

fre, 04 01 2008 kl. 22:43 +0000, skrev Matthew Tylee Atkinson:
> There are two problems I'm having (quite possibly related).  I would be
> grateful for any advice you may have on how to fix them.  I have
> attached a .m file that demonstrates them.  I'm running version 2.9.19.
You should consider upgrading to 3.0.0, but as I remember the changes
between 2.9.19 and 3.0.0 are fairly small, so I guess it's okay.

> 1. When I run ``octave confused.m'' on the command-line, the plot
> instruction seems to be ignored (fair enough, it could require to be run
> in interactive mode, but when I use -i, it still is ignored).
A plot is drawn when the 'drawnow' function is called. Either 'drawnow'
can be called by the user (i.e. you) or by Octave. Octave calls
'drawnow' when it is waiting for user input. When you call Octave from
the command line it will never wait for user input. What you want is
something:
  octave --persist confused.m
If you run
  octave --help
you'll get a bunch of possible options.

> 2. When I source the file from within Octave, it loads and plots the
> graph but the graph drawn is not as expected -- given the code, the
> gradient of the graph should change twice at certain points along the x
> axis.  It seems the if tests always evaluate to false.  When I run
> ``test(n)'' at the prompt, however, the correct values are returned from
> the function.
I think you have two problems with your code:

1) Your function is named 'test'. There is a built-in function called
'test' as well, so it's not a good idea to overwrite that function.

2) You code essentially looks like this:

x = 0 : 0.01 : 2*pi;
function retval = test (x)
        retval = 1/2 * x;
        if x < 3
                retval = 1/4 * x;
        elseif x > 6
                retval = 3/4 * x;
        endif
endfunction
test(x)

So, 'x' is a vector, right? Then you ask: 'if x < 3'. The answer will be
a binary vector where each element will indicate whether or not the
corresponding element of 'x' is less then 3. Just try typing 'x < 3' at
the Octave prompt, and you'll see what I mean. So, the question 'if x <
3' isn't well-defined. Octave will only consider the question to be true
if all elements of 'x' are larger than 3. What you want is something
like

function retval = test(x)
  retval = 0 * x;
  retval(x<6) = 3/4 * x(x<6);
  retval(x<3) = 1/4 * x(x<3);
endfunction

At first, this code might seem a bit odd, but you'll get used to the way
of thinking, and then you'll love it :-)


Søren
   




reply via email to

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