Code covered by the BSD License  

Highlights from
apply

3.25

3.2 | 4 ratings Rate this file 1 Download (last 30 days) File Size: 1.68 KB File ID: #16467

apply

by Stephen Lienhard

 

19 Sep 2007 (Updated 16 Nov 2007)

Apply a function looping over a dimension of a matrix

| Watch this File

File Information
Description

This function should help when it is difficult to generalize a function to operate on all dimensions.

Examples
--------
Take the eig of each page in the 3rd dimension

b = apply(@eig,rand(4,4,3),3,'uni',0)

Normalize each column
b = apply(@norm, rand(5,3), 2)

Normalize each row
b = apply(@norm, rand(5,3), 1)

MATLAB release MATLAB 7.5 (R2007b)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (5)
20 Sep 2007 Jos x@y.z

Do not waste bandwidth with something unfinished ...

20 Sep 2007 Jeremy Spear

Examples worked fine. I'll refine rating after error checking and documentation completed.

28 Sep 2007 Marc Cott

Excellent tool.

09 Apr 2008 Keith Bensar

Good for clear code but doesn't increase speed.

22 Jul 2010 Ged Ridgway

This looks like a useful helper-function to me. I have what I hope is a complementary helper-function
http://www.mathworks.com/matlabcentral/fileexchange/28255
that can be used when you want to apply a function to vectors along a dimension, rather than (potentially higher dimensional) arrays perpendicular to that dimension.

To clarify the differences, with a 3d array:
  r = randn(4,4,4);
the second of the four elements returned by:
  n = apply(@norm, r, 3)
gives the matrix norm of the second matrix:
  norm(r(:,:,2)
where matrices are stacked in the third dimension.

In contrast,
  n = dimfunc(@norm, r, 3)
gives you a 4-by-4 matrix of the vector norms, for vectors running along the third dimension, e.g. element n(2,3) equals:
  norm(squeeze(r(2,3,:)))

I hope that both functions will be useful for simplifying code to handle nD arrays.

Please login to add a comment or rating.
Updates
16 Nov 2007

Added error checking.

Tag Activity for this File
Tag Applied By Date/Time
matrices Stephen Lienhard 22 Oct 2008 09:27:43
arrayfun Stephen Lienhard 22 Oct 2008 09:27:43
margin Stephen Lienhard 22 Oct 2008 09:27:43
map Stephen Lienhard 22 Oct 2008 09:27:43
functional Stephen Lienhard 22 Oct 2008 09:27:43
loop Stephen Lienhard 22 Oct 2008 09:27:43
cellfun Stephen Lienhard 23 Oct 2008 21:51:34
bsxfun Stephen Lienhard 06 Jan 2010 14:08:11

Contact us at files@mathworks.com