0

I wrote a function that is supposed to horizontally stack a matrix and a vector, using hstack() method in numpy. But when I import it in another python file it is not doing what it is supposed to. Here is the function and where it is used:

I have tried directly write the code without the function and it worked. The problem is occuring when I try to call it as a function.

def augmented_matrix(A, b):
    A = np.hstack((A, b))
    return A

A = np.array([[2., 2., 3., 4., 6.],
              [3., 0., 3., 1., 11.],
              [2., 4., 0., 2., 5.],
              [5., 2., 12., 0., 6.],
              [6., 4., 1., 5., 8.]])

b = np.array([[1.], [2.], [4.], [6.], [8.]])

augmented_matrix(A, b)

It still gives the result:

[[ 2.  2.  3.  4.  6.]
[ 3.  0.  3.  1. 11.]
[ 2.  4.  0.  2.  5.]
[ 5.  2. 12.  0.  6.]
[ 6.  4.  1.  5.  8.]]

I expect the 5x6 matrix:

[[ 2.  2.  3.  4.  6.  1.]
 [ 3.  0.  3.  1. 11.  2.]
 [ 2.  4.  0.  2.  5.  4.]
 [ 5.  2. 12.  0.  6.  6.]
 [ 6.  4.  1.  5.  8.  8.]]
  • 1
    I just pasted your code in my editor and it produces the 5x6 matrix. What do you mean by importing the function? That you use `augmented_matrix` in another file? – Jeppe Feb 16 '19 at 19:39
  • 1
    I cannot reproduce your problem. Maybe the error is in part of your code that you did not show? – Bernhard Feb 16 '19 at 19:39
  • Are the two files inside a python package, i.e. are the two files inside a directory which contains blank `__init__.py` ? – Paandittya Feb 16 '19 at 19:41
  • 4
    do you mean `A = augmented_matrix(A, b)`? because the function is not changing `A` – user2314737 Feb 16 '19 at 19:47
  • does not the definition of the augmented_matrix(A, b) function say that the A matrix is changing? I mean it is defined as A = np.hstack((A, b)) so A has been revised. @user2314737 – Ercüment Kalkan Feb 16 '19 at 21:28
  • I want to use the augmented_matrix() function in another py file by importing the file that contains augmented_matrix(). But that's not the case here i think. I think it is about revising the A matrix in the function definition as mentioned before. @Jeppe – Ercüment Kalkan Feb 16 '19 at 21:33
  • @ErcümentKalkan AFAIK python passes by value, so the reference is copied - but `A = ...` is changing the the copied reference. If you could do `A.update(...)` or alike, it might be possible. – Jeppe Feb 16 '19 at 21:45
  • You might find this useful to understand the subtleties of local variables: [Why can a function modify some arguments as perceived by the caller, but not others?](https://stackoverflow.com/questions/575196/why-can-a-function-modify-some-arguments-as-perceived-by-the-caller-but-not-oth) – user2314737 Feb 16 '19 at 21:56

0 Answers0