help-octave
[Top][All Lists]
Advanced

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

Re: Iterating over a ND-array


From: John W. Eaton
Subject: Re: Iterating over a ND-array
Date: Fri, 27 May 2005 09:37:40 -0400

On 27-May-2005, David Bateman wrote:

| This is why you often see 
| the fortran_vec function used in octave even when a fortran function 
| isn't called, as it allows this checking to be bypassed.

Or, more precisely, done only once, outside the loop.

| So in short
| 
| NDArray foo (const NDArry &m)
| {
|   NDArray ret (m.dims ());
|   double *bar = ret.fortran_vec ();
|   for (int i =0; i < m.nelem (); i++)
|      bar [i] = foobar (m(i));
|   return ret;
| }
| 
| is good practice...

Yes, that is reasonable.  Here, no copy is made in the fortran_vec
function becuase there is only one reference to the data in RET (new
storage was allocated in the preceding declaration statement).  But
if more than one referece to the data exists, fortran_vec will force a
copy to be made (i.e., copy on write semantics).  Another example:

  NDArray foo (const NDArry &m)
  {
    NDArray ret = m;                    // 2 refs to same data, no copy yet.
    double *bar = ret.fortran_vec ();   // copy made here.
    for (int i =0; i < m.nelem (); i++)
       bar [i] = foobar (m(i));
    return ret;
  }

Here, fortran_vec forces a copy so that RET will contain the modified
data and M will remain unchanged.

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]