Matlab 中xxxfun的使用

Matlab 中xxxfun的使用

1、简介

Matlab中的xxxfun是对指定数据类型的操作,可以简化掉循环,通过函数句柄的方式对数据进行操作

函数名称适用数据类型
cellfun对元胞数组中的每个元胞应用函数,将输出串联成输出数组
arrayfun将函数应用于每个数组元素
structfun对标量结构体的每个字段应用函数

2、cellfun

  • 函数应用于元胞数组

    C = {1:10, [2; 4; 6], []}
    A = cellfun(@mean,C)
    >>> A = 1×3
    
        5.5000    4.0000       NaN
    
  • 将函数应用于字符串数组中的字符

    C = {'Monday','Tuesday','Wednesday','Thursday','Friday'}
    A = cellfun(@(x) x(1:3),C,'UniformOutput',false)
    >>> A = 1x5 cell
        {'Mon'}    {'Tue'}    {'Wed'}    {'Thu'}    {'Fri'}
    

3、arrayfun

  • 将函数应用于结构体数组的字段

    S(1).f1 = rand(1,5);
    S(2).f1 = rand(1,10);
    S(3).f1 = rand(1,15)
    A = arrayfun(@(x) mean(x.f1), S)
    >>>> A = 1×3
    
        0.6786    0.6216    0.6069
    
    • 以元胞数组的形式返回每列的均值
    S(1).f1 = rand(3,5);
    S(2).f1 = rand(6,10);
    S(3).f1 = rand(4,2)
    A = arrayfun(@(x) mean(x.f1),S,'UniformOutput',false)
    >>> A=1×3 cell array
        {[0.6158 0.5478 0.5943 0.6977 0.7476]}    {[0.6478 0.6664 0.3723 0.4882 0.4337 0.5536 0.5124 0.4436 0.5641 0.5566]}    {[0.3534 0.5603]}
    
    

4、structfun

  • 将函数应用于结构体的字段

S.f1 = 1:10;
S.f2 = [2; 4; 6];
S.f3 = []
A = structfun(@mean,S)
>>> A = 3×1
    5.5000
    4.0000
    NaN
  • 返回标量结构体
S.f1 = 1:10;
S.f2 = [2 3; 4 5; 6 7];
S.f3 = rand(4,4)
A = structfun(@mean,S,'UniformOutput',false)
>>> A = struct with fields:
    f1: 5.5000
    f2: [4 5]
    f3: [0.6902 0.3888 0.7627 0.5962]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值