当前位置: 首页>>代码示例>>C++>>正文


C++ NumericMatrix::ncol方法代码示例

本文整理汇总了C++中rcpp::NumericMatrix::ncol方法的典型用法代码示例。如果您正苦于以下问题:C++ NumericMatrix::ncol方法的具体用法?C++ NumericMatrix::ncol怎么用?C++ NumericMatrix::ncol使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rcpp::NumericMatrix的用法示例。


在下文中一共展示了NumericMatrix::ncol方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: FilterIndepOld

// [[Rcpp::export]]
SEXP FilterIndepOld  (Rcpp::NumericVector y_rcpp,
					Rcpp::NumericMatrix y_lagged_rcpp,
					Rcpp::NumericMatrix z_dependent_rcpp,
					Rcpp::NumericMatrix z_independent_rcpp,
					Rcpp::NumericVector beta_rcpp,
					Rcpp::NumericVector mu_rcpp,
					Rcpp::NumericVector sigma_rcpp,
					Rcpp::NumericMatrix gamma_dependent_rcpp,
					Rcpp::NumericVector gamma_independent_rcpp,
					Rcpp::NumericMatrix transition_probs_rcpp,
					Rcpp::NumericVector initial_dist_rcpp
					)
{
	int n = y_rcpp.size();
	int M = mu_rcpp.size();
	arma::mat xi_k_t(M, n); // make a transpose first for easier column operations.

	arma::colvec y(y_rcpp.begin(), y_rcpp.size(), false);
	arma::mat    y_lagged(y_lagged_rcpp.begin(),
								y_lagged_rcpp.nrow(), y_lagged_rcpp.ncol(), false);
	arma::mat    z_dependent(z_dependent_rcpp.begin(),
								z_dependent_rcpp.nrow(), z_dependent_rcpp.ncol(), false);
	arma::mat    z_independent(z_independent_rcpp.begin(),
								z_independent_rcpp.nrow(), z_independent_rcpp.ncol(), false);
	arma::colvec beta(beta_rcpp.begin(), beta_rcpp.size(), false);
	arma::colvec mu(mu_rcpp.begin(), mu_rcpp.size(), false);
	arma::colvec sigma(sigma_rcpp.begin(), sigma_rcpp.size(), false);
	arma::mat    gamma_dependent(gamma_dependent_rcpp.begin(),
								gamma_dependent_rcpp.nrow(), gamma_dependent_rcpp.ncol(), false);
	arma::colvec gamma_independent(gamma_independent_rcpp.begin(),
								gamma_independent_rcpp.size(), false);
	arma::mat    transition_probs(transition_probs_rcpp.begin(),
								transition_probs_rcpp.nrow(), transition_probs_rcpp.ncol(), false);
	arma::colvec initial_dist(initial_dist_rcpp.begin(), initial_dist_rcpp.size(), false);

	double likelihood = 0;

	SEXP eta_rcpp = EtaIndep(y_rcpp, y_lagged_rcpp,
						z_dependent_rcpp, z_independent_rcpp,
						beta_rcpp, mu_rcpp, sigma_rcpp,
						gamma_dependent_rcpp, gamma_independent_rcpp);
	arma::mat eta_t = (Rcpp::as<arma::mat>(eta_rcpp)).t();

	xi_k_t.col(0) = eta_t.col(0) % initial_dist;
	double total = sum(xi_k_t.col(0));
	xi_k_t.col(0) = xi_k_t.col(0) / total;
	likelihood += log(total);

	for (int k = 1; k < n; k++)
	{
	  	xi_k_t.col(k) = eta_t.col(k) % (transition_probs * xi_k_t.col(k-1));
	 	total = sum(xi_k_t.col(k));
		xi_k_t.col(k) = xi_k_t.col(k) / total;
		likelihood += log(total);
	}

	return Rcpp::List::create(Named("xi.k") = wrap(xi_k_t.t()),
														Named("likelihood") = wrap(likelihood));
}
开发者ID:chiyahn,项目名称:rMSWITCH,代码行数:60,代码来源:cppFilterIndepOld.cpp

示例2: rcpp_sweep_

