MATLAB中的地图功能? [英] Map function in MATLAB?
问题描述
我对MATLAB没有Map函数感到有点惊讶,所以我自己一起砍了一个,因为这是我不能没有的东西。那里有更好的版本吗?
有没有一个标准的MATLAB函数式编程库? function results = map(f,list)
%为什么MATLAB没有Map函数?
results = zeros(1,length(list));
for k = 1:length(list)
results(1,k)= f(list(k));
结束
结束
用法例如
map(@(x)x ^ 2,1:10)
简短回答:内置函数 arrayfun
完全符合你的 map
函数为数值数组做准备:
>> y = arrayfun(@(x)x ^ 2,1:10)
y =
1 4 9 16 25 36 49 64 81 100
还有两个其他内置函数的行为相似: cellfun
(它对单元格数组的元素进行操作)和 structfun
(它在结构的每个字段上运行) 。
但是,如果您利用矢量化,通常不需要使用这些函数,特别是使用基于元素的算术运算符。对于你给出的例子,一个矢量化的解决方案是:
>> x = 1:10;
>> y = x。^ 2
y =
1 4 9 16 25 36 49 64 81 100
有些操作会自动跨元素操作(例如向向量添加标量值),而其他操作符具有特殊的元素操作语法(由
在操作员面前)。 MATLAB中的许多内置函数被设计为使用基于元素的操作来操作矢量和矩阵参数(通常应用于给定维度,比如 sum
和 mean
),因此不需要映射函数。
总结一下,下面是一些不同的方法来将每个元素放在数组中:
x = 1:10; %示例数组
f = @(x)x。^ 2; %将其输入的每个元素平方的匿名函数
%选项#1:
y = x。^ 2; %使用基于元素的电力操作符
%选项#2:
y = f(x); %将矢量传递给f
%选项#3:
y = arrayfun(f,x); %将每个元素分别传递给f
当然,对于如此简单的操作,选项#1是最合理(高效)的选择。
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
usage would be e.g.
map( @(x)x^2,1:10)
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
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
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
Of course, for such a simple operation, option #1 is the most sensible (and efficient) choice.
这篇关于MATLAB中的地图功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!