Graphviz 14.1.3~dev.20260124.0732
Loading...
Searching...
No Matches
matinv.c
Go to the documentation of this file.
1/*************************************************************************
2 * Copyright (c) 2011 AT&T Intellectual Property
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * https://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors: Details at https://graphviz.org
9 *************************************************************************/
10
11/*
12 * This code was (mostly) written by Ken Turkowski, who said:
13 *
14 * Oh, that. I wrote it in college the first time. It's open source - I think I
15 * posted it after seeing so many people solve equations by inverting matrices
16 * by computing minors naïvely.
17 * -Ken
18 *
19 * The views represented here are mine and are not necessarily shared by
20 * my employer.
21 Ken Turkowski turk@apple.com
22 Immersive Media Technologist http://www.worldserver.com/turk/
23 Apple Computer, Inc.
24 1 Infinite Loop, MS 302-3VR
25 Cupertino, CA 95014
26 */
27
28/* Matinv() inverts the matrix A using LU decomposition. Arguments:
29 * A - the (n x n) matrix to be inverted
30 * Ainv - the (n x n) inverted matrix
31 * n - the order of the matrices A and Ainv
32 */
33
34#include "config.h"
35
36#include <stdlib.h>
37#include <common/render.h>
38#include <neatogen/neato.h>
39#include <util/alloc.h>
40#include <util/gv_math.h>
41
42int matinv(double **A, double **Ainv, int n)
43{
44 int i, j;
45
46 /* Decompose matrix into L and U triangular matrices */
47 if (lu_decompose(A, n) == 0)
48 return (0); /* Singular */
49
50 /* Invert matrix by solving n simultaneous equations n times */
51 double *b = gv_calloc(n, sizeof(double));
52 for (i = 0; i < n; i++) {
53 for (j = 0; j < n; j++)
54 b[j] = 0.0;
55 b[i] = 1.0;
56 lu_solve(Ainv[i], b, n); /* Into a row of Ainv: fix later */
57 }
58 free(b);
59
60 /* Transpose matrix */
61 for (i = 0; i < n; i++) {
62 for (j = 0; j < i; j++) {
63 SWAP(&Ainv[i][j], &Ainv[j][i]);
64 }
65 }
66
67 return (1);
68}
Memory allocation wrappers that exit on failure.
static void * gv_calloc(size_t nmemb, size_t size)
Definition alloc.h:26
#define A(n, t)
Definition expr.h:76
void free(void *)
Arithmetic helper functions.
#define SWAP(a, b)
Definition gv_math.h:134
void lu_solve(double *x, double *b, int n)
Definition lu.c:137
int lu_decompose(double **a, int n)
Definition lu.c:67
int matinv(double **A, double **Ainv, int n)
Definition matinv.c:42