473,785 Members | 2,602 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Finding the determinant of a matrix

79 New Member
I am having trouble making this recursive C function work for square matrices of size greater than 3 rows and columns.

Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2. #include<conio.h>
  3. #include<math.h>
  4. int M[100];
  5. float DET(float A[][100],int dim)
  6. {
  7. int i=100,j,k,l;
  8. static int det=0;
  9. static int DIM=dim;
  10. if(dim>2)
  11.     for(i=0;i<DIM;i++)
  12.     {
  13.     if(i==0&&DIM==dim)for(j=0;j<100;j++)M[j]=100;
  14.     for(j=DIM-1;j>=2;j--)
  15.     if(M[j]==i)continue;
  16.     M[dim-1]=i;
  17.     det+=pow(-1,i+dim-1)*A[dim-1][i]*DET(A,dim-1);
  18.     }
  19.     if(i==DIM-1)M[dim-1]=100;
  20. if(dim==2)
  21.       {
  22.     for(i=0;i<DIM;i++)
  23.     {
  24.     k=0;
  25.       for(j=DIM-1;j>=2;j--)
  26.     if(i!=M[j])k++;
  27.     if(k==DIM-2)break;
  28.     }
  29.     for(j=0;j<DIM;j++)
  30.     {
  31.     k=0;
  32.     for(l=DIM-1;l>=2;l--)
  33.     if(j!=M[l])k++;
  34.     if(k==DIM-2&&j!=i)break;
  35.     }
  36.     return(A[0][i]*A[1][j]-A[0][j]*A[1][i]);
  37.       }
  38. if(dim==1)return(A[0][0]);
  39. return(det);
  40. }
  41.  
  42.  
  43. void main()
  44. {
  45. float A[100][100];
  46. int n,k,l;
  47. puts("Input size of square matrix:");
  48. scanf("%d",&n);
  49. puts("Input square matrix:");
  50. for(k=0;k<n;k++)
  51. {
  52. printf("\n");
  53. for(l=0;l<n;l++)
  54. {
  55. printf("Input a%d%d: ",k+1,l+1);
  56. scanf("%f",&A[k][l]);
  57. }
  58. }
  59. printf("\n\nThe determenant of the matrix is %0.2f",DET(A,n));
  60. getch();
  61. }
  62.  
If anyone can tell me where I went wrong in writing the program I would be grateful.
P.S.:Here are some points to make the program clearer:
_This program works by using method of minor.
_M[100] is an array of integers used to store in decreasing order of its elements which column in the matrix does not belong to the minor associated with the element chosen on a certain row.
_In the function, dim represents wich row is being used, while i(in the first for loop) represents which column is being used.
Aug 15 '08
29 13878
curiously enough
79 New Member
No one here is going to debug your code for you, you'll have to do that yourself. You can get advice here on specific problems which is pretty good for free.

You don't need a special case for dim==2. That you continue to pollute your code with this non-special case seems to indicate that you don't fully understand how do do a minor expansion.
I still find your code is too compact and variable names abstruse, and the fact you can't get it to work proves you can't see what's going on either. Code should be written for human beings, not just for computers.
If your minors and cofactors are correct, then you should have gotten the correct answer. Therefore, I don't believe they are correct.
The minors expansion for the aforementioned matrix looks like this:
Expand|Select|Wrap|Line Numbers
  1. |1 2 3 4|   
  2. |1 2 1 1|     |2 1 1|     |1 1 1|     |1 2 1|    |1 2 1|
  3. |1 1 2 1| = 1 |1 2 1| - 2 |1 2 1| + 3 |1 1 1| - 4|1 1 2|
  4. |5 6 7 8|     |6 7 8|     |5 7 8|     |5 6 8|    |5 6 7|
  5.  
