Q:

Set::write: Error When Creating Function

I'm very new to Mathematica, and I'm getting pretty frustrated with the errors I'm generating when it comes to creating a function. Below, I have a function I'm writing for 'centering' a matrix where rows correspond to examples, columns to features. The aim is to subtract from each element the mean of the column to which it belongs. 
centerdata[datamat_] := (

  numdatapoints = 
   Dimensions[datamat][[1]](*Get number of datapoints*)

     numberfeatures = 
    Dimensions[datamat[[1]]][[1]](*Get number of datapoints*)

      columnmean = ((Total[datamat])/numdatapoints)

      For[i = 1, i < numdatapoints + 1, i++, (* For each row*)

       For[j = 1, j < numfeatures + 1, j++, (* For each element*)

              datum = datamat[[i]][[j]];
         newval = (datum - (colmean[[j]]));
         ReplacePart[datamat, {i, j} -> newval];
         ];
       ];

  Return[datamat];
  )

Running this function for a matrix, I get the following error:
"Set::write: Tag Times in 4 {5.84333,3.054,3.75867,1.19867} is Protected. >>
Set::write: "Tag Times in 4\ 150 is Protected." 
Where {5.84333,3.054,3.75867,1.19867} is the first example in the data matrix and 150 is the number of examples in the matrix (I'm using the famous iris dataset, for anyone interested). These errors correspond to this code:
numdatapoints = Dimensions[datamat][[1]](*Get number of datapoints*)

numberfeatures = Dimensions[datamat[[1]]][[1]](*Get number of datapoints*)

Googling and toying with this error hasn't helped much as the replies in general relate to multiplication, which clearly isn't being done here.

A:

Given a table (tab) of data the function Mean[tab] will return a list of the means of each column.  Next, you want to subtract this (element-wise) from each row in the table, try this:
Map[Plus[-Mean[tab],#]&,tab]

I have a feeling that there is probably either an intrinsic statistical function to do this in one statement or that I am blind to a much simpler solution.
Since you are a beginner I suggest that you immediately read the documentation for:

Map, which is one of the fundamental operators in functional programming languages such as Mathematica pretends to be; and
pure functions whose use involves the cryptic symbols # and &.

If you are writing loops in Mathematica programs you are almost certainly mis-using the system.

