DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解
C++ 的 MTL 函式庫示例:矩陣複製與轉置(整理 by RobinKin from DevonIT)
編輯:AJAX詳解     

MTL(Matrix Template Library)是一套高效能的數值線性代數函式庫。以下範例示範如何利用 mtl::copy,把矩陣 A 的「欄」複製到矩陣 B 的「列」,藉此達到轉置的效果:

// 矩陣 copy 與轉置
// -*- c++ -*-
//
// $COPYRIGHT$
//
//===========================================================================

#include <iostream>
using namespace std;

#include <mtl/matrix.h>
#include <mtl/mtl.h>
#include <mtl/utils.h>
#include <mtl/linalg_vec.h>

/*
  Transpose matrix A into matrix B using mtl::copy.
  (We could use the mtl::transpose(A,B) function,
   but then this wouldn't be an example about mtl::copy)

  Sample Output

  3x3
  [
  [1,4,7],
  [2,5,8],
  [3,6,9]
  ]
  3x3
  [
  [1,2,3],
  [4,5,6],
  [7,8,9]
  ]

  */

using namespace mtl;

typedef matrix< double, rectangle<>,
                dense<>, column_major>::type Matrix;

/* An external matrix - uses memory from some "outside" source, and
  just makes that memory look like an MTL Matrix */
typedef matrix< double, rectangle<>,
                dense<external>, column_major>::type EMatrix;

int
main()
{
  int i;
  const int N = 3;
  double da[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

  EMatrix A(da, N, N);
  Matrix B(N, N);

  print_all_matrix(A);

  // Copy the columns of A into the rows of B
  for (i = 0; i < N; ++i)
    copy(A[i], rows(B)[i]); // rows(B) 建立 B 的一個「列導向」檢視

  print_all_matrix(B);

  return 0;
}

範例中先宣告兩種矩陣型別:Matrix 是 MTL 內建的矩陣,EMatrix 則是「外部矩陣」——它借用來自外部來源的記憶體,只是讓那塊記憶體看起來像一個 MTL 矩陣。核心邏輯在於那個迴圈:透過 copy 函式,把 A 的每一「欄」逐一複製到 B 對應的「列」上,其中 rows(B) 會建立 B 的一個列導向檢視。由於 A 是 3×3 矩陣,複製完成後,B 就正好是 A 的轉置矩陣。這個例子也巧妙展示了 MTL 靈活的檢視(view)與迭代機制。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved