Is there a way to apply a function to each element of a matrix?

I am attempting to do some analysis of images that involves rendering them as EDIT: matrices.

Is there some way to apply functions to each element of a matrix in the same way the “Map” function works for lists?

What about

  #^2 & /@ {{1, 2}, {3, 4}}

or

N[Sin[#]] & /@ {{1, 2}, {3, 4}}

This following command should add noise to each pixel; well actually to each of the RGB channels.

 Manipulate[
 Mod[# + RandomReal[delta, 512], 
     1] & /@ (ExampleData[{"TestImage", "Lena"}] // ImageData) // 
  Image, {delta, 0, 0.5}]

This gives:

noise2.gif

A much more interesting example is given in this fantastic blog post: Doing spy stuff with Mathematica.

M.

Map can take a “levelspec”

In[1]:= Map[f, {{a, b}, {c, d, e}}, {2}]

Out[1]= {{f[a], f[b]}, {f[c], f[d], f[e]}}

Thanks! I did end up using the levelspec on the Map command.

Do you know about list-ability of a function? You can set that attribute to avoid explicit mapping.

SetAttributes[f, Listable];
f[{{x, y}, {a, b}}]

{{f[x], f[y]}, {f[a], f[b]}}

You may want to take a look at ImageApply as well. It can transform each pixel of an image using an arbitrary function. It is equivalent to converting the image to a matrix and mapping a function at level 2.

(Strinctly speaking this is true for grascale images. Colour images are processed per channel.)