英文:
Armadillo/C++: How to assign elements from a vector to a cube tube?
问题
假设我有一个3x3x4的立方体Q
(即一个具有3行、三列和4切片的立方体),以及一个具有4个元素的列向量C
(即与Q的切片数相同的元素)。有没有办法让我使用C来填充Q的一个管道?
我尝试了以下方法:
# include <armadillo>
cube Q(3,3,4);
mat C(4,1, fill::zeros);
Q.tube(0, 0) = C;
但它没有起作用(出现了运行时异常)。有没有办法在不显式循环管道和向量元素的情况下实现这个目标?
已解决
上面的代码完全有效。事实证明,第一次尝试时我可能做了其他事情(不知道是什么)出错了。感谢darcamo指出代码实际上是有效的!
英文:
Suppose I have a 3x3x4 cube Q
(i.e. a cube having 3 rows, three columns, and 4 slices) and a column vector C
with 4 elements (i.e. as many elements as the slices of Q). Is there a way for me to use C to populate a tube of Q?
I tried the following:
# include <armadillo>
cube Q(3,3,4);
mat C(4,1, fill::zeros);
Q.tube(0, 0) = C;
but it didn't work (got a runtime exception). Is there a way to achieve the goal without looping explicitly through the tube and the vector elements?
SOLVED
The code above works just fine. It turns out I was probably doing something else (don't know what) wrong the first time I tried it. Thanks to darcamo for pointing out the code actually works!
答案1
得分: 1
这很奇怪。我尝试过,对我来说完全正常。在进行赋值之前,尝试将C
矩阵转换为arma::vec
。
Q.tube(0, 0) = arma::conv_to<arma::vec>::from(C);
由于"tube"是一维的,将完整的二维矩阵分配给它是没有意义的。尽管在你的情况下,它是一个列矩阵,应该可以工作。
我不需要进行转换,但值得尝试,因为由于不同的标志、编译器支持等原因,一些Armadillo中的功能可能不可用。
英文:
That is strange. I try it and it worked just fine for me. Try converting the C
matrix into an arma::vec
before with the assignment.
Q.tube(0, 0) = arma::conv_to<arma::vec>::from(C);
Since a "tube" is one-dimensional it does not make sense to assign a full 2D matrix to it anyway. Although in your case it's a column matrix and it should work.
I didn't need to convert it, but it is worth trying, since some features in armadillo might not be available due to different flags, compiler support, etc.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论