gpt4 book ai didi

python - 用 Armadillo 函数替换 `sparse.eye`

转载 作者:行者123 更新时间:2023-11-28 01:52:22 24 4
gpt4 key购买 nike

我有一个 python 脚本,我想使用 Armadillo 用 C++ 重写。在 python 中我有一行

matrix = 1/(12*h)*(sparse.eye(num_points, k = -2, dtype=np.complex).toarray() * 1 + sparse.eye(num_points, k = -1, dtype=np.complex).toarray() * -8 + sparse.eye(num_points, k = 1, dtype=np.complex).toarray() * 8 + sparse.eye(num_points, k = 2, dtype=np.complex).toarray() * -1)

这会生成一个矩阵,其中除五个主对角线外的所有值均为零。不幸的是我在 Armadillo 中找不到类似的功能,目前我能看到的唯一方法是创建一个ones()-matrix,然后用.diag()<设置对角线,然后将其余部分归零。有更简单的方法吗?

最佳答案

以下代码应该具有等效的功能:

// sparse matrices have all values as zero at initialization
sp_mat X(10,10);

X.diag(-2).fill( 1);
X.diag(-1).fill(-8);
X.diag(+1).fill( 8);
X.diag(+2).fill(-1);

X *= 1.0 / (12*h); // the .0 in 1.0 tells the compiler to use the double type

关于python - 用 Armadillo 函数替换 `sparse.eye`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42504963/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com