473,785 Members | 2,841 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 13877
arnaudk
424 Contributor
Yup correct (using my LUP function) ;-)
Phew! I usually prefer to work in special units where 1 = -1 = 2 = 1/2. In those units I never have to hunt down minus signs or factors of 2 and my answers are always correct. :-)
Aug 15 '08 #11
JosAH
11,448 Recognized Expert MVP
Phew! I usually prefer to work in special units where 1 = -1 = 2 = 1/2. In those units I never have to hunt down minus signs or factors of 2 and my answers are always correct. :-)
Well, my LUP implementation isn't the most efficient one when it comes to pivot
selection but then again it has to deal with symbolics as well and it does a fine
job when it comes to that e.g.

Expand|Select|Wrap|Line Numbers
  1. | a b |
  2. | c d | = a*d-b*c
  3.  
It can do any larger dimensions as well ;-)

kind regards,

Jos
Aug 15 '08 #12
curiously enough
79 New Member
So... were the minors displayed correct or not? For example, run your program on this invertible matrix and check the minors and cofactors are correct and have the right sign
Expand|Select|Wrap|Line Numbers
  1. .
  2.    (1 2 3 4)
  3. det(1 2 1 1) = -12
  4.    (1 1 2 1)
  5.    (5 6 7 8)
  6.  
and [code]...[/code] tags are good. Please use them.

OK, now I've perfected the program, and all the minors are displayed correctly, but It still gives the wrong answer, and I'm still trying to find out what's wrong.
here's the program, test it on C++(V5.02) if you have it:
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,j,k,l,m;
  8. static float 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.     m=0;
  15.     for(j=DIM-1;j>=2;j--)
  16.     if(M[j]==i)m++;
  17.     if(m!=0)continue;
  18.        /*here printing starts*/
  19.        for(k=0;k<dim;k++)
  20.        {
  21.     printf("\n");
  22.        for(j=0;j<DIM;j++)
  23.         {
  24.         m=0;
  25.         for(l=DIM-1;l>=2;l--)
  26.         if(j!=M[l])m++;
  27.         if(m==DIM-2)printf("%0.0f   ",A[k][j]);
  28.         }
  29.     }
  30.        printf("\n\n");
  31.     /*here printing ends*/
  32.     M[dim-1]=i;
  33.     det+=pow(-1,i+dim-1)*A[dim-1][i]*DET(A,dim-1);
  34.     M[dim-1]=100;
  35.     }
  36. if(dim==2)
  37.  {
  38.     /*here printing starts*/
  39.        for(k=0;k<dim;k++)
  40.        {
  41.     printf("\n");
  42.            for(j=0;j<DIM;j++)
  43.         {
  44.         m=0;
  45.         for(l=DIM-1;l>=2;l--)
  46.         if(j!=M[l])m++;
  47.         if(m==DIM-2)printf("%0.0f   ",A[k][j]);
  48.         }
  49.     }
  50.        printf("\n\n");
  51.     /*here printing ends*/
  52.     for(i=0;i<DIM;i++)
  53.     {
  54.     k=0;
  55.       for(j=DIM-1;j>=2;j--)
  56.     if(i!=M[j])k++;
  57.     if(k==DIM-2)break;
  58.     }
  59.     for(j=0;j<DIM;j++)
  60.     {
  61.     k=0;
  62.     for(l=DIM-1;l>=2;l--)
  63.     if(j!=M[l])k++;
  64.     if(k==DIM-2&&j!=i)break;
  65.     }
  66.     return(A[0][i]*A[1][j]-A[0][j]*A[1][i]);
  67.  }
  68. if(dim==1)return(A[0][0]);
  69. return(det);
  70. }
  71.  
  72.  
  73. void main()
  74. {
  75. float A[100][100];
  76. int n,k,l;
  77. puts("Input size of square matrix:");
  78. scanf("%d",&n);
  79. puts("Input square matrix:");
  80. for(k=0;k<n;k++)
  81. {
  82. printf("\n");
  83. for(l=0;l<n;l++)
  84. {
  85. printf("Input a%d%d: ",k+1,l+1);
  86. scanf("%f",&A[k][l]);
  87. }
  88. }
  89. printf("\n\nThe determenant of the matrix is %0.2f",DET(A,n));
  90. getch();
  91. }
  92.  
I just have one question:
When I write
det+=pow(-1,i+dim-1)*A[dim-1][i]*DET(A,dim-1); where the return value of the DET(A,dim-1) function is det, is the value added to det just (sign)*A[dim-1][i] multiplied by the determinant of its minor?
P.S: I tried your matrix, and got -8550.
Aug 17 '08 #13
JosAH
11,448 Recognized Expert MVP
When I write
det+=pow(-1,i+dim-1)*A[dim-1][i]*DET(A,dim-1); where the return value of the DET(A,dim-1) function is det, is the value added to det just (sign)*A[dim-1][i] multiplied by the determinant of its minor?
When you write X+= Y then the entire expression Y is evaluated and its value
is added to X for whatever the values of X and Y here the new value of X is
Y larger than it was before.

