Short answer: the built-in ARRAYFUN function 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 works with elements of cell arrays) and STRUCTFUN (which works with each field of the structure).
However, these functions are often not needed if you take advantage of vectorization, in particular using arithmetic operators . For the example you specified, 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 work through elements (for example, adding a scalar value to a vector), while other operators have special syntax for an elementary operation (indicated by the β.β Symbol before the operator). Many functions in MATLAB are designed to work with vector and matrix arguments using elementary operations and, therefore, do not require map functions.
To summarize, here are a few 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
Of course, for such a simple operation, option No. 1 is the most reasonable choice.
gnovice Jun 11 '09 at 19:48 2009-06-11 19:48
source share