repmat函数无法正常工作

时间:2014-06-10 06:46:19

标签: matlab matrix algebra

让我们考虑下面的情况,例如我们已经给出了矩阵,我们希望将这个矩阵置于零列中,所以

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

现在这两种方法正常运行

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

以及

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

但不知何故,以下方法不起作用

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

我尝试了转置,但

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

我也试过

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?

1 个答案:

答案 0 :(得分:5)

您没有为repmat函数使用正确的语法

在您的示例中,您需要使用4 x 3

创建大小为repmat的矩阵

现在,对repmat(A,k,j)的调用沿第一维(即垂直)重复矩阵A k次,沿第二维(即水平)重复j次。

在这里,您需要在第一维中重复矩阵mean 4次,在第二维中重复1次。

因此,正确调用repmat是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

看起来你需要知道你的方法失败的原因

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
相关问题