kind regards,

Jos

ps. you definitely should use other variable names and use a proper indentation
and spaces to make your code more readable.
Aug 17 '08 #14
curiously enough
79 New Member
When you write X+= Y then the entire expression Y is evaluated and its value
is added to X for whatever the values of X and Y here the new value of X is
Y larger than it was before.

kind regards,

Jos

ps. you definitely should use other variable names and use a proper indentation
and spaces to make your code more readable.
You didn't understand what I meant.
When I add to the value of the det static variable a return value which is that very same static variable(which is happening in the function as long as dim-1 is not equal to 2), will it add itself twice? Or will it just add the return value associated with the dim-1 part of the recursivity to the initial value of det in the part of the recursivity where I made the statement det+=pow(-1,i+dim-1)*A[dim-1][i]*DET(A,dim-1); ?
Aug 17 '08 #15
JosAH
11,448 Recognized Expert MVP
You didn't understand what I meant.
When I add to the value of the det static variable a return value which is that very same static variable(which is happening in the function as long as dim-1 is not equal to 2), will it add itself twice? Or will it just add the return value associated with the dim-1 part of the recursivity to the initial value of det in the part of the recursivity where I made the statement det+=pow(-1,i+dim-1)*A[dim-1][i]*DET(A,dim-1); ?
If the DET method in that last assignment expression also changes static variable
det then the entire thing causes undefined behaviour; you are changing the value
of an LHV (here: det) more than once before a sequence point is reached.
Anything can happen here.

kind regards,

Jos
Aug 17 '08 #16
arnaudk
424 Contributor
curiously enough, you're really making your life difficult by insisting on having those static variables. :-) Why don't you take heed of the comments in post #6?
Aug 17 '08 #17
curiously enough
79 New Member
curiously enough, you're really making your life difficult by insisting on having those static variables. :-) Why don't you take heed of the comments in post #6?
I'm writing this so you don't find the program arcane anymore,PLEASE try to read it, cause it still gives the wrong answer for DIM greater than 3
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,int DIM,float det)
  6. {
  7. int i=100,j,k,l;
  8. if(dim>2)
  9.     for(i=0;i<DIM;i++)
  10.     {
  11.     if(i==0&&DIM==dim)
  12.     for(j=0;j<100;j++)M[j]=100;
  13.     for(j=DIM-1;j>=2;j--)
  14.     if(M[j]==i)continue;
  15.     M[dim-1]=i;
  16.     det+=pow(-1,i+dim-1)*A[dim-1][i]*DET(A,dim-1,DIM,det);
  17.     }
  18.     if(i==DIM-1)M[dim-1]=100;
  19. if(dim==2)
  20.       {
  21.     for(i=0;i<DIM;i++)
  22.     {
  23.     k=0;
  24.     for(j=DIM-1;j>=2;j--)
  25.     if(i!=M[j])k++;
  26.     if(k==DIM-2)break;
  27.     }
  28.     for(j=0;j<DIM;j++)
  29.     {
  30.     k=0;
  31.     for(l=DIM-1;l>=2;l--)
  32.     if(j!=M[l])k++;
  33.     if(k==DIM-2&&j!=i)break;
  34.     }
  35.     return(A[0][i]*A[1][j]-A[0][j]*A[1][i]);
  36.       }
  37. if(dim==1)return(A[0][0]);
  38. return(det);
  39. }
  40.  
  41.  
  42. void main()
  43. {
  44. float A[100][100];
  45. int n,k,l;
  46. puts("Input size of square matrix:");
  47. scanf("%d",&n);
  48. puts("Input square matrix:");
  49. for(k=0;k<n;k++)
  50. {
  51. printf("\n");
  52. for(l=0;l<n;l++)
  53. {
  54. printf("Input a%d%d: ",k+1,l+1);
  55. scanf("%f",&A[k][l]);
  56. }
  57. }
  58. printf("\n\nThe determenant of the matrix is %0.2f",DET(A,n,n,0));
  59. getch();
  60. }
  61.  
Aug 18 '08 #18
newb16
687 Contributor
Expand|Select|Wrap|Line Numbers
  1.     if(i==0&&DIM==dim)
  2.     for(j=0;j<100;j++)M[j]=100;
  3.     for(j=DIM-1;j>=2;j--)
  4.     if(M[j]==i)continue;
  5.     M[dim-1]=i;
  6.  
This is still arcane.
Expand|Select|Wrap|Line Numbers
  1.     if(i==0&&DIM==dim)
  2.        for(j=0;j<100;j++)
  3.            M[j]=100;
  4.     for(j=DIM-1;j>=2;j--)
  5.         if(M[j]==i)continue;
  6.     M[dim-1]=i;
  7.  
This is less so.
Aug 18 '08 #19
arnaudk
424 Contributor
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.
Aug 18 '08 #20

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
9480
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
10153
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...
1
10093
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8976
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...
1
7500
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6740
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3654
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2880
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.