// [[Rcpp::export]]
Rcpp::NumericMatrix rcpp_sweep_(Rcpp::NumericMatrix x, Rcpp::NumericVector vec)
{
  Rcpp::NumericMatrix ret(x.nrow(), x.ncol());
  
  #pragma omp parallel for default(shared)
  for (int j=0; j<x.ncol(); j++)
  {
    #pragma omp simd
    for (int i=0; i<x.nrow(); i++)
      ret(i, j) = x(i, j) - vec(i);
  }
  
  return ret;
}
开发者ID:wrathematics,项目名称:Romp,代码行数:15,代码来源:examples_rcpp.cpp

示例3: return

std::vector<std::vector<float> > matrix_to_array_v(Rcpp::NumericMatrix& mat)
{
  std::vector<std::vector<float> > v;
  if(!mat.ncol() || !mat.nrow())
    return(v);
  v.resize(mat.nrow());
  std::vector<float> v_row(mat.ncol()); // = new float[ mat.ncol() * mat.nrow() ];
  for(unsigned int i=0; i < (unsigned int)mat.nrow(); ++i){
    for(unsigned int j=0; j < (unsigned int)mat.ncol(); ++j){
      v_row[j] = (float)mat(i, j);
    }
    v[i] = v_row;
  }
  return(v);
}
开发者ID:lmjakt,项目名称:R-SOD,代码行数:15,代码来源:R_DimSqueezer.cpp

示例4: bic_linear

static double bic_linear(Rcpp::NumericMatrix X, 
			 Rcpp::NumericVector y, 
			 Rcpp::NumericMatrix beta_new, 
			 double eps, 
			 Rcpp::IntegerVector nk)
{
  int n_tot = X.nrow();
  int p = X.ncol();
  int K = nk.size();
 

  /*calculate SSe*/
  double SSe = 0.0;  
  int idx = 0;
  
  for (int k = 0; k < K; k++) {
    int n = nk[k];
    for (int i = 0; i < n; i++) {
      double Xrow_betacol = 0.0;
      for (int j = 0; j < p; j++) {
	Xrow_betacol += elem(X, idx+i, j) * elem(beta_new, j, k);
      }
      SSe += pow(y[idx+i] - Xrow_betacol, 2);
    }
    idx += n;
  }
  
  double ll = -n_tot / 2.0 * (log(SSe) - log(n_tot) + log(2.0 * M_PI) + 1);
  double bic = -2 * ll + df(beta_new, eps) * log(n_tot);

  return bic;
}
开发者ID:kland,项目名称:multitask,代码行数:32,代码来源:multitask.cpp

示例5: result

static Rcpp::IntegerVector nz_vec(Rcpp::NumericMatrix alpha_new,
				  Rcpp::NumericMatrix eta_new,
				  Rcpp::NumericVector d_new,
				  double eps)
{
  int K = alpha_new.ncol();
  int p = alpha_new.nrow();
  int L = eta_new.nrow();
  
  Rcpp::IntegerVector result(p*K + L*K + L);
 	
  for (int i = 0; i < p*K; i++) {
    result[i] = nz(alpha_new[i],eps);
  }

  for (int i = 0; i < L*K; i++) {
    result[p*K + i] = nz(eta_new[i],eps);
  }

  for (int i = 0; i < L; i++) {
    result[p*K + L*K + i] = nz(d_new[i],eps);
  }

  return result;
}
开发者ID:kland,项目名称:multitask,代码行数:25,代码来源:multitask.cpp

示例6: bic_logistic

static double bic_logistic(Rcpp::NumericMatrix X, 
			   Rcpp::NumericVector y, 
			   Rcpp::NumericMatrix beta_new, 
			   double eps, 
			   Rcpp::IntegerVector nk)
{
  int n_tot = X.nrow();
  int p = X.ncol();
  int K = nk.size();
    
  int idx = 0;
  double ll = 0.0;
  for (int k = 0; k < K; k++) {
    int n = nk[k];
    for (int i = 0; i < n; i++) {
      double lp = 0.0;
      for (int j = 0; j < p; j++) {
	lp += elem(X, idx+i, j) * elem(beta_new, j, k);
      }
      ll += y[idx+i] * lp - log(1.0 + exp(lp));
    }
    idx += n;
  }
  
  double bic = -2.0 * ll + df(beta_new, eps) * log(n_tot);
  return bic;
}
开发者ID:kland,项目名称:multitask,代码行数:27,代码来源:multitask.cpp

