% To run the examples in this section, create a nonscalar structure array with arrays of different sizes in field f1.

s(1).f1 = rand(3, 6);

s(2).f1 = magic(12);

s(3).f1 = ones(5, 10);

% Count the number of elements in each f1 field.

counts = arrayfun(@(x) numel(x.f1), s)

% The syntax @(x) creates an anonymous function. This code returns%

% counts =

% 18 144 50

% Compute the size of each array in the f1 fields.

[nrows, ncols] = arrayfun(@(x) size(x.f1), s)

% This code returns

%

% nrows =

% 3 12 5

% ncols =

% 6 12 10

% Compute the mean of each column in the f1 fields of s. Because the output is nonscalar, set UniformOutput to false.

averages = arrayfun(@(x) mean(x.f1), s, 'UniformOutput', false)

% This code returns

%

% averages =

% [1x6 double] [1x12 double] [1x10 double]

% Create additional nonscalar structures t and u, and test for equality between the arrays in fields f1 across structures s, t, and u.

t = s; t(1).f1(:)=0;

u = s; u(2).f1(:)=0;

same = arrayfun(@(x,y) isequal(x.f1, y.f1), s, t)

% This code returns

% same =

% 0 1 1

same = arrayfun(@(x,y,z) isequal(x.f1, y.f1, z.f1), s, t, u)

% This code returns

% same =

% 0 0 1

使用例子:

1.将十进制矩阵转化为二进制矩阵

定义转换函数 transform=@(x) dec2bin(x)

初始矩阵 A=[1 2 3; 4 5 6]

目的矩阵及转化过程C=arrayfun(transform,A,'UniformOutput',false)

上图

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