Skip to content

[Rcpp-devel] For a Matrix A, is A(i, j) or A[i, j] preferred as an accessor for an element

5 messages · Romain Francois, Douglas Bates, Dirk Eddelbuettel

#
Le 10/12/12 17:29, Douglas Bates a ?crit :
A[i,j] is wrong, not valid C or C++ code. so there is only one choice.

Romain
#
On Mon, Dec 10, 2012 at 10:38 AM, Romain Francois
<romain at r-enthusiasts.com>wrote:

            
Indeed.  Thanks.  Somehow I managed to convince myself that I had used
A[i,j] at some point and the compiler accepted it.  Apparently my memory
isn't what it used to be.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20121210/c65901d7/attachment.html>
#
Le 10/12/12 17:45, Douglas Bates a ?crit :
That is even worse than that. At least here, the compiler accepts it, 
and does something wrong with it:

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
double fun(NumericMatrix m){
   return m[5,0] ;
}

/*** R
   fun( diag(4) )
***/


doug.cpp: In function ?double fun(Rcpp::NumericMatrix)?:
doug.cpp:7: warning: left-hand operand of comma has no effect
 > fun(diag(4))
[1] 1

So m[5,0] gets me m[0] ...
#
On 10 December 2012 at 10:45, Douglas Bates wrote:
| On Mon, Dec 10, 2012 at 10:38 AM, Romain Francois <romain at r-enthusiasts.com>
| wrote:
| 
|     Le 10/12/12 17:29, Douglas Bates a ?crit :
| 
|         or does it matter?
| 
| 
|     A[i,j] is wrong, not valid C or C++ code. so there is only one choice.

No, it's worse, It is valid:

   R> cppFunction("double val(Rcpp::NumericMatrix X) { return X[1,2]; }")
   R> val(matrix(1:9,3,3))
  [1] 3
   R>

| Indeed. ?Thanks. ?Somehow I managed to convince myself that I had used A[i,j]
| at some point and the compiler accepted it. ?Apparently my memory isn't what
| it used to be.

.. but it is possibly the worst gotcha we can have in C++ and matrices as the
comma _is_ in fact a valid operator coming from C --- here though A[i,j] simply
collapses to A[j] with i being ignored as comma sequences the statements
around it.

Dirk