1

The input array is x with dimensions (1 x 3) and the output array is 3 x 3 (column of input x column of input). The output array's diagonals are the values^2. If row != column, then the formula is x(row)+x(col) for each value. Currently for 1 x 3 but should assume a variety of dimensions as input. Cannot use 'def'. The current code does not work, what would you recommend?

x = np.array([[0, 5, 10]])
output array formulas = 
[[i^2,   x(row)+x(col),  x(row)+x(col)]
 [x(row)+x(col), i^2,    x(row)+x(col)]
 [x(row)+x(col), x(row)+x(col),   i^2]]

# where row and column refer to the output matrix row, column. For example, the value in (1,2) is x(1)+x(2)= 5

ideal output = 
[[0 5 10]
 [5 25  15]
 [10 15 100]]

Code Attempted:

x = np.array([[0, 5, 10]])
r, c = np.shape(x)
results = np.zeros((c, c))
g[range(c), range(c)] = x**2
for i in x:
    for j in i:
        results[i,j] = x[i]+x[j]
3
  • why not just something like: [n[i][j]**2 if i == j else n[i][j] for j in i for i in n]. (obviously you would have to get the actual indexes of i and j so this code is just an algorithm example. But you could use enumerate()) Commented Jan 19, 2022 at 16:48
  • @EliHarold, I tried that but getting error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). Can you show an example with the given x array? Commented Jan 19, 2022 at 16:50
  • 1
    see my answer, I coded what I mentioned. Commented Jan 19, 2022 at 17:00

2 Answers 2

1

Learn to use numpy methods and broadcasting:

>>> x
array([[ 0,  5, 10]])
>>> x.T
array([[ 0],
       [ 5],
       [10]])
>>> x.T + x
array([[ 0,  5, 10],
       [ 5, 10, 15],
       [10, 15, 20]])
>>> result = x.T + x
>>> result
array([[ 0,  5, 10],
       [ 5, 10, 15],
       [10, 15, 20]])

Then this handy built-in:

>>> np.fill_diagonal(result, x**2)
>>> result
array([[  0,   5,  10],
       [  5,  25,  15],
       [ 10,  15, 100]])

Can replace the results[range(c), range(c)] = x**2

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

x.repeat(x.shape[1], axis=0)
x = x+x.T
x[np.arange(len(x)),np.arange(len(x))] = (np.diag(x)/2)**2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.