基於 Eigen 實現 循環移位

Eigen 這麼強大的庫竟然沒有移位的功能 ,哎

手寫一個 ,向量版本的沒貼出,比較簡單嘻嘻

/*循環移位
a b 爲正數時 向下移動a行 ,向右移動b 列
*/
MatrixXd circshift(MatrixXd data, int A, int B = 0)
{
	UINT row = data.rows();
	UINT col = data.cols();
	MatrixXd out(row, col);
	MatrixXd y(row, col);
	int a = A%row;
	int b = B%col;
	if (a > 0)//向下移動a行
	{
		out.topRows(a) = data.bottomRows(a);
		out.bottomRows(row - a) = data.topRows(row - a);
	}
	else if (a < 0)//向上移動a行
	{
		out.topRows(row + a) = data.bottomRows(row + a);
		out.bottomRows(abs(a)) = data.topRows(abs(a));
	}
	else if (a == 0)
	{
		out.array() = data.array();
	}


	if (b > 0)//向右移動b列
	{
		y.leftCols(b) = out.rightCols(b);
		y.rightCols(col - b) = out.leftCols(col - b);
	}
	else if (b<0)//向左移動b列
	{
		y.leftCols(col + b) = out.rightCols(col + b);
		y.rightCols(abs(b)) = out.leftCols(abs(b));

	}
	else if (b == 0)
	{
		y = out;
	}
	return y;
}

 

測試代碼


	MatrixXd data(3, 3);
	data << 1, 2, 3,
		4, 5, 6,
		7, 8, 9;
	cout << "原始矩陣\n" <<data<< endl;
	cout << "向左移動1次\n" << circshift(data,0, -1) << endl;
	cout << "向右移動2次\n" << circshift(data, 0, 2) << endl;
	cout << "向下移動2次 向左移動1次\n" << circshift(data, 2,-1) << endl;
	cout << "向上移動一次\n" << circshift(data, -1) << endl;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章