| Ver tema anterior :: Ver siguiente tema | | Autor | Mensaje |
|---|
wirr9
Registrado: 16 Jun 2006 Mensajes: 2
| Publicado: 17/06/2006 6:31 am | | | Título: determinante de una matriz m*n |
| alguien me puede ayudar con el algoritmo para sacar determinates de una matreiz, porfavor enviarlo a gracias  |
| | Volver arriba | |  | Killrazor
Registrado: 24 Ene 2006 Mensajes: 1267 Ubicación: Barcelona
| Publicado: 17/06/2006 6:32 pm | | | Título: |
| Hola, que tal si en vez de enviartelo lo compartimos todos?
| Código: | //============================================================================== // Recursive definition of determinate using expansion by minors. // // Notes: 1) arguments: // a (double **) pointer to a pointer of an arbitrary square matrix // n (int) dimension of the square matrix // // 2) Determinant is a recursive function, calling itself repeatedly // each time with a sub-matrix of the original till a terminal // 2X2 matrix is achieved and a simple determinat can be computed. // As the recursion works backwards, cumulative determinants are // found till untimately, the final determinate is returned to the // initial function caller. // // 3) m is a matrix (4X4 in example) and m13 is a minor of it. // A minor of m is a 3X3 in which a row and column of values // had been excluded. Another minor of the submartix is also // possible etc. // m a b c d m13 . . . . // e f g h e f . h row 1 column 3 is elminated // i j k l i j . l creating a 3 X 3 sub martix // m n o p m n . p // // 4) the following function finds the determinant of a matrix // by recursively minor-ing a row and column, each time reducing // the sub-matrix by one row/column. When a 2X2 matrix is // obtained, the determinat is a simple calculation and the // process of unstacking previous recursive calls begins. // // m n // o p determinant = m*p - n*o // // 5) this function uses dynamic memory allocation on each call to // build a m X m matrix this requires ** and * pointer variables // First memory allocation is ** and gets space for a list of other // pointers filled in by the second call to malloc. // // 6) C++ implements two dimensional arrays as an array of arrays // thus two dynamic malloc's are needed and have corresponsing // free() calles. // // 7) the final determinant value is the sum of sub determinants // //==============================================================================
double Determinant(double **a,int n) { int i,j,j1,j2 ; // general loop and matrix subscripts double det = 0 ; // init determinant double **m = NULL ; // pointer to pointers to implement 2d // square array
if (n < 1) { } // error condition, should never get here
else if (n == 1) { // should not get here det = a[0][0] ; }
else if (n == 2) { // basic 2X2 sub-matrix determinate // definition. When n==2, this ends the det = a[0][0] * a[1][1] - a[1][0] * a[0][1] ;// the recursion series }
// recursion continues, solve next sub-matrix else { // solve the next minor by building a // sub matrix det = 0 ; // initialize determinant of sub-matrix
// for each column in sub-matrix for (j1 = 0 ; j1 < n ; j1++) { // get space for the pointer list m = (double **) malloc((n-1)* sizeof(double *)) ;
for (i = 0 ; i < n-1 ; i++) m[i] = (double *) malloc((n-1)* sizeof(double)) ; // i[0][1][2][3] first malloc // m -> + + + + space for 4 pointers // | | | | j second malloc // | | | +-> _ _ _ [0] pointers to // | | +----> _ _ _ [1] and memory for // | +-------> _ a _ [2] 4 doubles // +----------> _ _ _ [3] // // a[1][2] // build sub-matrix with minor elements excluded for (i = 1 ; i < n ; i++) { j2 = 0 ; // start at first sum-matrix column position // loop to copy source matrix less one column for (j = 0 ; j < n ; j++) { if (j == j1) continue ; // don't copy the minor column element
m[i-1][j2] = a[i][j] ; // copy source element into new sub-matrix // i-1 because new sub-matrix is one row // (and column) smaller with excluded minors j2++ ; // move to next sub-matrix column position } }
det += pow(-1.0,1.0 + j1 + 1.0) * a[0][j1] * Determinant(m,n-1) ; // sum x raised to y power // recursively get determinant of next // sub-matrix which is now one // row & column smaller
for (i = 0 ; i < n-1 ; i++) free(m[i]) ;// free the storage allocated to // to this minor's set of pointers free(m) ; // free the storage for the original // pointer to pointer } } return(det) ; }
|
Extraido de |
| | Volver arriba | |  | wirr9
Registrado: 16 Jun 2006 Mensajes: 2
| Publicado: 28/06/2006 10:23 am | | | Título: Re: determinante de una matriz m*n |
| | MUCHAS GRACIAS POR TU APOYO KILLRAZOR |
| | Volver arriba | |  | | holylance
Registrado: 03 Ene 2006 Mensajes: 114 Ubicación: Argentina
| Publicado: 26/07/2006 3:24 pm | | | Título: |
| groso el codigo, tambien puede tratar de triangular la matriz con gauss y despues calcular la productoria de los elementos de la diagonal, y devolver cero en otro caso...el problema es que si la matriz no es muy "feliz", puede llegar a tirar cualquier cosa mi sugerencia. _________________ si me equivoqué en algo respondan o manden privados |
| | Volver arriba | |  | tonilope
Registrado: 16 Oct 2005 Mensajes: 255
| Publicado: 28/08/2006 12:34 pm | | | Título: Éste es mio: |
| | Código: | /* CALCULADOR de DETERMINANTES de orden n Autor: Antonio López Vivar Fecha: 1 de diciembre de 2003 Revisión: final 1.0 */
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <conio.h>
//Prototipos float Determinante (float **, int); void Adjunta (float **, float **, int, int); //Principal void main() { int n, i, f, c; float **matriz; char comando; for(i=0; i<3; i++) { printf("\n\n\tBienvenido al CaLcuLaDOR de DeTERminanTes de orden n marca MIKASA"); sleep(500); system("cls"); printf("\n\n\tBienvenido al CaLcuLaDOR de DeTERminanTes de orden n marca MIKASA"); printf("\n\n\n\n\n\n\n\t\t\tUna utilidad de Antonio Lopez Vivar"); sleep(500); system("cls"); } do{ do{ system("cls"); printf("\n\n\tNota--> Este programa utiliza una funcion recursiva. Abstenerse de introducir matrices de orden elevado (mayor de 10), puesto que el consumo de RAM puede ser bestial"); printf("\n\n\tORDEN?>\t"); scanf("%d", &n); }while(n<1); //Petición de memoria dinámica para la matriz matriz=(float**)calloc(n, sizeof(float*)); if(matriz==NULL) printf("ERROR, FALTA MEMORIA PARA LA MATRIZ. Introduzca un orden MUCHO mas pequeño"); else { for(i=0; i<n; i++) matriz[i]=(float*)calloc(n, sizeof(float)); //Lectura por teclado de la matriz for(f=0; f<n; f++) for(c=0; c<n; c++) {printf("\nIntroduce el elemento %d de la fila %d --->\t", c+1, f+1); scanf("%f", &matriz[f][c]); } //Se muestra la matriz al usuario system("cls"); printf("\n\n\n"); for(f=0; f<n; f++) { printf("\t\t"); for(c=0; c<n; c++) printf("%12.1f ", matriz[f][c]); printf("\n"); } printf("\n\n\n\t\tCalculando el determinante, por favor espere...\n\t\t(Para abortar el calculo pulse CTRL+C)\n"); printf("\n\n\n\n\n\t\t\tEl determinante es:"); printf("\n\n\n\t\t\t\t%.1f\n\n\n\n\n\t\t", Determinante(matriz, n)); //Se libera la memoria solicitada free(matriz); } printf("Pulsa INTRO para calcular OTRO determinante, o pulsa S para SALIR"); fflush(stdin); comando=getch(); }while(comando!='s' && comando!='S');
}
/* Esta función recursiva se encarga del cálculo del determinante propiamente dicho. Recibe: - La matriz (referencia). - Orden de la matriz (valor).
Devuelve: - El determinante (valor). */
float Determinante (float **mat, int orden) { float det; int h; float **auxiliar; //Caso básico if(orden<=2) { if(orden==2) det=mat[0][0]*mat[1][1]-(mat[1][0]*mat[0][1]); else det=mat[0][0]; } //Se calculan n determinantes de orden "n-1". else { //Petición de memoria dinámica para la matriz auxiliar auxiliar=(float**)calloc(orden-1, sizeof(float*)); for(h=0; h<orden-1; h++) auxiliar[h]=(float*)calloc(orden-1, sizeof(float)); //Se usa un acumulador para ir sumando los determinantes de orden n-1 det=0; for(h=0; h<orden; h++) { Adjunta(mat, auxiliar, orden, h); det+=pow(-1, h)*mat[h][0]*Determinante(auxiliar, orden-1); } //Se libera la memoria auxiliar solicitada free(auxiliar); } return(det); }
/* Esta función se encarga de calcular la matriz resultante de tachar la primera columna y alguna de las n filas de la matriz inicial. Recibe: - La matriz inicial (referencia). - El orden de la matriz inicial(valor). - La fila que hay que tachar de la matriz inicial (valor).
Devuelve: - La matriz auxiliar que se usará para calcular los determinates de orden n-1 (referencia). */ void Adjunta (float **mat, float **aux, int orden, int pos) { int fila, columna, j, i; for(j=0, fila=0; fila<orden-1; j++, fila++) { if(j==pos) fila--; else for(i=1, columna=0; columna<orden-1; i++, columna++) aux[fila][columna]=mat[j][i]; } }
|
Salu2  |
| | Volver arriba | |  | Segurilink
Registrado: 09 Ago 2006 Mensajes: 6
| Publicado: 28/09/2006 1:22 pm | | | Título: Hola |
| | quisiera saber el mismo ejemplo pero si es posible hacerlo sin punteros. |
| | Volver arriba | |  | | Killrazor
Registrado: 24 Ene 2006 Mensajes: 1267 Ubicación: Barcelona
| Publicado: 29/09/2006 12:43 am | | | Título: |
| | Sin punteros donde? Es decir, sin punteros para definir la matriz, entonces necestias una matriz de un tamaño determinado. Sin punteros en las funciones, entonces todo parametro es con copia.... |
| | Volver arriba | |  | gui2485_kawakx
Registrado: 22 Ene 2006 Mensajes: 59 Ubicación: Korn, Bs As, Argentina.
| Publicado: 10/10/2006 6:09 pm | | | Título: |
| Matematicamente no esta definido el determinante de una matriz que no es cuadrada....  _________________
Guillermo I'll Love Her, I Need Her, I Seed Her... She Is A Killing Maching |
| | Volver arriba | |  | | |
| No puede crear mensajes No puede responder temas No puede editar sus mensajes No puede borrar sus mensajes No puede votar en encuestas
|
|
| |