บทนำ
ในบทช่วยสอนนี้ เราจะหา Trace (แทรซ/ผลรวมแนวทแยง) ของแมทริกซ์ที่ได้จากการบวก Row-major matrix และ Column-major matrix ของออเดอร์เดียวกัน
Row-major vs Column-major
Order 3×3:
Row-major: Column-major:
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
| 1 | 4 | 7 |
| 2 | 5 | 8 |
| 3 | 6 | 9 |
ขั้นตอนการแก้ปัญหา
- สร้าง Row-major matrix (เติมแถวก่อนคอลัมน์)
- สร้าง Column-major matrix (เติมคอลัมน์ก่อนแถว)
- บวกแมทริกซ์ทั้งสอง
- หา Trace (ผลรวม diagonal: result[i][i])
ตัวอย่างโค้ด
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int traceOfRowAndColumnMajorMatrices(int m, int n) {
int row_major[m][n], column_major[m][n], addition_result[m][n], count = 1;
// Row-major: เติมแถว
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
row_major[i][j] = count++;
}
}
count = 1;
// Column-major: เติมคอลัมน์
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
column_major[j][i] = count++;
}
}
// บวกแมทริกซ์
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
addition_result[i][j] = row_major[i][j] + column_major[i][j];
}
}
// หา Trace
int trace = 0;
for (int i = 0; i < m; i++) {
trace += addition_result[i][i];
}
return trace;
}
int main() {
int m = 3, n = 3;
cout << traceOfRowAndColumnMajorMatrices(m, n) << endl;
return 0;
}
ผลลัพธ์
30
คำนวณ: (1+1)+(5+5)+(9+9) = 2+10+18 = 30
สูตรทั่วไป
สำหรับแมทริกซ์ m×n (m=n):
Trace = Σ(i=0 to n-1) [ (i×n + i + 1) + (i + i×n + 1) ] = Σ 2(i×n + i + 1)
= 2[ nΣi + Σi + n ] = 2[ n×n(n-1)/2 + n(n-1)/2 + n ] = n²(n+1)
สำหรับ n=3: 3²×4 = 36? รอ... ต้องตรวจสอบอีกครั้ง
จริงๆ Row-major[i][i] = i×n + i + 1, Column-major[i][i] = i + i×n + 1 = เหมือนกัน!
ดังนั้น Trace = 2 × Σ(i×n + i + 1) = 2 × [n(n-1)/2 × (n+1) + n] = n(n-1)(n+1) + 2n = n(n²-1) + 2n = n³ + n
n=3: 27+3=30 ✓
สรุป
Trace = n³ + n สำหรับแมทริกซ์ n×n สามารถคำนวณได้ O(1) โดยไม่ต้องสร้างแมทริกซ์ หากมีคำถาม สามารถถามได้ในส่วนความคิดเห็นครับ