Do you get these minors, with the columns in the right order and the correct cofactors and signs? Are you sure you then get the correct minors for the 3x3 matrices? Remember that swapping columns introduces minus signs.
I've run the program countless times and the minors were always perfecty correct, but the answer remained incorrect for matrices of order 4 or greater(for 3x3 matrices they are correct), and there is no column swapping in the program.
Anyway, I've simplified and explained the program here as much as possible for you, so if you can understand it finally, then tell me the problem.(by the way, this gives the same answers as before)
Here I explain with order of the code from up to down:
1.The skip_col integer array is used to know which columns are to be skipped when finding the minor matrix
2.The parameters of this function are the square matrix A, the number of rows which is changed by the recursivity, and the SIZE of the matrix which is a constant(which in this case is both the number of rows and columns since it is a square matrix)
3.det is the return value of the function
4.As you may have noticed, the funtion DET is called recursively from inside a for loop
5.this recursive funtion moves from the last row to the first row,and the for loop(the first one) is from the first column to the last column
6.everytime the function is called inside the for loop, the for loop is passed again to find all the minors of the minor of the pivot which was called which would be A[row-1][col]
7.the step if(col==0&&row= =size) is just to set the initial values of the array skip_col and the value det, it is only passed once in the entire program
8.skip_col is filled with 100's completely instead of zero's because unike 0, 100 is very unlikely to be found as a column's number
9.and det is assigned an initial value of zero
10.then, using a for loop I check if the column col is one of the columns that belong to the minor associated with the previous elements that were used in calling in the previous steps of the recursivity
11.using the integer test, which is always set to zero before this for loop, I test if this is one of the column numbers that are stored in skip_col
12.if test shows that this column does belong to skip_col, then continue is used to skip the remaining statements and check the next column col while on the same row
13.if col here is the right column, then first it is stored in skip_col. Notice that the elements of skip_col are stored in decreasing order(from row-1 to 1, skip_col[0] is never used and its value will always stay 100)
14.Then I add to the value of det the element multiplied by its minor
15.everytime DET(A,row-1,SIZE) recieves a return value the column associated with row-1(which is stored in skip_col) is set back to 100
16.in if(row==1) is the return value after which recursivity goes backward, and this is the first row of the matrix
17.then same test as before
18.if test shows that col is the column that belongs to all the minors col is taken
19.the value is returned to the phase where row was equal to 2
20.det is returned everytime the last column is passed in the first for loop and it is the final return value
Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2. #include<conio.h>
  3. #include<math.h>
  4. int skip_col[100];
  5. float DET(float A[][100],int row,int SIZE)
  6. {
  7. int col,i,test;
  8. float det;
  9.  
  10. if(row>1)
  11. for(col=0;col<SIZE;col++)
  12. {
  13.    if(col==0&&row==SIZE)
  14.    {
  15.    for(i=0;i<100;i++)
  16.        skip_col[i]=100;
  17.    det=0;
  18.    }
  19.    test=0;
  20.     for(i=SIZE-1;i>1;i--)
  21.            if(col==skip_col[i])test++;
  22.        if(test!=0)continue;
  23.     skip_col[row-1]=col;
  24.     det+=pow(-1,(row-1)+col)*A[row-1][col]*DET(A,row-1,SIZE);
  25.    skip_col[row-1]=100;
  26. }
  27.  
  28. if(row==1)
  29. {
  30.    for(col=0;col<SIZE;col++)
  31.    {
  32.    test=0;
  33.    for(i=SIZE-1;i>1;i--)
  34.            if(col==skip_col[i])test++;
  35.        if(test==0)break;
  36.    }
  37.     return(A[0][col]);
  38. }
  39.  
  40. return(det);
  41. }
  42.  
  43.  
  44. void main()
  45. {
  46. float A[100][100];
  47. int n,k,l;
  48. puts("Input size of square matrix:");
  49. scanf("%d",&n);
  50. puts("Input square matrix:");
  51. for(k=0;k<n;k++)
  52. {
  53. printf("\n");
  54. for(l=0;l<n;l++)
  55. {
  56. printf("Input a%d%d: ",k+1,l+1);
  57. scanf("%f",&A[k][l]);
  58. }
  59. }
  60. printf("\n\nThe determenant of the matrix is %0.2f",DET(A,n,n));
  61. getch();
  62. }
  63.  
