[Rcpp-devel] Variable for loop

Avraham Adler avraham.adler at gmail.com
Tue Sep 27 03:51:03 CEST 2016


Hello.

Once again, it is very unclear what you want to do. Can you please
explain, in English not code what your procedure intends to do, the
input you expect, and the output you expect?

What it LOOKS like you want to do is to create an N x M x N cube where
the first slice is your matrix and the remaining slices are all 0. If
that is the case, There are much, much simpler ways to do it than to
traverse all N²M cells. The following should work.

#include <RcppArmadillo.h>
using namespace Rcpp;
using namespace RcppArmadillo;
//[[Rcpp::depends(RcppArmadillo)]]

//[[Rcpp::export]]
arma::cube fillup(arma::mat a){
  int m = a.n_cols;
  int n = a.n_rows;
  arma::cube C = arma::cube(n, m, n, arma::fill::zeros);

  C.slice(0) = a;

  return(C);
}

Avi

On Mon, Sep 26, 2016 at 5:59 PM, Amina Shahzadi <aminashahzadi at gmail.com> wrote:
> Hi Dear
>
> I have a problem in using a variable for loop in using RcppArmadillo
> library.
> I have pasting here my code. It is executing but not giving the same results
> as its R code version gives. The results produced by it are really weird. I
> have checked it step by step. It is because of the for (int q=0; q<i; q++).
> I request tp please help how to handle it in cpp.
>
> The another question is I want to multiply the cube b(i, ,) by a scalar. How
> can we consider the entire columns and slices of a cube for each of the
> rows.  "b(span(i), span(), span())"  is not working for me.
>
> Thank you
>
> #include <RcppArmadillo.h>
> using namespace Rcpp;
> using namespace RcppArmadillo;
> //[[Rcpp::depends(RcppArmadillo)]]
> //[[Rcpp::export]]
> arma::cube up(arma::mat a){
>   int m = a.n_cols;
>   int n = a.n_rows;
>   int p = a.n_rows;
>   arma::cube b(n, m, p);
>   for(int i=0; i<n; i++){
>       for(int j=0; j<m; j++){
>         for(int q=0; q<i; q++){
>          if(q==0){
>            b(i, j, q) = a(i, j);
>          }
>          else{
>            b(i, j, q) = 0.0;
>          }
>       }
>     }
>   }
>   return b;
> }
>
> --
> Amina Shahzadi


More information about the Rcpp-devel mailing list