1

I have to extract a matrix from a file through C and calculate the determinant of it. To do this for any matrix up to a 3x3 I'm sure i'll need to know the dimensions of the matrix but I'm pretty new to programming so I don't know what options I have.

If I have a .dat file with an unspecified matrix in it what can i do to find the dimensions of the matrix?

Just a push in the right direction would be useful as I don't know what my options are

Carterini
  • 165
  • 7
  • This might help perhaps? http://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c – codedude Nov 02 '13 at 16:20
  • If you want to calculate the determinant of a matrix, the matrix is always of the form `n x n`. In this case you could read the content linewise until `EOF`. Then you know the number of rows that is equal to the number of cols. – PhillipD Nov 02 '13 at 16:34
  • I thought of that but unfortunately i don't know how to read the content linewise? – Carterini Nov 02 '13 at 16:38

2 Answers2

1

well what you can do is put them in array and since it is square matrix number of rows=number of columns find the square root of the number of elements

access is through M[i*d+j] d is the dimension of the matrix r=c=d;

tip use dynamic arrays i.e. pointers

Wissam Y. Khalil
  • 133
  • 1
  • 5
  • 13
0

Responding to you comment:

You can determine the number of line in a file by counting the number of \n.

#include <stdio.h>

int main(void) {

    int lines = 0;

    FILE *fh;

    fh = fopen("matrix.dat", "r");

    int ch;

    while (EOF != (ch=fgetc(fh)))
    if (ch=='\n')
        ++lines;

    fclose(fh);

    printf("%d\n", lines);

    return 0;

}
PhillipD
  • 1,797
  • 1
  • 13
  • 23
  • Ahh okay, I didn't know about fgetc() very new to this. Thanks so much for your help by the way i think i'm slowly getting it! – Carterini Nov 02 '13 at 17:05
  • Quick question, what is ch? Is it just a temporary integer you used? – Carterini Nov 02 '13 at 17:25
  • @Carterini `ch` is a temporary variable. `fgetc(file_handle)` reads a single character from a file, i.e. every time we call `fgetc()` we overwrite `ch`, i.e. it is indeed a temporary. See http://www.cplusplus.com/reference/cstdio/getchar/ for more information on `getch()` – PhillipD Nov 02 '13 at 17:32