首页 文章

repmat函数无法正常工作

提问于
浏览
1

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

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 回答

  • 5

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

    在您的示例中,您需要使用 repmat 创建大小为 4 x 3 的矩阵

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

    在这里,您需要在第一维中重复矩阵 mean ,在第二维中重复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
    

相关问题