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]

640

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



