Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
2.8 kB
3
Indexable
Never
#include <stdio.h>
#include <stdlib.h>

float matrix1[3][3];
float matrix2[3][3];
float sum_matrix[3][3];

float * matrix3D(char letter, float matrix[3][3]);
void matrixPrint(int r, int c, float *matrix);
float traceMatrix(int r, int c, float matrix[3][3]);
void sumMatrix(int r, int c, float *matrix_a, float *matrix_b);

int main(void)
{
    int stu_id = 70357003;

    /// Q3a
    float *Mat_A, *Mat_B;
    int row = 3;
    int column = 3;
    printf("Please enter two 3-by-3 matrices below.\n");
    printf("Please enter for the first matrix called 'Mat_A'.\n");
    Mat_A = matrix3D('A', matrix1);
    printf("Please enter for the second matrix called 'Mat_B'.\n");
    Mat_B = matrix3D('B', matrix2);

    // Print for checking
    printf("<Mat_A>\n");
    matrixPrint(row, column, Mat_A);
    puts("");
    printf("<Mat_B>\n");
    matrixPrint(row, column, Mat_B);

    puts("");
    /// Q3b
    float trace_A, trace_B;
    trace_A = traceMatrix(row, column, Mat_A);
    trace_B = traceMatrix(row, column, Mat_B);
    printf("The trace of Mat_A is %f\n", trace_A);
    printf("The trace of Mat_B is %f\n", trace_B);

    puts("");
    /// Q3c
    sumMatrix(row, column, Mat_A, Mat_B);

    printf("\n\nStudent ID: %d\n\n", stu_id);
    return 0;
}

float * matrix3D(char letter, float matrix[3][3]){
//    static float matrix[3][3];
    float element;

    printf("Please enter the elements row-by-row\n");
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            printf("Mat_%c [%d][%d]: ", letter, i, j);
            scanf("%f", &element);
            matrix[i][j] = element;
        }
    }
    return matrix;
}

void matrixPrint(int r, int c, float *matrix){
    printf("Matrix in 2-D format:\n");
    for(int i = 0; i < r; i++){
        for(int j = 0; j < c; j++){
            printf("%f ", *(matrix + i*3 + j));
            if(j == c - 1){
                printf("\n");
            }
        }
    }
}

float traceMatrix(int r, int c, float matrix[3][3]){
    float trace = 0;
    for(int i = 0; i < r; i++){
        trace += matrix[i][i];
    }
    return trace;
}

void sumMatrix(int r, int c, float *matrix_a, float *matrix_b){
    float element_a = 0;
    float element_b = 0;
    for(int i = 0; i < r; i++){
        for(int j = 0; j < c; j++){
            element_a = *(matrix_a + i*3 + j);
            element_b = *(matrix_b + i*3 + j);
            sum_matrix[i][j] = element_a + element_b;
        }
    }

    printf("The sum of two matrices is:\n");
    for(int i = 0; i < r; i++){
        for(int j = 0; j < c; j++){
            printf("%f ", sum_matrix[i][j]);
            if(j = c - 1){
                printf("\n");
            }
        }
    }
}