Aug 18 '08 #21
curiously enough
79 New Member
Experts my ass, I knew I should have never posted here in the first place.
Aug 20 '08 #22
JosAH
11,448 Recognized Expert MVP
Experts my ass, I knew I should have never posted here in the first place.
Ok, goodbye and good luck with your code (a partial LUP decomposition would
have been much faster and easier to implement).

kind regards,

Jos
Aug 20 '08 #23
newb16
687 Contributor
Experts my ass, I knew I should have never posted here in the first place.
No one is going to debug somebody else's trivial but complex code debugging of which ( by definition ) does not reward in any way ( e.g. 'I showed off my knowlegde of language constructions! I'm cool" or "This is because this algorithm that I know works not like implemented here" etc )
Aug 20 '08 #24
curiously enough
79 New Member
No one is going to debug somebody else's trivial but complex code debugging of which ( by definition ) does not reward in any way ( e.g. 'I showed off my knowlegde of language constructions! I'm cool" or "This is because this algorithm that I know works not like implemented here" etc )
I'm not asking anyone to debug my code, post #21 made the algorithm as clear as possible, anyone can understand just by reading it, but obviously none bothered.
Aug 20 '08 #25
JosAH
11,448 Recognized Expert MVP
I'm not asking anyone to debug my code, post #21 made the algorithm as clear as possible, anyone can understand just by reading it, but obviously none bothered.
I can't speak for others but at least I didn't bother to dig through that code and
you can't force anyone to feel bothered; that code is just highly inefficient even
if it does run properly.

kind regards,

Jos
Aug 20 '08 #26
curiously enough
79 New Member
I SOLVED IT !!!!!!!!!!!!!!! !!!!!!!
IT IS 100% CORRECT!
HERE IT IS ''EXPERTS'':

Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2. #include<conio.h>
  3. #include<math.h>
  4. int skip_col[100];
  5. float DET(float A[][100],int row,int SIZE)
  6. {
  7. int col,i,test;
  8. float det=0;
  9. int minor_col=0;
  10.  
  11. if(row>1)
  12. for(col=0;col<SIZE;col++)
  13. {
  14.    if(col==0&&row==SIZE)
  15.    {
  16.    for(i=0;i<100;i++)
  17.        skip_col[i]=100;
  18.    }
  19.    test=0;
  20.     for(i=SIZE-1;i>1;i--)
  21.            if(col==skip_col[i])test++;
  22.        if(test!=0)continue;
  23.     skip_col[row-1]=col;
  24.     det+=pow(-1,(row-1)+minor_col)*A[row-1][col]*DET(A,row-1,SIZE);
  25.    minor_col++;
  26.    skip_col[row-1]=100;
  27. }
  28.  
  29. if(row==1)
  30. {
  31.     for(col=0;col<SIZE;col++)
  32.    {
  33.    test=0;
  34.    for(i=SIZE-1;i>=1;i--)
  35.            if(col==skip_col[i])test++;
  36.        if(test==0)break;
  37.    }
  38.     return(A[row-1][col]);
  39. }
  40.  
  41. return(det);
  42. }
  43.  
  44.  
  45. void main()
  46. {
  47. float A[100][100];
  48. int n,k,l;
  49. puts("Input size of square matrix:");
  50. scanf("%d",&n);
  51. puts("Input square matrix:");
  52. for(k=0;k<n;k++)
  53. {
  54. printf("\n");
  55. for(l=0;l<n;l++)
  56. {
  57. printf("Input a%d%d: ",k+1,l+1);
  58. scanf("%f",&A[k][l]);
  59. }
  60. }
  61. printf("\n\nThe determenant of the matrix is %0.2f",DET(A,n,n));
  62. getch();
  63. }
  64.  
READ IT AND MAYBE YOU'LL LEARN SOMETHING.
Aug 23 '08 #27
JosAH
11,448 Recognized Expert MVP
READ IT AND MAYBE YOU'LL LEARN SOMETHING.
Did *you* learn anything?

kind regards,