示例7: corRcpp

//' Marginal correlation matrix
//' 
//' Various workhorse functions to compute the marginal (or unconditional) 
//' correlations (and cross-correlation) estimates efficiently. 
//' They are (almost) 
//' equivalent implementations of \code{\link[stats]{cor}} in Rcpp, 
//' RcppArmadillo, and RcppEigen.
//' 
//' @rdname corFamily
//' @aliases corFamily
//'   corRcpp xcorRcpp corArma xcorArma corEigen xcorEigen
//' @param X A numeric matrix.
//' @param Y A numeric matrix of compatible dimension with the \code{X}, i.e. 
//'   \code{nrow(X)} equals \code{nrow(Y)}.
//' @return
//'   The \code{corXX} family returns a numeric correlation matrix of size 
//'   \code{ncol(X)} times \code{ncol(X)}.
//'   
//'   The \code{xcorXX} family returns a numeric cross-correlation matrix 
//'   of size \code{ncol(X)} times \code{ncol(Y)}.
//' @details
//'   Functions almost like \code{\link{cor}}.
//'   For the \code{xcorXX} functions, the \code{i}'th and \code{j}'th 
//'   entry of the output matrix is the correlation between \code{X[i, ]} and 
//'   \code{X[j, ]}.
//'   Likewise, for the \code{xcorXX} functions, the \code{i}'th and
//'   \code{j}'th entry of the output is the correlation between \code{X[i, ]} 
//'   and \code{Y[j, ]}.
//' @note 
//'   \code{NA}s in \code{X} or \code{Y} will yield \code{NA}s in the correlation matrix.
//'   This also includes the diagonal unlike the behavior of 
//'   \code{\link[stats]{cor}}.
//' @author Anders Ellern Bilgrau <anders.ellern.bilgrau (at) gmail.com>
//' @export
// [[Rcpp::export]]
Rcpp::NumericMatrix corRcpp(Rcpp::NumericMatrix & X) {
  
  const int m = X.ncol();
  const int n = X.nrow();
  
  // Centering the matrix
  X = centerNumericMatrix(X);
  
  Rcpp::NumericMatrix cor(m, m);
  
  // Degenerate case
  if (n == 0) {
    std::fill(cor.begin(), cor.end(), Rcpp::NumericVector::get_na());
    return cor; 
  }
  
  // Compute 1 over the sample standard deviation
  Rcpp::NumericVector inv_sqrt_ss(m);
  for (int i = 0; i < m; ++i) {
    inv_sqrt_ss(i) = 1/sqrt(Rcpp::sum(X(Rcpp::_, i)*X(Rcpp::_, i)));
  }
  
  // Computing the correlation matrix
  for (int i = 0; i < m; ++i) {
    for (int j = 0; j <= i; ++j) {
      cor(i, j) = Rcpp::sum(X(Rcpp::_,i)*X(Rcpp::_,j)) *
        inv_sqrt_ss(i) * inv_sqrt_ss(j);
      cor(j, i) = cor(i, j);
    }
  }

  return cor;
}
开发者ID:AEBilgrau,项目名称:correlateR,代码行数:68,代码来源:corFamily.cpp

示例8: cdm_rcpp_irt_classify_individuals

