MATLAB 用给定向量减去矩阵的每一行
MATLAB subtract every row of matrix by a given vector
让
M = | 1 2 3 |
| 4 5 6 |
| 7 8 9 |
和
V = | 1 1 1 |
我想从 M 的每一行中减去 V,这样 M 应该看起来像
M = | 0 1 2 |
| 3 4 5 |
| 6 7 8 |
如果不使用 for,我如何做到这一点,有没有直接的命令?
>> M = [1 2 3; 4 5 6; 7 8 9];
>> V = [1 1 1];
>> MV = M-repmat(V,size(M,1),1)
MV =
0 1 2
3 4 5
6 7 8
调用 repmat 将向量 V 重复 M 中的行数。
用户beaker pointed out that an even simpler (though a bit obscure) syntax works in recent versions of MATLAB. If you subtract a vector from a matrix, MATLAB will extend the vector to match the size of the matrix as long as one dimension of vector matches the matrix dimensions. See Compatible Array Sizes for Basic Operations。
>> M-V
ans =
0 1 2
3 4 5
6 7 8
当然,如果知道V会包含全1,解法就更简单了:
>> MV = M-1
MV =
0 1 2
3 4 5
6 7 8
您也可以使用bsxfun。
M = [1 2 3 ; 4 5 6 ; 7 8 9] ;
V = [1 1 1] ;
iwant = bsxfun(@minus,M,V)
让
M = | 1 2 3 |
| 4 5 6 |
| 7 8 9 |
和
V = | 1 1 1 |
我想从 M 的每一行中减去 V,这样 M 应该看起来像
M = | 0 1 2 |
| 3 4 5 |
| 6 7 8 |
如果不使用 for,我如何做到这一点,有没有直接的命令?
>> M = [1 2 3; 4 5 6; 7 8 9];
>> V = [1 1 1];
>> MV = M-repmat(V,size(M,1),1)
MV =
0 1 2
3 4 5
6 7 8
调用 repmat 将向量 V 重复 M 中的行数。
用户beaker pointed out that an even simpler (though a bit obscure) syntax works in recent versions of MATLAB. If you subtract a vector from a matrix, MATLAB will extend the vector to match the size of the matrix as long as one dimension of vector matches the matrix dimensions. See Compatible Array Sizes for Basic Operations。
>> M-V
ans =
0 1 2
3 4 5
6 7 8
当然,如果知道V会包含全1,解法就更简单了:
>> MV = M-1
MV =
0 1 2
3 4 5
6 7 8
您也可以使用bsxfun。
M = [1 2 3 ; 4 5 6 ; 7 8 9] ;
V = [1 1 1] ;
iwant = bsxfun(@minus,M,V)