MATLAB 中的映射函数? [英] Map function in MATLAB?
问题描述
我对 MATLAB 没有 Map 函数感到有点惊讶,所以我自己开发了一个,因为我离不开它.有没有更好的版本?是否有我缺少的某种标准的 MATLAB 函数式编程库?
I'm a little surprised that MATLAB doesn't have a Map function, so I hacked one together myself since it's something I can't live without. Is there a better version out there? Is there a somewhat-standard functional programming library for MATLAB out there that I'm missing?
function results = map(f,list)
% why doesn't MATLAB have a Map function?
results = zeros(1,length(list));
for k = 1:length(list)
results(1,k) = f(list(k));
end
end
用法是例如
map( @(x)x^2,1:10)
推荐答案
简短的回答:内置函数 arrayfun
与您的 map
函数对数字数组所做的完全一样:
The short answer: the built-in function arrayfun
does exactly what your map
function does for numeric arrays:
>> y = arrayfun(@(x) x^2, 1:10)
y =
1 4 9 16 25 36 49 64 81 100
还有两个类似的内置函数:cellfun
(对元胞数组的元素进行操作)和 structfun
(对结构的每个字段进行操作).
There are two other built-in functions that behave similarly: cellfun
(which operates on elements of cell arrays) and structfun
(which operates on each field of a structure).
但是,如果您利用矢量化,特别是使用元素化算术运算符.对于您给出的示例,矢量化解决方案是:
However, these functions are often not necessary if you take advantage of vectorization, specifically using element-wise arithmetic operators. For the example you gave, a vectorized solution would be:
>> x = 1:10;
>> y = x.^2
y =
1 4 9 16 25 36 49 64 81 100
某些操作会自动跨元素操作(例如向向量添加标量值),而其他操作符具有用于元素操作的特殊语法(由操作符前的 .
表示).MATLAB 中的许多内置函数旨在使用逐元素运算(通常应用于给定维度,例如 sum
和 mean
例如),因此不需要地图功能.
Some operations will automatically operate across elements (like adding a scalar value to a vector) while others operators have a special syntax for element-wise operation (denoted by a .
before the operator). Many built-in functions in MATLAB are designed to operate on vector and matrix arguments using element-wise operations (often applied to a given dimension, such as sum
and mean
for example), and thus don't require map functions.
总而言之,这里有一些不同的方法来对数组中的每个元素进行平方:
To summarize, here are some different ways to square each element in an array:
x = 1:10; % Sample array
f = @(x) x.^2; % Anonymous function that squares each element of its input
% Option #1:
y = x.^2; % Use the element-wise power operator
% Option #2:
y = f(x); % Pass a vector to f
% Option #3:
y = arrayfun(f, x); % Pass each element to f separately
当然,对于如此简单的操作,选项#1 是最明智(也最有效)的选择.
Of course, for such a simple operation, option #1 is the most sensible (and efficient) choice.
这篇关于MATLAB 中的映射函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!