Code covered by the BSD License  

Highlights from
DimFunc

Be the first to rate this file! 2 Downloads (last 30 days) File Size: 2.35 KB File ID: #28255

DimFunc

by Ged Ridgway

 

21 Jul 2010

Apply a function along any dimension of an n-D array.

| Watch this File

File Information
Description

DimFunc provides behaviour like sum(X, dim) for functions that don't already handle dimension arguments.

The function need only handle vectors (or 2d matrices, if faster) and may return vector output. The size of the output matches that of the input, except that the chosen dimension changes to match the length of the output of the function (often, but not necessarily, 1).

Usage:
 out = dimfunc(func, data, dim, out_length, handles_matrix)
Input:
 func - function handle (or function name string) to apply
 data - input array, of arbitrary dimensionality and size
 dim - dimension to operate along, defaulting to first non-singleton dimension
Optional inputs:
 out_length - length of vector output from func (default: 1)
 handles_matrix - Boolean flag, if true, assume func will operate on columns of a matrix input (default: false)

Example:
 v = randn(10,10,3); % a 10x10 array of random 3-vectors
 n = sqrt(sum(v.^2, 3)); % a 10x10 matrix of their norms
 N = dimfunc('norm', v, 3); % the same as n, but perhaps clearer

Note that norm does not allow the "dim behaviour" that sum does; in this case, it is easy enough to use sum directly, but for other functions there might be no simple alternatives. I hope that dimfunc will make it slightly easier for others to write functions by removing the need to worry about n-D arrays, instead just handling either 1 or 2-d inputs.

Acknowledgements

The author wishes to acknowledge the following in the creation of this submission:
reshape2matrix.m v1.0 (Oct 2009)

MATLAB release MATLAB 7.1.0 (R14SP3)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (1)
22 Jul 2010 Ged Ridgway

See also:
http://www.mathworks.com/matlabcentral/fileexchange/16467-apply
which performs a complementary function. I have written a comment there that I hope will clarify the difference between the two.

Please login to add a comment or rating.
Tag Activity for this File
Tag Applied By Date/Time
multidimensional arrays Ged Ridgway 22 Jul 2010 10:55:27
nd Ged Ridgway 22 Jul 2010 10:55:27
first nonsingleton dimension Ged Ridgway 22 Jul 2010 10:55:27
dim Ged Ridgway 22 Jul 2010 10:55:27

Contact us at files@mathworks.com