0

In python (I am new working with python), I have a matrix built inside a loop in the following way:

A[:,index_i ,index_j] = B[:,index_i ,index_j] - C[:,index_i ,index_j]

Just after that inside the same loop there are some calculations on A, but before I need to get A with each element positive for those operations, then, writing this will work so each A[k,index_i,index_j]>=0?

A[:,index_i ,index_j]= abs( B[:,index_i ,index_j] - C[:,index_i ,index_j] )

If possible, I want to avoid more loops to have every element positive.

Thank you!

ernest_k
  • 44,416
  • 5
  • 53
  • 99
FiSer
  • 27
  • 3
  • Welcome to StackOverflow! Please take the time to read this post on how to [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) as well as how to provide a [minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and revise your question accordingly – yatu Jan 15 '21 at 12:34

2 Answers2

2

Assuming these are numpy arrays, the below should work quite well:

A[:, i,j] = np.abs(B[:, i, j]- C[:,i, j])

Indeed, you can even skip the i, j loop and simply right:

A = np.abs(B-C)

to get the same outcome in a more pythonic and faster way.

supercooler8
  • 503
  • 2
  • 7
1

The builtin abs function accepts a scalar value. You can use numpy's function

import numpy as np
result = np.abs(...)
blue_note
  • 27,712
  • 9
  • 72
  • 90