///********************************************************************
///**  cdm_rcpp_irt_classify_individuals
// [[Rcpp::export]]
Rcpp::List cdm_rcpp_irt_classify_individuals( Rcpp::NumericMatrix like )
{
    int N = like.nrow();
    int TP = like.ncol();
    Rcpp::IntegerVector class_index(N);
    Rcpp::NumericVector class_maxval(N);
    double val=0;
    int ind=0;
    for (int nn=0; nn<N; nn++){
        val=0;
        ind=0;
        for (int tt=0; tt<TP; tt++){
            if ( like(nn,tt) > val ){
                val = like(nn,tt);
                ind = tt;
            }
        }
        class_index[nn] = ind + 1;
        class_maxval[nn] = val;
    }
    //---- OUTPUT:
    return Rcpp::List::create(
                Rcpp::Named("class_index") = class_index,
                Rcpp::Named("class_maxval") = class_maxval
        );
}
开发者ID:cran,项目名称:CDM,代码行数:29,代码来源:cdm_rcpp_irt_classify.cpp

示例9: reweight

    /** 
     * Update V, Vtr and fac
     *
     * Note: May want to update fac in a separate operation.  For the
     * fixed-effects modules this will update the factor twice because
     * it is separately updated in updateRzxRx.
     * 
     * @param Xwt square root of the weights for the model matrices
     * @param wtres weighted residuals
     */
    void sPredModule::reweight(Rcpp::NumericMatrix   const&   Xwt,
			       Rcpp::NumericVector   const& wtres) throw(std::runtime_error) {
	if (d_coef.size() == 0) return;
	double one = 1., zero = 0.;
	int Wnc = Xwt.ncol();//, Wnr = Xwt.nrow(),
//	    Xnc = d_X.ncol, Xnr = d_X.nrow;
	if ((Xwt.rows() * Xwt.cols()) != (int)d_X.nrow)
	    throw std::runtime_error("dimension mismatch");
	    // Rf_error("%s: dimension mismatch %s(%d,%d), %s(%d,%d)",
	    // 	     "deFeMod::reweight", "X", Xnr, Xnc,
	    // 	     "Xwt", Wnr, Wnc);
	if (Wnc == 1) {
	    if (d_V) M_cholmod_free_sparse(&d_V, &c);
	    d_V = M_cholmod_copy_sparse(&d_X, &c);
	    chmDn csqrtX(Xwt);
	    M_cholmod_scale(&csqrtX, CHOLMOD_ROW, d_V, &c);
	} else throw runtime_error("sPredModule::reweight: multiple columns in Xwt");
// FIXME write this combination using the triplet representation
	
	chmDn cVtr(d_Vtr);
	const chmDn cwtres(wtres);
	M_cholmod_sdmult(d_V, 'T', &one, &zero, &cwtres, &cVtr, &c);

	CHM_SP Vt = M_cholmod_transpose(d_V, 1/*values*/, &c);
	d_fac.update(*Vt);
	M_cholmod_free_sparse(&Vt, &c);
    }
开发者ID:rforge,项目名称:lme4,代码行数:37,代码来源:predModules.cpp

示例10: y

///********************************************************************
///** scale2_NA_C
// [[Rcpp::export]]
Rcpp::NumericMatrix scale2_NA_C( Rcpp::NumericMatrix x )
{
    int n = x.nrow();
    int p = x.ncol();
    Rcpp::NumericMatrix y(n,p);
    double mvv=0;
    double sdvv=0;
    double nvv=0;
    double eps_add = 1e-10;
    for (int vv=0;vv<p;vv++){
        mvv=0;
        sdvv=0;
        nvv=0;
        for (int ii=0;ii<n;ii++){
            if (! R_IsNA(x(ii,vv)) ) {
                mvv += x(ii,vv);
                sdvv += std::pow( x(ii,vv), 2.0 );
                nvv ++;
            }
        }
        mvv = mvv / nvv;
        sdvv = std::sqrt( ( sdvv - nvv * mvv*mvv )/(nvv - 1.0 ) );
        // define standardization
        y(_,vv) = ( x(_,vv) - mvv ) / ( sdvv + eps_add );
    }
    //--- output
    return y;
}
开发者ID:cran,项目名称:miceadds,代码行数:31,代码来源:miceadds_rcpp_scale.cpp

示例11: CheckFinite

