help-octave
[Top][All Lists]

Re: Toy NDArray example

 From: David Bateman Subject: Re: Toy NDArray example Date: Thu, 19 Jan 2006 10:52:25 +0100 User-agent: Mozilla Thunderbird 1.0.2 (Windows/20050317)

```Keith Goodman a écrit :

```
```On 1/18/06, David Bateman <address@hidden> wrote:
> I'd think the following example is something like what you want

Nice example. Thank you. Pairing a bunch of toy m-functions with the
corresponding oct-functions would make a nice document.

```
```
```
You should look at the oct-file programming documents of Christophe Spiel (http://octave.sourceforge.net/coda/coda.pdf) and Paul Thomas (http://perso.wanadoo.fr/prthomas/intro.html). Essentially, I believe what you discuss is already pretty well discussed there, so I don't see the need for further effort to write something new.
```
```
```Since I can only index a NDArray with a single index, how do I pull
out an entire 2D slice of a 3D array?

n = [3 2 4];
x = rand(n);

```
I want y = x(:,:,j), so in an oct function would I have to do the equivalent of
```
ind = (j - 1)*n(1)*n(2) + (1:(n(1)*n(2)));
y = x(ind);
y = reshape(x,n(1),n(2));

or if reshape is not available loop over the rows and columns of y?

```
With idx_vector's in an oct-file you can do this. But not very efficiently. The thread
```
http://www.octave.org/octave-lists/archive/help-octave.2005/msg00328.html

```
is probably of interest in this case. However, for the case you have here, due the fortran style indexing of octave matrices, what you want to do can be easily implemented as in the attached file
```
D.

```
```#include <oct.h>

DEFUN_DLD(ndarraytoy, args, nargout, "y = ndarraytoy(x, j).")
{
int nargin = args.length ();
octave_value retval;

// Important to check the number of arguments as if incorrect will seg-fault
if (nargin != 2)
{
print_usage ("ndarraytoy");
return retval;
}

// input matrix x is 3D. Define const so we don't make a copy later
const NDArray x = args(0).array_value();
octave_idx_type j = args(1).int_value() - 1;

if (!error_state)
{
// Ok it was an NDArray

//Note if  2.1.x need  int instead of octave_idx_type
dim_vector dv = x.dims();

if (dv.length() < 3 || j < 0 || j >= dv(2))
error ("ndarrytoy: index out of range");
else
{
// Define output NDArray
NDArray y(dim_vector(dv(0),dv(1)));
octave_idx_type len = y.length();
octave_idx_type offset = len * j;
std::cerr << "len,offset: " << len << " " << offset << "\n";

// Can only loop over one index value for NDArray.
for (octave_idx_type i = 0; i < len; i++)
y(i) = x(i+offset);

retval = y;
}
}
return retval;
}

```