boltz
boltz

Reputation: 75

Repmat operation in python

I want to calculate the mean of a 3D array along two axes and subtract this mean from the array. In Matlab I use the repmat function to achieve this as follows

% A is an array of size 100x50x100
mean_A = mean(mean(A,3),1);                % mean_A is 1D of length 50
Am = repmat(mean_A,[100,1,100])            % Am is 3D 100x50x100
flc_A = A - Am                             % flc_A is 3D 100x50x100

Now, I am trying to do the same with python.

mean_A = numpy.mean(numpy.mean(A,axis=2),axis=0);

gives me the 1D array. However, I cannot find a way to copy this to form a 3D array using numpy.tile(). Am I missing something or is there another way to do this in python?

Upvotes: 0

Views: 1678

Answers (2)

Sheldon
Sheldon

Reputation: 193

numpy.tile is not the same with Matlab repmat. You could refer to this question. However, there is an easy way to repeat the work you have done in Matlab. And you don't really have to understand how numpy.tile works in Python.

import numpy as np
A = np.random.rand(100, 50, 100)
# keep the dims of the array when calculating mean values
B = np.mean(A, axis=2, keepdims=True)
C = np.mean(B, axis=0, keepdims=True) # now the shape of C is (1, 50, 1)
# then simply duplicate C in the first and the third dimensions
D = np.repeat(C, 100, axis=0) 
D = np.repeat(D, 100, axis=2)

D is the 3D array you want.

Upvotes: 0

yatu
yatu

Reputation: 88276

You could set keepdims to True in both cases so the resulting shape is broadcastable and use np.broadcast_to to broadcast to the shape of A:

np.broadcast_to(np.mean(np.mean(A,2,keepdims=True),axis=0,keepdims=True), A.shape) 

Note that you can also specify a tuple of axes along which to take the successive means:

np.broadcast_to(np.mean(A,axis=tuple([2,0]), keepdims=True), A.shape)

Upvotes: 1

Related Questions