the matlab code and the output i was expecting (gauss elimination method)
my code in python:
JavaScript
x
23
23
1
import numpy as np
2
3
4
A = np.array([
5
[1,2,-1,1],
6
[-1,4,3,1],
7
[2,1,1,1]])
8
9
n = rows = len(A)
10
col = len(A[0])
11
12
13
for i in range(n):
14
A[i,:] = A[i,:] / A[i,i]
15
for j in range(n):
16
if i==j:
17
pass
18
else:
19
A[j,:] = A[j,:] - (A[i,:] * A[j,i])
20
21
22
print(A)
23
the output i got:
JavaScript
1
4
1
[[1 0 0 1]
2
[0 1 0 0]
3
[0 0 1 0]]
4
Advertisement
Answer
Your problem is related to casting. Without info, numpy
cast your matrix to integer numbers, so when you divide, the result is not a float. For example 2 / 6 = 0
and not 0.33333
.
If you put
JavaScript
1
5
1
A = np.array([
2
[1,2,-1,1],
3
[-1,4,3,1],
4
[2,1,1,1]], dtype=float)
5
your result will be
JavaScript
1
4
1
[[1. 0. 0. 0.33333333]
2
[0. 1. 0. 0.33333333]
3
[0. 0. 1. 0.]]
4
In matlab there is not this problem because your starting matrix is already casted to floating point numbers.