C ++实现:矩阵为mat数据类型,取矩阵的实部并输出
时间: 2023-10-01 08:11:57 浏览: 57
假设mat数据类型已经定义好,可以使用以下代码实现:
```c++
// 获取矩阵的实部并输出
void get_real_part(const mat& m) {
for (int i = 0; i < m.rows(); i++) {
for (int j = 0; j < m.cols(); j++) {
std::cout << m(i, j).real() << " ";
}
std::cout << std::endl;
}
}
```
其中,mat.rows() 和 mat.cols() 分别返回矩阵的行数和列数,m(i,j) 返回矩阵中第 i 行、第 j 列的元素,m(i,j).real() 返回该元素的实部。通过双重循环遍历矩阵中的所有元素,依次输出实部即可。
相关问题
C ++实现:取矩阵的实部并输出
假设矩阵用二维数组表示,可以使用以下代码实现取矩阵的实部并输出:
```cpp
#include <iostream>
using namespace std;
int main() {
int rows, cols;
cout << "Enter the number of rows and columns for the matrix: ";
cin >> rows >> cols;
double matrix[rows][cols];
// Input the matrix
cout << "Enter the elements of the matrix: " << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrix[i][j];
}
}
// Output the real part of the matrix
cout << "The real part of the matrix is:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << matrix[i][j].real() << " ";
}
cout << endl;
}
return 0;
}
```
这里使用了 `std::complex` 类型,因为它可以表示复数,其中 `real()` 函数可以返回复数的实部。
C++ 图像matA进行傅里叶变换得到matB,取matB的实部输出存储为图片matC
你可以使用OpenCV库来进行傅里叶变换,实现代码如下:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// 读入图片
Mat matA = imread("input.jpg", IMREAD_GRAYSCALE);
// 进行傅里叶变换
Mat matB;
dft(matA, matB, DFT_COMPLEX_OUTPUT);
// 取实部
Mat planes[2];
split(matB, planes);
Mat matC = planes[0];
// 输出存储为图片
imwrite("output.jpg", matC);
return 0;
}
```
在代码中,我们首先读入原始图片 `matA`,然后通过 `dft` 函数进行傅里叶变换,将结果存储在 `matB` 中。接着,我们将 `matB` 拆分成实部和虚部两个矩阵,取出实部矩阵 `matC`。最后,将 `matC` 存储为图片文件。
需要注意的是,傅里叶变换是基于复数运算的,所以我们在进行傅里叶变换时要使用 `DFT_COMPLEX_OUTPUT` 标志位,将结果存储为复数矩阵。因此,在取实部时,我们需要将复数矩阵拆分成实部和虚部两个矩阵。