This blog is under construction

Sunday, 28 July 2013

C program to find the norm of a matrix

Write a C program to find the norm of a matrix.
Consider the below matrix.
10 20 30 40 50
50 20 30 40 10
20 30 40 50 60

Find the sum of elements in each column:
80 70 100 130 120

Find the maximum value in above manipulated value.
max(80, 70, 100, 130, 120)

120 is the norm of the given matrix.


  #include <stdio.h>
  #define ROW 10
  #define COL 10

  int main() {
        int array[ROW][COL], norm[COL] = {0};
        int i, j, row, col, max;

        /* get the number of rows in input matrix */
        printf("Enter the number of rows:");
        scanf("%d", &row);

        /* get the number of columns in input matrix */
        printf("Enter the number of columns:");
        scanf("%d", &col);

        /* get the entries for the given input matrix */
        printf("Enter the entries for input matrix:\n");
        for (i = 0; i < row; i++) {
                for (j = 0; j < col; j++) {
                        scanf("%d", &array[i][j]);
                }
        }

        /* find the sum of elements in each column */
        for (i = 0; i < col; i++) {
                for (j = 0; j < row; j++) {
                        norm[i] = norm[i] + array[j][i];
                }
        }

        max = norm[0];

        /* maximum value in column sum */
        for (i = 0; i < col; i++) {
                if (max < norm[i]) {
                        max = norm[i];
                }
        }

        /* printing the result */
        printf("Max(");
        for (i = 0; i < col; i++) {
                printf("%d ", norm[i]);
        }
        printf(")\n");

        printf("Norm of the given matrix is %d\n", max);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of rows:3
  Enter the number of columns:5
  Enter the entries for input matrix:
  10 20 30 40 50
  50 20 30 40 10
  20 30 40 50 60
  Max(80 70 100 130 120 )

  Norm of the given matrix is 130


1 comment:

  1. For this program to compute the norm 1 of any matrix properly, the line
    norm[i] = norm[i] + array[j][i]; should be modified to
    norm[i] = norm[i] + abs(array[j][i]);

    ReplyDelete