Search code examples
matlabmatrixalgebra

repmat function does not work properly


let us consider following situation,for instance we have given matrix and we want to make zero centered this matrix in columns,so

A=rand(4,3)

A =

    0.6948    0.4387    0.1869
    0.3171    0.3816    0.4898
    0.9502    0.7655    0.4456
    0.0344    0.7952    0.6463

now this two method works properly

A-repmat(mean(A),size(A,1),1)

ans =

    0.1957   -0.1565   -0.2553
   -0.1820   -0.2137    0.0476
    0.4511    0.1703    0.0035
   -0.4647    0.1999    0.2042

and also

bsxfun(@minus,A,mean(A))

ans =

    0.1957   -0.1565   -0.2553
   -0.1820   -0.2137    0.0476
    0.4511    0.1703    0.0035
   -0.4647    0.1999    0.2042

but somehow following method does not work

B=mean(A)

B =

    0.4991    0.5953    0.4421

 A-repmat(B,1,4)

ans =

     0     0     0     0     0     0     0     0     0     0     0     0

i have tried transpose but

A-repmat(B,1,4)'
Error using  - 
Matrix dimensions must agree.

also i have tried following

A-repmat(B,1,3)'
Error using  - 
Matrix dimensions must agree.

>> A-repmat(B,1,3)
Error using  - 
Matrix dimensions must agree.
 so what is problem of  failure of this method?

Solution

  • You are not using proper syntax for the repmat function

    In your example ,You need to create a matrix of size 4 x 3 using repmat

    Now a call to repmat(A,k,j) repeats matrix A k times along the first dimension (i.e vertically) and j times along the second dimension (i.e, horizontally).

    Here, you need to repeat matrix mean 4 times in first dimension and 1 time in second dimension .

    Hence, the correct call to repmat is repmat(mean,4,1)

    repmat(B,4,1)
    
    ans =
    
        0.4991    0.5953    0.4421
        0.4991    0.5953    0.4421
        0.4991    0.5953    0.4421
        0.4991    0.5953    0.4421
    

    It looks like you need to know why your method is failing

    repmat(B,1,4) %// returns a 1x12 matrix while A is 3x4 matrix hence dimensions do not agree while using @minus
    ans =
    
        0.4991    0.5953    0.4421   0.4991    0.5953    0.4421   0.4991    0.5953    0.4421   0.4991    0.5953    0.4421