//' Check whether there are any non-finite values in a matrix
//'
//' The C++ functions will not work with NA values, and the calculation of the
//' summary profile will take a long time to run before crashing.
//'
//' @param matPtr matrix to check.
//' 
//' @return
//'  Throws an error if any \code{NA}, \code{NaN}, \code{Inf}, or \code{-Inf}
//'  values are found, otherwise returns silently.
//' 
// [[Rcpp::export]]
void CheckFinite(Rcpp::NumericMatrix matPtr) {
  arma::mat mat = arma::mat(matPtr.begin(), matPtr.nrow(), matPtr.ncol(), false, true);
  arma::uvec nonFiniteIdx = arma::find_nonfinite(mat);
  if (nonFiniteIdx.n_elem > 0) {
    throw Rcpp::exception("matrices cannot have non-finite or missing values");
  } 
}
开发者ID:xflicsu,项目名称:NetRep,代码行数:19,代码来源:checkFinite.cpp

示例12:

void ScoreGaussL0PenScatter::setData(Rcpp::List& data)
{
	std::vector<int>::iterator vi;
	//uint i;

	// Cast preprocessed data from R list
	dout.level(2) << "Casting preprocessed data...\n";
	_dataCount = Rcpp::as<std::vector<int> >(data["data.count"]);
	dout.level(3) << "# samples per vertex: " << _dataCount << "\n";
	_totalDataCount = Rcpp::as<uint>(data["total.data.count"]);
	dout.level(3) << "Total # samples: " << _totalDataCount << "\n";
	Rcpp::List scatter = data["scatter"];
	Rcpp::NumericMatrix scatterMat;
	_disjointScatterMatrices.resize(scatter.size());
	dout.level(3) << "# disjoint scatter matrices: " << scatter.size() << "\n";
	for (R_len_t i = 0; i < scatter.size(); ++i) {
		scatterMat = Rcpp::NumericMatrix((SEXP)(scatter[i]));
		_disjointScatterMatrices[i] = arma::mat(scatterMat.begin(), scatterMat.nrow(), scatterMat.ncol(), false);
	}

	// Cast index of scatter matrices, adjust R indexing convention to C++
	std::vector<int> scatterIndex = Rcpp::as<std::vector<int> >(data["scatter.index"]);
	for (std::size_t i = 0; i < scatterIndex.size(); ++i)
		_scatterMatrices[i] = &(_disjointScatterMatrices[scatterIndex[i] - 1]);

	// Cast lambda: penalty constant
	_lambda = Rcpp::as<double>(data["lambda"]);
	dout.level(3) << "Penalty parameter lambda: " << _lambda << "\n";

	// Check whether an intercept should be calculated
	_allowIntercept = Rcpp::as<bool>(data["intercept"]);
	dout.level(3) << "Include intercept: " << _allowIntercept << "\n";
}
开发者ID:igraph,项目名称:pcalg,代码行数:33,代码来源:score.cpp

示例13: rcpp_validate

//' @title Calculating validation scores between two adjacency matrices
//' 
//' @description
//' This function calculates the validation scores between two adjacency matrices.
//' 
//' @param inf_mat matrix. It should be adjacency matrix of inferred network.
//' @param true_mat matrix. It should be adjacency matrix of true network.
// [[Rcpp::export]]
Rcpp::NumericVector rcpp_validate(Rcpp::NumericMatrix inf_mat, Rcpp::NumericMatrix true_mat) {
  if(inf_mat.ncol() != true_mat.ncol()) {
    throw std::invalid_argument( "Two input matrices should have the same number of columns." );
  }
  if(inf_mat.nrow() != true_mat.nrow()) {
    throw std::invalid_argument( "Two input matrices should have the same number of rows." );
  }
  
  int tp=0;
  int tn=0;
  int fp=0;
  int fn=0;
  for(signed int i=0; i<inf_mat.nrow(); i++) {
    //Convert R objects into C++ objects.
    Rcpp::NumericVector xr = inf_mat.row(i);
    Rcpp::NumericVector yr = true_mat.row(i);
    std::vector<int> x = Rcpp::as<std::vector <int> >(xr);
    std::vector<int> y = Rcpp::as<std::vector <int> >(yr);
    std::vector<int> z;
    
    //Calculate the frequency of numbers.
    //tp=true positive [1,1], tn=true negative [0,0], fp=false positive [1,0], fn=false negative [0,1].
    for(unsigned int k=0; k<x.size(); k++) {
      z.push_back(x[k] + y[k]); //Calculate the summation of x and y between each element.
                
      if(z[k] == 2) {
        tp += 1;
      } else if(z[k] == 0) {
        tn += 1;
      } else if(z[k] == 1) {
        if(x[k] == 0) {
          fp += 1;
        } else {
          fn += 1;
        }
      } else {
        throw std::invalid_argument("Error in calculating the contigency table.");
      }
    }
  }
  
  //std::vector<int> output{tp, tn, fp, fn}; c++11 only
  int tmp_arr[4] = {tp, tn, fp, fn};
  std::vector<int> output(&tmp_arr[0], &tmp_arr[0]+4);

  return Rcpp::wrap(output);
}
开发者ID:cran,项目名称:BTR,代码行数:55,代码来源:score_calculation.cpp

