MATLAB 中的映射函数
map函数基本上采用数组的元素并将函数应用于每个元素。结果输出与数组具有相同的形状,但值是函数的结果。在MATLAB中,有一个类似的函数叫做arrayfun(),我们可以用它来实现同样的任务。此arrayfunc的输出可以具有任何数据类型。
句法:
X = arrayfun(func,A)
参数:
- fun: It is a function that we are going to map on each element of the array A.
- A: It is the array on which we are going to map the function.
- X: In variable X the output is going to be stored from the map function.
这里, arrayfun(funct,A)将函数funct应用于数组A的元素。然后, arrayfun将funct的输出连接到输出数组X 中,这样对于A的第 i 个元素, X(i) = funct(A(i ))。
输入参数本功能是一个函数句柄,它有一个输入参数,并返回一个标量的函数。
让我们举一个例子来更好地理解:
示例 1:
Matlab
% MAP function in MatLab
% creating a dummy array
% on which we are going to map a function
A = [1,2,3,4,5,6,7,8,9,10];
% Applying arrayfun()
output = arrayfun(@(x) x*2, A);
% displaying output
fprintf("output is :");
disp(output);
Matlab
% MAP function in MatLab
% creating two dummy arrays
% on which we are going to map a function
A = [1,2,3,4,5];
B = [6,7,8,9,10];
% Applying arrayfun()
output = arrayfun(@(x,y) x*y, A,B);
% displaying output
fprintf("Product is :");
disp(output);
输出:
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/Map_Function_in_MATLAB_0.jpg)
应用 arrayfun()
在上面的函数,首先我们创建了一个数组,我们要将自定义函数映射到该数组。自定义是x*2,即将数组中的每个元素乘以 2。
然后我们使用arrayfun(@(x) x*2, A),让我们分解这个语句,这里 arrayfun(fun,array) 是将函数映射到数组的一般语法。我们在语句中使用@(x)和x*2 ,其中x*2是我们正在应用的自定义函数, @(x)是作为数组A 的每个元素。之后,我们将存储输出到一个变量,然后使用fprintf函数在显示器上打印一个字符串,并使用disp函数显示输出。
示例 2:
MATLAB
% MAP function in MatLab
% creating two dummy arrays
% on which we are going to map a function
A = [1,2,3,4,5];
B = [6,7,8,9,10];
% Applying arrayfun()
output = arrayfun(@(x,y) x*y, A,B);
% displaying output
fprintf("Product is :");
disp(output);
输出:
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/Map_Function_in_MATLAB_1.jpg)
使用 arrayfun() 生成两个数组