逆数字矩阵按行
Reverse Numeric Matrix by Row
本文关键字:数字 更新时间:2023-10-16
使用Rcpp
,对于我用R编写的包,我试图反转NumericMatrix,以便最后一行现在将成为第一行,第一行将成为最后一行,换句话说,相对行索引将从1, 2, 3, ... n
到n, n-1, n-2, .... 1
那么,如果我声明下面的函数:
NumericMatrix reverseByRow(NumericMatrix in){
int r = in.nrow();
NumericMatrix nw(r,in.ncol());
for(int i = 0; i < r; i++){
nw.row(i) = in.row(r-i-1);
}
return nw;
}
我有一个'N x M'的数字矩阵,称为'mid',我试图通过以下方式逐行反转:
cout << "Reversing1: " << mid(0,0) << endl;
cout << "Reversing2: "<< mid(1,0) << endl;
mid = reverseByRow(mid);
cout << "Reversed1: " << mid(0,0) << endl;
cout << "Reversed2: " << mid(1,0) << endl;
为什么我得到以下输出,暗示没有任何改变…??
Reversing1: 2806
Reversing2: 7
Reversed1: 2806
Reversed2: 7
我肯定错过了一些非常明显的东西…??? 这是一个'固定'版本,有一个合适的变量名:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericMatrix reverseByRow(NumericMatrix inmat) {
int r = inmat.nrow();
NumericMatrix nw(r,inmat.ncol());
for(int i = 0; i < r; i++){
nw.row(i) = inmat.row(r-i-1);
}
return nw;
}
/*** R
M <- matrix(1:9, 3, 3)
M
reverseByRow(M)
*/
按预期工作:
R> sourceCpp("/tmp/nicholas.cpp")
R> M <- matrix(1:9, 3, 3)
R> M
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
R> reverseByRow(M)
[,1] [,2] [,3]
[1,] 3 6 9
[2,] 2 5 8
[3,] 1 4 7
R>
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 将数字打印成文字
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 在将数字随机生成为数组期间从内存输出随机数的数组