C++模仿Numpy常用文本文件读取、写入

本文介绍了一套用于C++的简单工具,该工具能够帮助开发者轻松地从文本文件中读取矩阵数据,并能将矩阵数据保存到文本文件中。支持自定义分隔符、注释符以及固定精度的输出。

经常用C++读入、写出(打印)矩阵数组,觉得要想办法自动解决一下这个问题。于是开始模仿Python的Numpy,矩阵暂时用vector<vector<double>>代替:

*目前是V0.1

实现功能主要如下:

  • ReadTxt.h / ReadTxt.cpp
    • genFromtxt(支持分隔符和注释,制表符视为空格,返回vector<vector<double>>
  • WriteTxt.h / Writetxt.cpp
    • print(显示在屏幕上,fixed,可控制位数)
    • saveTxt(将vector<vector<double>>保存为文件,fixed,可控制位数)

更详细一点的说明见头文件函数定义注释

😄ReadTxt.h

/*
@author: Kan Haoyu
@date: 2021/3/8
@function: Basic text Input 
*/


#pragma once
#ifndef READTXT_H
#define READTXT_H

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>

using namespace std;

// read a txt into a vector<vector<double>> ;
// line splited by split_char; 
// string after comment_char will be discarded; 
// line without contents(pure comment) will also be discarded
vector<vector<double>> genFromtxt(const string& file_path, const char split_char, const char comment_char);

// return a string where substring after comment_char will be discarded
string decommentString(const string& str, const char comment_char);

// split string with split_char into a vector<string>
vector<string> splitString(const string& str, const char split_char);

// convert vector<string> into vector<double>
vector<double> asDouble(const vector<string>& vec_str);

// replace all tab('\t') with blankspace(' ') in a string and return the result
string replaceTabWithBlankspace(const string& str);




#endif

😄ReadTxt.cpp

#include "ReadTxt.h"

vector<vector<double>> genFromtxt(const string& file_path, const char split_char, 
### Vector Signal Processing Overview Vector signals play a crucial role in various domains including telecommunications, radar systems, and digital signal processing. A vector signal is characterized by both magnitude and direction at each point in time or space. In programming and data analysis, handling vector signals involves several key operations: #### Representation of Vector Signals A common approach to representing vector signals is using arrays or lists where each element corresponds to one component of the vector. For instance, in Python, this could be done with NumPy arrays which provide efficient storage and manipulation capabilities for large datasets[^1]. ```python import numpy as np # Example of creating a simple vector signal time_points = np.linspace(0, 1, num=500) amplitude = np.sin(2 * np.pi * 3 * time_points) vector_signal = np.column_stack((time_points, amplitude)) print(vector_signal[:5]) # Display first five elements ``` #### Filtering Techniques Filtering techniques are essential when dealing with noisy real-world measurements. Low-pass filters remove high-frequency noise while preserving lower frequencies present within the original signal. High-pass filters do exactly opposite—eliminating slow variations but keeping rapid changes intact. For example, applying a low-pass filter on our previously created sine wave might look like below code snippet shows how it's implemented efficiently via SciPy library functions[^2]: ```python from scipy.signal import butter, filtfilt def apply_low_pass_filter(data, cutoff_frequency, sample_rate): nyquist_freq = 0.5 * sample_rate normal_cutoff = cutoff_frequency / nyquist_freq b, a = butter(order=5, Wn=normal_cutoff, btype='low', analog=False) filtered_data = filtfilt(b=b, a=a, x=data[:, 1]) return np.vstack([data[:, 0], filtered_data]).T filtered_vector_signal = apply_low_pass_filter( data=vector_signal, cutoff_frequency=1., sample_rate=len(time_points)/(max(time_points)-min(time_points)) ) ``` #### Fourier Transform Analysis Fourier transforms convert time-domain representations into frequency domain ones allowing us better understand underlying patterns hidden inside complex waves. Fast Fourier Transforms (FFT), available through libraries such as FFTW or even simpler implementations found in SciPy/Numpy packages make performing these conversions straightforwardly accessible without needing extensive mathematical background knowledge about integral calculus involved behind scenes during transformation process itself[^3]. ```python from scipy.fft import fft fft_result = abs(fft(filtered_vector_signal[:, 1])) frequencies = np.fft.fftfreq(len(fft_result)) plt.plot(frequencies[frequencies >= 0], fft_result[frequencies >= 0]) plt.xlabel('Frequency') plt.ylabel('|Amplitude|') plt.title('Spectrum after filtering') plt.show() ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值