示例14: compute_lambda

// This calculates lambda from a lookup table index by transition (row) and rounded quality (col)
double compute_lambda(Raw *raw, Sub *sub, Rcpp::NumericMatrix errMat, bool use_quals) {
  // use_quals does nothing in this function, just here for backwards compatability for now
  int s, pos0, pos1, nti0, nti1, len1, ncol;
  double lambda;
  float prefactor, fqmin;
  int tvec[SEQLEN];
  int qind[SEQLEN];
  
  if(!sub) { // NULL Sub, outside Kmer threshold
    return 0.0;
  }
  
  // Make vector that indexes as integers the transitions at each position in seq1
  // Index is 0: exclude, 1: A->A, 2: A->C, ..., 5: C->A, ...
  len1 = raw->length;
  ncol = errMat.ncol();
  prefactor = ((float) (ncol-1))/((float) QMAX-QMIN);
  fqmin = (float) QMIN;
  for(pos1=0;pos1<len1;pos1++) {
    nti1 = ((int) raw->seq[pos1]) - 1;
    if(nti1 == 0 || nti1 == 1 || nti1 == 2 || nti1 == 3) {
      tvec[pos1] = nti1*4 + nti1;
    } else {
      Rcpp::stop("Error: Can't handle non ACGT sequences in CL3.");
    }
    if(raw->qual) {
      // Turn quality into the index in the array
      qind[pos1] = round(prefactor * (raw->qual[pos1] - fqmin));
    } else {
      qind[pos1] = 0;
    }
    
    if( qind[pos1] > (ncol-1) ) {
      Rcpp::stop("Error: rounded quality exceeded err lookup table.");
    }
  }

  // Now fix the ones where subs occurred
  for(s=0;s<sub->nsubs;s++) {
    pos0 = sub->pos[s];
    if(pos0 < 0 || pos0 >= len1) { Rcpp::stop("CL: Bad pos0."); }
    pos1 = sub->map[sub->pos[s]];
    if(pos1 < 0 || pos1 >= len1) { Rcpp::stop("CL: Bad pos1."); }
    
    nti0 = ((int) sub->nt0[s]) - 1;
    nti1 = ((int) sub->nt1[s]) - 1;
    tvec[pos1] = nti0*4 + nti1;
  }

  // And calculate lambda
  lambda = 1.0;
  for(pos1=0;pos1<len1;pos1++) {
    lambda = lambda * errMat(tvec[pos1], qind[pos1]);
  }

  if(lambda < 0 || lambda > 1) { Rcpp::stop("Bad lambda."); }

  return lambda;
}
开发者ID:cd-mcfarland,项目名称:dada2,代码行数:60,代码来源:pval.cpp

示例15: ZERO

//[[Rcpp::export]]
Rcpp::NumericMatrix ZERO(Rcpp::NumericMatrix x) {
  int i=0, j=0;
  for(i=0; i < x.ncol(); i++) {
    for(j=0; j < x.nrow(); j++) {
      x(i,j) = 0;
    }
  }
  return(x);
}
开发者ID:justinpenz,项目名称:mrgsolve,代码行数:10,代码来源:mrgsolve.cpp


注:本文中的rcpp::NumericMatrix::ncol方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。