[Tutor] Loops and matrices'
Peter Otten
__peter__ at web.de
Tue Aug 30 08:27:14 CEST 2011
Reed DA (Danny) at Aera wrote:
> I have a matrix which contains temperatures. The columns are time, spaced
> 33 seconds apart, and the rows are depth intervals. What I'm trying to do
> is create another matrix that contains the rate of change of temperature
> for each depth. The array is called LS_JULY_11 and the output array should
> be delta_temp
I think you don't need any explicit for-loops:
>>> import numpy as np
>>> july = np.random.randint(0, 100, (3, 4))
>>> july
array([[27, 43, 67, 12],
[52, 22, 54, 26],
[70, 81, 61, 49]])
>>> dt = 33.0
>>> july[1:]
array([[52, 22, 54, 26],
[70, 81, 61, 49]])
>>> july[:-1]
array([[27, 43, 67, 12],
[52, 22, 54, 26]])
>>> (july[1:]-july[:-1])
array([[ 25, -21, -13, 14],
[ 18, 59, 7, 23]])
>>> (july[1:]-july[:-1])/dt
array([[ 0.75757576, -0.63636364, -0.39393939, 0.42424242],
[ 0.54545455, 1.78787879, 0.21212121, 0.6969697 ]])
If rows and columns are swapped in the above, just transpose the matrix
before you start and again when you're done:
>>> july = july.transpose()
>>> july
array([[27, 52, 70],
[43, 22, 81],
[67, 54, 61],
[12, 26, 49]])
>>> ((july[1:]-july[:-1])/dt).transpose()
array([[ 0.48484848, 0.72727273, -1.66666667],
[-0.90909091, 0.96969697, -0.84848485],
[ 0.33333333, -0.60606061, -0.36363636]])
More information about the Tutor
mailing list