Matlab中arrayfun函数

本文介绍了MATLAB中arrayfun函数的应用,展示了如何利用该函数对不同大小的数组进行统一的操作,如求平方、计数、计算平均值等,特别适用于需要对多个数组执行相同运算的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值