How to extract a submatrix from a matrix .. ?

Posted by ZaZu on Stack Overflow See other posts from Stack Overflow or by ZaZu
Published on 2010-05-08T23:41:14Z Indexed on 2010/05/08 23:48 UTC
Read the original article Hit count: 170

Filed under:
|

Hello,

I have a matrix in a txt file and I want to load the matrix based on my input of number of rows and columns

For example, I have a 5 by 5 matrix in the file. I want to extract a 3 by 3 matrix, how can I do that ?

I created a nested loop using :

FILE *sample
sample=fopen("randomfile.txt","r"); 
for(i=0;i<rows;i++){
  for(j=0;j<cols;j++){
     fscanf(sample,"%f",&matrix[i][j]);
   }
 fscanf(sample,"\n",&matrix[i][j]);
}
fclose(sample);

Sadly the code does not work .. If I have this matrix :

5.00    4.00    5.00    6.00    
5.00    4.00    3.00    25.00   
5.00    3.00    4.00    23.00   
5.00    2.00    352.00  6.00

And inputting 3 for rows and 3 for columns, I get :

5.00    4.00    5.00
6.00    5.00    4.00
3.00    25.00   5.00

Which is obviously wrong , its reading line by line rather than skipping the unmentioned column ...

What am I doing wrong ?

Thanks !

© Stack Overflow or respective owner

Related posts about c

    Related posts about matrix