下面这句是在百度百科上面看到的非常形象,比官方给出的好,谢谢百度百科bsxfun()函数的编辑作者
“
”
列举第一种情况
例一:矩阵与向量 减法运算@minus
例二:向量与向量 减法运算@minus
例一:矩阵与向量 减法运算@minus >> A = [1 2 10; 1 4 20;1 6 15] A =1 2 10 1 4 20 1 6 15 | >> mean(A) ans = 1 4 15 | >> C = bsxfun(@minus, A, mean(A)) C =0 -2 -5 0 0 5 0 2 0 |
具体计算过程 A = | 为了计算,需要将mean(A)向量,变成与A矩阵大小相同的矩阵3X3, 所以,需要对mean(A)扩充,扩充方式就是,将1X3的向量, 复制三次,变成3X3的矩阵。 >> repmat(mean(A),3,1) ans =1 4 15 1 4 15 1 4 15 | 然后两个矩阵相减 >> A-repmat(mean(A),3,1) |
例二:向量与向量 减法运算@minus >> a=[1 2 3] | >> b=[2 3 4]' b = 2 3 4 | c= bsxfun(@minus, a, b) c = -1 0 1 -2 -1 0 -3 -2 -1 |
具体计算过程 因为向量a与b分别是1X3与3X1,为了能够相减,则a需要扩充为3X3,b与需要扩充为3X3,才能进行计算 >> repmat(a,3,1) | >> repmat(b,1,3) ans = 2 2 2 3 3 3 4 4 4 | >> repmat(a,3,1)-repmat(b,1,3) ans = -1 0 1 -2 -1 0 -3 -2 -1 |
同理 a=[1 2 3],1X3向量; b=b=[2 3 4 5]',4X1向量。则需要都变成4X3的矩阵 a = 1 2 3 b = |
ans = 1 2 31 2 3 1 2 3 1 2 3 | ans = 2 2 2 3 3 3 4 4 4 5 5 5 | >> c= bsxfun(@minus, a, b) c = -1 0 1 -2 -1 0 -3 -2 -1 -4 -3 -2 |
列举第二种情况
bsxfun(@( 数组1,数组2)函数体表达式,数组1,数组2)
fun = @(A,B) A.*(12*B); A = 1:7; B = [0 1/4 1/3 1/2 2/3 3/4 1].'; C = bsxfun(fun,A,B) | >> A = 1:7 A = 1 2 3 4 5 6 7 | >> B = [0 1/4 1/3 1/2 2/3 3/4 1].' >> 12*B ans = 0 3 4 6 8 9 12 |
计算过程,同上面第一种形式一样 | A 扩展为7X7 | B 也扩展为7X7 |
| >> repmat(A,7,1) ans = 1 2 3 4 5 6 7 1 2 3 4 5 6 7 1 2 3 4 5 6 7 1 2 3 4 5 6 7 1 2 3 4 5 6 7 1 2 3 4 5 6 7 1 2 3 4 5 6 7 | >> repmat(B,1,7) ans = 0 0 0 0 0 0 0 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.3333 0.3333 0.3333 0.3333 0.3333 0.3333 0.3333 0.5000 0.5000 0.5000 0.5000 0.5000 0.5000 0.5000 0.6667 0.6667 0.6667 0.6667 0.6667 0.6667 0.6667 0.7500 0.7500 0.7500 0.7500 0.7500 0.7500 0.7500 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 | |
| >> fun = @(A,B) A.*(12*B) fun = @(A,B)A.*(12*B) | 所以计算A.*(12*B) | 先计算12*B ans = |
关于 .*,里面举例说明过,是对应乘 | >> C = bsxfun(fun,A,B) C = 0 0 0 0 0 0 0 3 6 9 12 15 18 21 4 8 12 16 20 24 28 6 12 18 24 30 36 42 8 16 24 32 40 48 56 9 18 27 36 45 54 63 12 24 36 48 60 72 84 |
下面:
给出已定义函数名,来自help matble 我觉得上面给出的解释比help上面给出的更容易理解,希望给了你想要的帮助。
@plus
Plus
@minus
Minus
@times
Array multiply
@rdivide
Right array divide
@ldivide
Left array divide
@power
Array power
@max
Binary maximum
@min
Binary minimum
@rem
Remainder after division
@mod
Modulus after division
@atan2
Four-quadrant inverse tangent; result in radians
@atan2d
Four-quadrant inverse tangent; result in degrees
@hypot
Square root of sum of squares
@eq
Equal
@ne
Not equal
@lt
Less than
@le
Less than or equal to
@gt
Greater than
@ge
Greater than or equal to
@and
Element-wise logical AND
@or
Element-wise logical OR
@xor
Logical exclusive OR
本文介绍了Matlab中的bsxfun函数,包括其在矩阵与向量减法运算以及自定义函数体表达式中的应用。通过实例解析,详细展示了bsxfun的使用方法,如加法、减法、乘法等操作,并提供了与官方帮助文档的对比,便于理解和掌握。
3万+

被折叠的 条评论
为什么被折叠?



