【发布时间】:2022-01-06 10:03:38
【问题描述】:
我需要像这样重载 + 操作 a + b = max(a,b)。 因此,我需要它来处理矩阵加法和矩阵乘法以及其他一些操作(跟踪、功率等)。这里 \bigoplus 是 max 操作 使用 Eigen 执行此操作的最佳方法是什么?我读到了特征扩展here,但我不明白如何为我的任务做到这一点。 目前我有这个:
#include <iostream>
#include <Eigen/Dense>
#include <algorithm>
using namespace Eigen;
namespace MaxAlgebra {
template <typename T>
T operator+(const T& a,const T& b) {
T c(a.rows(),a.cols());
for (uint i = 0; i < a.rows(); ++i) {
for (uint j = 0; j < a.cols(); ++j) {
c(i,j) = std::max(a(i,j),b(i,j));
}
}
return c;
}
template <typename T>
T operator*(const T& a,const T& b){
T c(a.rows(),b.cols());
for (uint i = 0; i < a.rows(); ++i) {
for (uint j = 0; j < b.cols(); ++j) {
std::vector<uint> values;
for (uint k = 0; k < a.cols(); ++k) {
values.push_back(a(i,k) * b(k,j));
}
c(i,j) = *std::max_element(begin(values),end(values));
}
}
return c;
}
template <typename T>
uint trace(const T& a) {
std::vector<uint> values;
for (uint i = 0; i < a.rows(); ++i) {
values.push_back(a(i,i));
}
return *std::max_element(begin(values),end(values));
}
}
int main() {
MatrixXd x(2,2);
MatrixXd y(2,2);
x(0,0) = 3;
x(1,0) = 2;
x(0,1) = 1;
x(1,1) = 2;
y(0,0) = 2;
y(1,0) = 1;
y(0,1) = 2;
y(1,1) = 3;
MatrixXd c = MaxAlgebra::operator*(x,y);
std::cout << "Here is the matrix a:\n" << x << std::endl;
std::cout << "Here is the matrix b:\n" << y << std::endl;
std::cout << "Here is the matrix c:\n" << c << std::endl;
return 0;
}
【问题讨论】:
标签: eigen