【Matlab开发】函数bsxfun的使用

【Matlab开发】函数bsxfun的使用

标签:【Matlab开发】

版权声明:本文为博主原创文章,转载请注明出处http://blog.csdn.net/lg1259156776/


说明:当我们想对一个矩阵A的每一列或者每一行与同一个长度相等的向量a进行某些操作(比较大小,乘除等)时,我们只能用循环方法或者利用repmat函数将要操作的向量a复制成和A一样尺寸的矩阵,进而进行操作。从MATLAB R2007a开始,再遇到类似的问题时,我们有了简洁高效的方法,即利用bsxfun函数。


bsxfun函数用法

【函数描述】C=bsxfun(fun,A,B):两个数组间元素逐个计算,fun是函数句柄或者m文件,也可以为如下内置函数

            @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
            @hypot          Square root of sum of squares
            @eq             Equal
            @ne             Not equal
            @lt             Less than
            @le             Less than or equal
            @gt             Greater than
            @ge             Greater than or equal
            @and            Element-wise logical AND
            @or             Element-wise logical OR
            @xor            Logical EXCLUSIVE OR


a = [1,2,3;4,5,6;7,8,9]

a =

     1     2     3
     4     5     6
     7     8     9

>> acol = bsxfun(@times,a,[1 2 4])

acol =

     1     4    12
     4    10    24
     7    16    36



A = magic(5);
>> A

A =

    17    24     1     8    15
    23     5     7    14    16
     4     6    13    20    22
    10    12    19    21     3
    11    18    25     2     9

>> mean(A)

ans =

    13    13    13    13    13

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

A =

     4    11   -12    -5     2
    10    -8    -6     1     3
    -9    -7     0     7     9
    -3    -1     6     8   -10
    -2     5    12   -11    -4

Matlab中repmat函数用法

复制和平铺矩阵
函数 repmat
格式 B = repmat(A,m,n) %将矩阵A复制m×n块,即B由m×n块A平铺而成。
B = repmat(A,[m n]) %与上面一致
B = repmat(A,[m n p…]) %B由m×n×p×…个A块平铺而成
repmat(A,m,n) %当A是一个数a时,该命令产生一个全由a组成的m×n矩阵。


2015-11-25 学习笔记 张朋艺

原文地址:https://www.cnblogs.com/huty/p/8518934.html