help-octave
[Top][All Lists]
Advanced

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

Passing integers: use arg(x).int_value() ?


From: John W. Eaton
Subject: Passing integers: use arg(x).int_value() ?
Date: Mon, 21 Feb 2005 14:56:10 -0500

On 21-Feb-2005, Steve C. Thompson <address@hidden> wrote:

| I'm trying to pass integers into a custom .oct program.  For example
| (granted, a useless program), say I want to generate a matrix of
| random numbers then return the matrix, the number or rows and the number of
| columns both of which are passed to the function. I've found that these
| parameters must be of type ``int'' or the ``octave_rand'' gets mad.
| With some trial and error, I've found that ``args(x).int_value() works.
| Is this the best/simplest way to do this?

Yes.

| Below is a sample program.
| 
| #include <octave/oct.h>
| #include <octave/oct-rand.h>
| DEFUN_DLD (sct_rand, args, ,
|   "Returns a matrix of random numbers")
| { 
| octave_value_list retval;
| 
|   int r = args(0).int_value();
|   int c = args(1).int_value();
| 
|   octave_rand::distribution ("normal");
| 
|   Matrix tmp = octave_rand::matrix (r, c);
| 
|   retval(0) = r;
|   retval(1) = c;
|   retval(2) = tmp;
| 
|   return retval;
| }

I would write this as:

#include <octave/oct.h>
#include <octave/oct-rand.h>

DEFUN_DLD (sct_rand, args, ,
  "Returns a matrix of random numbers")
{ 
  octave_value_list retval;

  if (args.length () == 2)
    {
      int r = args(0).int_value();
      int c = args(1).int_value();

      if (! error_state)
        {
          // XXX FIXME XXX -- check that r and c are both non-negative?

          octave_rand::distribution ("normal");

          retval(2) = octave_rand::matrix (r, c);
          retval(1) = c;
          retval(0) = r;
        }
      else
        error ("sct_rand: expecting integer arguments");
    }
  else
    print_usage ("sct_rand");

  return retval;
}

This way, it won't crash if you supply an incorrect number or type of
arguments.

Filling in retval in reverse is better because then it only has to
resize once.  Currently, octave_value_list implemented as a vector of
values.  If that ever changes and it becomes a real list of values, we
will try to ensure that filling the list in either order is fast.

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



reply via email to

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