arrayfun with scalar expansion
Version 3.0 (6.3 KB) by
Matt J
Version of arrayfun which allows argument arrays to have different sizes, so long as they are compatible for scalar expansion.
At the time of this submission, the syntax of arrayfun(),
B = arrayfun(fun,A1,...,An)
requires that all input arrays A1,...,An have the same size (on the CPU, not on the GPU). In this submission, we provide alternatives in which this requirement is relaxed, allowing the input arrays to be of different sizes, so long as they are compatible for scalar expansion. The submission includes two implementations, one which is RAM-conserving (arrayfunLowMem) and one which is liberal with RAM, but somewhat faster (arrayfunHighMem).
A few examples are shown below. Further examples are presented in the Examples tab, with tests of speed performance. Both implementations (arrayfunLowMem and arrayfunHighMem) prove to be considerably faster in these tests than Matlab's native arrayfun command.
>> arrayfunHighMem(@plus, [10,20,30],[4;5])
ans =
14 24 34
15 25 35
>> arrayfunHighMem(@(a,b)[a,b] , [10,20,30],[4;5],'UniformOutput',0)
ans =
2×3 cell array
{[10 4]} {[20 4]} {[30 4]}
{[10 5]} {[20 5]} {[30 5]}
Cite As
Matt J (2026). arrayfun with scalar expansion (https://www.mathworks.com/matlabcentral/fileexchange/182992-arrayfun-with-scalar-expansion), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Created with
R2024b
Compatible with any release
Platform Compatibility
Windows macOS LinuxTags
Discover Live Editor
Create scripts with code, output, and formatted text in a single executable document.
