473,770 Members | 4,999 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 #1
29 13873
arnaudk
424 Contributor
As noted in a recent thread, finding the determinant by a minors expansion is very slow (O(n!) for an nxn matrix), there are much better methods like the finding the LU decomposition which is O(n^3). Also, there are a number of libraries which can do all this for you, such as GSL.
Aug 15 '08 #2
curiously enough
79 New Member
As noted in a recent thread, finding the determinant by a minors expansion is very slow (O(n!) for an nxn matrix), there are much better methods like the finding the LU decomposition which is O(n^3). Also, there are a number of libraries which can do all this for you, such as GSL.
I know there are other methods , but I want to use this one, so please read the program and try it and maybe you'll know what's wrong with it.
Aug 15 '08 #3
arnaudk
424 Contributor
What kind of problems are you having with your code? Does it compile? Does it give you the wrong answer?
Aug 15 '08 #4
curiously enough
79 New Member
What kind of problems are you having with your code? Does it compile? Does it give you the wrong answer?
it compiles,but It gives the wrong answer for square matrices of order greater than or equal to 4
Aug 15 '08 #5
arnaudk
424 Contributor
Since there is probably an arithmetic error in your code, why not get the function DET to print out the matrix that it is given in a nice tabular form, as well as the cofactor so that you can check that everything is working as expected and you are getting the correct cofactor and associated minor?

Some general suggestions:
  • The return type of main is int, not void.
  • Use more intuitive variable names, if i represents a column, call it col.
  • Use brief comments to explain what's going on if you ever want anyone else to lay eyes on your code.
  • Scrunching up code like if(i==0&&DIM==d im)for(j=0;j<10 0;j++)M[j]=100; makes it hard to read.
  • Use const wherever you don't expect a variable to be changed, this is to prevent accidentally changing it and to enable some compiler optimizations: float DET(const float A[100][100], const int dim)
  • Using static variables in a recursively called function is arcane. Rather than using static variables, why not pass the variables to each new function call, in this case, pass det and DIM as arguments to the function DET(), the first call to DET will be called with arguments det=0 and DIM=dim.
  • You don't need a special case for dim==2; you can do a cofactor expansion on a 2x2 matrix as well, the minors in this case are just rank 1 matrices (i.e. numbers).
Aug 15 '08 #6
newb16
687 Contributor
Why is det int while A is float?
Aug 15 '08 #7
curiously enough
79 New Member
Since there is probably an arithmetic error in your code, why not get the function DET to print out the matrix that it is given in a nice tabular form, as well as the cofactor so that you can check that everything is working as expected and you are getting the correct cofactor and associated minor?

Some general suggestions:
  • The return type of main is int, not void.
  • Use more intuitive variable names, if i represents a column, call it col.
  • Use brief comments to explain what's going on if you ever want anyone else to lay eyes on your code.
  • Scrunching up code like if(i==0&&DIM==d im)for(j=0;j<10 0;j++)M[j]=100; makes it hard to read.
  • Use const wherever you don't expect a variable to be changed, this is to prevent accidentally changing it and to enable some compiler optimizations: float DET(const float A[100][100], const int dim)
  • Using static variables in a recursively called function is arcane. Rather than using static variables, why not pass the variables to each new function call, in this case, pass det and DIM as arguments to the function DET(), the first call to DET will be called with arguments det=0 and DIM=dim.
  • You don't need a special case for dim==2; you can do a cofactor expansion on a 2x2 matrix as well, the minors in this case are just rank 1 matrices (i.e. numbers).
Thanks for your first advice, I printed all the minors like you said but still can't figure out what's wrong, and sorry if the randomly chosen variable names cuased you a headache, so if there is something unclear to you I will clear it up. Here's the program:
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,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.     for(j=DIM-1;j>=2;j--)
  15.     if(M[j]==i)continue;
  16.        /*here printing starts*/
  17.                   for(k=0;k<dim;k++)
  18.                   {
  19.                printf("\n");
  20.                   for(j=0;j<DIM;j++)
  21.         {
  22.         m=0;
  23.         for(l=DIM-1;l>=dim;l--)
  24.         if(j!=M[l])m++;
  25.         if(m==DIM-dim)printf("%0.0f   ",A[k][j]);
  26.         }
  27.                            }
  28.                   printf("\n\n");
  29.                 /*here printing ends*/
  30.     M[dim-1]=i;
  31.     det+=pow(-1,i+dim-1)*A[dim-1][i]*DET(A,dim-1);
  32.     }
  33.     if(i==DIM-1)M[dim-1]=100;
  34. if(dim==2)
  35.  {
  36.       /*here printing starts*/
  37.        for(k=0;k<dim;k++)
  38.        {
  39.                     printf("\n");
  40.                        for(j=0;j<DIM;j++)
  41.         {
  42.         m=0;
  43.         for(l=DIM-1;l>=dim;l--)
  44.         if(j!=M[l])m++;
  45.         if(m==DIM-dim)printf("%0.0f   ",A[k][j]);
  46.         }
  47.                }
  48.                printf("\n\n");
  49.       /*here printing ends*/
  50.     for(i=0;i<DIM;i++)
  51.     {
  52.     k=0;
  53.       for(j=DIM-1;j>=2;j--)
  54.     if(i!=M[j])k++;
  55.     if(k==DIM-2)break;
  56.     }
  57.     for(j=0;j<DIM;j++)
  58.     {
  59.     k=0;
  60.     for(l=DIM-1;l>=2;l--)
  61.     if(j!=M[l])k++;
  62.     if(k==DIM-2&&j!=i)break;
  63.     }
  64.     return(A[0][i]*A[1][j]-A[0][j]*A[1][i]);
  65.  }
  66. if(dim==1)return(A[0][0]);
  67. return(det);
  68. }
  69.  
  70.  
  71. void main()
  72. {
  73. float A[100][100];
  74. int n,k,l;
  75. puts("Input size of square matrix:");
  76. scanf("%d",&n);
  77. puts("Input square matrix:");
  78. for(k=0;k<n;k++)
  79. {
  80. printf("\n");
  81. for(l=0;l<n;l++)
  82. {
  83. printf("Input a%d%d: ",k+1,l+1);
  84. scanf("%f",&A[k][l]);
  85. }
  86. }
  87. printf("\n\nThe determenant of the matrix is %0.2f",DET(A,n));
  88. getch();
  89. }
  90.  
Aug 15 '08 #8
arnaudk
424 Contributor
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.
Aug 15 '08 #9
JosAH
11,448 Recognized Expert MVP
So... were the minors displayed were 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.
Yup correct (using my LUP function) ;-)

kind regards,

Jos
Aug 15 '08 #10

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
5656
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
7130
by: James Stroud | last post by:
Hello All, I'm using numpy to calculate determinants of matrices that look like this (13x13):
4
8096
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
14206
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
9592
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
9425
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
10231
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
10059
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
10005
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
9871
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8887
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
7416
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
5452
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.