Jos (moderator)
Aug 23 '08 #28
newb16
687 Contributor
I SOLVED IT !!!!!!!!!!!!!!! !!!!!!!
IT IS 100% CORRECT!
HERE IT IS ''EXPERTS'':
Experts are not those who rush to solve trivial tasks for free.

READ IT AND MAYBE YOU'LL LEARN SOMETHING.
I learned that a human equipped with teh brain is able to write and debug teh codez on his own.
p.s. And as you wrote that minors are calculated corectly but result is wrong - the bug was exactly in calculating final sum of products of minors and coefficients.
Aug 23 '08 #29
sicarie
4,677 Recognized Expert Moderator Specialist
I SOLVED IT !!!!!!!!!!!!!!! !!!!!!!
IT IS 100% CORRECT!
HERE IT IS ''EXPERTS'':
Congratulations , and good effort.

I'd recommend three things, in the future, though:

1) use standard libraries as much as possible.

Obviously, at some point this will be impossible if you get a job as a programmer (outside of FOSS development), and you will use libraries on custom apps, but it's good practice for figuring out what is in those custom libraries to start now - looking through the libraries you have available to achieve the result you want.

On this note, I challenge you to remove conio.h from your program. I only glanced through your code, but it looks like there is only one reason you have it in there, and that functionality is easily duplicated. Conio itself is non-standard whose implementation varies by version, and can cause issues if you were to distribute a package using a different version than is what the end users have - so it's good to get in the habit of not using things that you can replicate easily without.

2) Use a standard indentation pattern

This isn't Python where indentation affects execution (or compilation), but picking one of the more standard indentations (three spaces or a tab) will make your code much, much more readable

3) Comments

Commenting code is another way to increase readability and reuse - you can easily look at the description of a module or loop, its inputs and outputs, and either modify it or use it in another program (though if it's really that useful, you can make it into its own module that can be included...
Aug 23 '08 #30

Sign in to post your reply or Sign up for a free account.

Similar topics

2
10610
by: aruna | last post by:
i want a c program to find the determinant of matrix and inverse of matrix as two separate c programs . please help me
1
3322
by: naren | last post by:
can anyone help with the code for determinant,cofactor and inverse of a matrix in c++ lang? i am not getting the logic.....
1
5657
by: avdhoot | last post by:
Hi Everybody, I am doing some project in VB6 where I ahve to calculate the Determinant of the matrix. I have got a function MDETERM but not able to pass on the parameters of the matrix and get the result. Can any body tell me how to get the result of this. I am using a 3x3 matrix. Code with example is highly appriciated......
14
7132
by: James Stroud | last post by:
Hello All, I'm using numpy to calculate determinants of matrices that look like this (13x13):
4
8097
by: krishnai888 | last post by:
I had already asked this question long back but no one has replied to me..I hope someone replies to me because its very important for me as I am doing my internship. I am currently writing a code involving lot of matrices. At one point I need to calculate the square root of a matrix e.g. A which contains non-zero off-diagonal elements. I searched for a lot of info on net but no algorithm worked. My best bet for finding square root was to find...
2
4041
by: pvsgangadhar | last post by:
I need the program in c-langauge to find the determinant of a matrix for specified no.or rows and columns.
1
4460
by: haderika | last post by:
Hey, I'm having trouble overloading the ~ operator (the determinant of the matrix) in a case of 2x2 matrices. So i have a matrix class, with the constructor, overloading +, += and ~ operators. the first two are working but I don't know how to overload the ~ one. here's what I have: matrix matrix::operator~(matrix &m) { double x; x=(m.a11*m.a22)-(m.a12*m.a21); return x; of course it's not working cause i can't return a double value...
1
14207
by: Glenton | last post by:
Hi All Here is a very simple little class for finding a shortest route on a network, following Dijkstra's Algorithm: #!/usr/bin/env python #This is meant to solve a maze with Dijkstra's algorithm from numpy import inf from copy import copy
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9481
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10336
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10155
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8978
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5383
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5513
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3655
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2881
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.