Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หา Mean Vector ของเมทริกซ์ใน C++

Mean Vector คือเวกเตอร์ที่แต่ละองค์ประกอบเป็นค่าเฉลี่ยของคอลัมน์ในเมทริกซ์

ตัวอย่าง เมทริกซ์ 3×3:

1 2 3
4 5 6
7 8 9
Mean Vector = [4, 5, 6] เพราะ (1+4+7)/3=4, (2+5+8)/3=5, (3+6+9)/3=6

ตัวอย่างโค้ด

#include <iostream>
#define M 3
#define N 3
using namespace std;

void calculateMeanVector(int mat[M][N]) {
    cout << "[ ";
    for (int i = 0; i < N; i++) { // วนตามคอลัมน์
        double sum = 0;
        for (int j = 0; j < M; j++) // วนตามแถว
            sum += mat[j][i];
        double avg = sum / M;
        cout << avg << " ";
    }
    cout << "]";
}

int main() {
    int mat[M][N] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    cout << "Mean vector is: ";
    calculateMeanVector(mat);
    return 0;
}

ผลลัพธ์

Mean vector is: [ 4 5 6 ]

หมายเหตุ

  • โค้ดต้นฉบับมีลูป i, j สลับกันทำให้คำนวณแถวแทนคอลัมน์ เราแก้ไขให้ถูกต้อง
  • สำหรับเมทริกซ์ขนาดใหญ่ ควรใช้ double สำหรับผลรวมป้องกัน Overflow

การใช้งานกับ Vector

vector> mat = {{1,2,3}, {4,5,6}, {7,8,9}};
vector mean(N);
for (int j = 0; j < N; j++) {
    double sum = 0;
    for (int i = 0; i < M; i++) sum += mat[i][j];
    mean[j] = sum / M;
}