arrayfun函数用于对数组中每个元素进行相同的函数操作。
例如,如果进行求平方操作。为避免循环,对于数组可以进行.^操作。即
a=rand(2,2); a2=a.^2; %完成对数组a中每个元素的平方操作。
a=rand(2,2);b=rand(3,3);c=rand(4,4); 如果需要同时对a,b,c数组进行求平方操作。可以通过arrayfun实现 s(1).f1=rand(2,2);s(2).fl=rand(3,3);s(3).f1=rand(4,4);
y=arrayfun(@(x)(x.f1.^2),s,'UniformOutput',false)
以下是MATLAB帮助文档的几个例子。
% 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